OSDN Git Service

PR c++/40595
[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 "pointer-set.h"
36 #include "flags.h"
37 #include "c-common.h"
38 #include "cp-tree.h"
39 #include "cp-objcp-common.h"
40 #include "tree-inline.h"
41 #include "decl.h"
42 #include "output.h"
43 #include "except.h"
44 #include "toplev.h"
45 #include "rtl.h"
46 #include "timevar.h"
47 #include "tree-iterator.h"
48 #include "vecprim.h"
49
50 /* The type of functions taking a tree, and some additional data, and
51    returning an int.  */
52 typedef int (*tree_fn_t) (tree, void*);
53
54 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
55    instantiations have been deferred, either because their definitions
56    were not yet available, or because we were putting off doing the work.  */
57 struct GTY (()) pending_template {
58   struct pending_template *next;
59   struct tinst_level *tinst;
60 };
61
62 static GTY(()) struct pending_template *pending_templates;
63 static GTY(()) struct pending_template *last_pending_template;
64
65 int processing_template_parmlist;
66 static int template_header_count;
67
68 static GTY(()) tree saved_trees;
69 static VEC(int,heap) *inline_parm_levels;
70
71 static GTY(()) struct tinst_level *current_tinst_level;
72
73 static GTY(()) tree saved_access_scope;
74
75 /* Live only within one (recursive) call to tsubst_expr.  We use
76    this to pass the statement expression node from the STMT_EXPR
77    to the EXPR_STMT that is its result.  */
78 static tree cur_stmt_expr;
79
80 /* A map from local variable declarations in the body of the template
81    presently being instantiated to the corresponding instantiated
82    local variables.  */
83 static htab_t local_specializations;
84
85 /* Contains canonical template parameter types. The vector is indexed by
86    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
87    TREE_LIST, whose TREE_VALUEs contain the canonical template
88    parameters of various types and levels.  */
89 static GTY(()) VEC(tree,gc) *canonical_template_parms;
90
91 #define UNIFY_ALLOW_NONE 0
92 #define UNIFY_ALLOW_MORE_CV_QUAL 1
93 #define UNIFY_ALLOW_LESS_CV_QUAL 2
94 #define UNIFY_ALLOW_DERIVED 4
95 #define UNIFY_ALLOW_INTEGER 8
96 #define UNIFY_ALLOW_OUTER_LEVEL 16
97 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
98 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
99
100 static void push_access_scope (tree);
101 static void pop_access_scope (tree);
102 static bool resolve_overloaded_unification (tree, tree, tree, tree,
103                                             unification_kind_t, int);
104 static int try_one_overload (tree, tree, tree, tree, tree,
105                              unification_kind_t, int, bool);
106 static int unify (tree, tree, tree, tree, int);
107 static void add_pending_template (tree);
108 static int push_tinst_level (tree);
109 static void pop_tinst_level (void);
110 static tree reopen_tinst_level (struct tinst_level *);
111 static tree tsubst_initializer_list (tree, tree);
112 static tree get_class_bindings (tree, tree, tree);
113 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
114                                    bool, bool);
115 static void tsubst_enum (tree, tree, tree);
116 static tree add_to_template_args (tree, tree);
117 static tree add_outermost_template_args (tree, tree);
118 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
119 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
120                                              tree);
121 static int type_unification_real (tree, tree, tree, const tree *,
122                                   unsigned int, int, unification_kind_t, int);
123 static void note_template_header (int);
124 static tree convert_nontype_argument_function (tree, tree);
125 static tree convert_nontype_argument (tree, tree);
126 static tree convert_template_argument (tree, tree, tree,
127                                        tsubst_flags_t, int, tree);
128 static int for_each_template_parm (tree, tree_fn_t, void*,
129                                    struct pointer_set_t*, bool);
130 static tree expand_template_argument_pack (tree);
131 static tree build_template_parm_index (int, int, int, tree, tree);
132 static bool inline_needs_template_parms (tree);
133 static void push_inline_template_parms_recursive (tree, int);
134 static tree retrieve_local_specialization (tree);
135 static void register_local_specialization (tree, tree);
136 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
137 static int mark_template_parm (tree, void *);
138 static int template_parm_this_level_p (tree, void *);
139 static tree tsubst_friend_function (tree, tree);
140 static tree tsubst_friend_class (tree, tree);
141 static int can_complete_type_without_circularity (tree);
142 static tree get_bindings (tree, tree, tree, bool);
143 static int template_decl_level (tree);
144 static int check_cv_quals_for_unify (int, tree, tree);
145 static void template_parm_level_and_index (tree, int*, int*);
146 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
147 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
148 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
149 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
150 static void regenerate_decl_from_template (tree, tree);
151 static tree most_specialized_class (tree, tree);
152 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
153 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
154 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
155 static bool check_specialization_scope (void);
156 static tree process_partial_specialization (tree);
157 static void set_current_access_from_decl (tree);
158 static tree get_template_base (tree, tree, tree, tree);
159 static tree try_class_unification (tree, tree, tree, tree);
160 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
161                                            tree, tree);
162 static bool template_template_parm_bindings_ok_p (tree, tree);
163 static int template_args_equal (tree, tree);
164 static void tsubst_default_arguments (tree);
165 static tree for_each_template_parm_r (tree *, int *, void *);
166 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
167 static void copy_default_args_to_explicit_spec (tree);
168 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
169 static int eq_local_specializations (const void *, const void *);
170 static bool dependent_template_arg_p (tree);
171 static bool any_template_arguments_need_structural_equality_p (tree);
172 static bool dependent_type_p_r (tree);
173 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
174 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
175 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
176 static tree tsubst_decl (tree, tree, tsubst_flags_t);
177 static void perform_typedefs_access_check (tree tmpl, tree targs);
178 static void append_type_to_template_for_access_check_1 (tree, tree, tree);
179
180 /* Make the current scope suitable for access checking when we are
181    processing T.  T can be FUNCTION_DECL for instantiated function
182    template, or VAR_DECL for static member variable (need by
183    instantiate_decl).  */
184
185 static void
186 push_access_scope (tree t)
187 {
188   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
189               || TREE_CODE (t) == VAR_DECL);
190
191   if (DECL_FRIEND_CONTEXT (t))
192     push_nested_class (DECL_FRIEND_CONTEXT (t));
193   else if (DECL_CLASS_SCOPE_P (t))
194     push_nested_class (DECL_CONTEXT (t));
195   else
196     push_to_top_level ();
197
198   if (TREE_CODE (t) == FUNCTION_DECL)
199     {
200       saved_access_scope = tree_cons
201         (NULL_TREE, current_function_decl, saved_access_scope);
202       current_function_decl = t;
203     }
204 }
205
206 /* Restore the scope set up by push_access_scope.  T is the node we
207    are processing.  */
208
209 static void
210 pop_access_scope (tree t)
211 {
212   if (TREE_CODE (t) == FUNCTION_DECL)
213     {
214       current_function_decl = TREE_VALUE (saved_access_scope);
215       saved_access_scope = TREE_CHAIN (saved_access_scope);
216     }
217
218   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
219     pop_nested_class ();
220   else
221     pop_from_top_level ();
222 }
223
224 /* Do any processing required when DECL (a member template
225    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
226    to DECL, unless it is a specialization, in which case the DECL
227    itself is returned.  */
228
229 tree
230 finish_member_template_decl (tree decl)
231 {
232   if (decl == error_mark_node)
233     return error_mark_node;
234
235   gcc_assert (DECL_P (decl));
236
237   if (TREE_CODE (decl) == TYPE_DECL)
238     {
239       tree type;
240
241       type = TREE_TYPE (decl);
242       if (type == error_mark_node)
243         return error_mark_node;
244       if (MAYBE_CLASS_TYPE_P (type)
245           && CLASSTYPE_TEMPLATE_INFO (type)
246           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
247         {
248           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
249           check_member_template (tmpl);
250           return tmpl;
251         }
252       return NULL_TREE;
253     }
254   else if (TREE_CODE (decl) == FIELD_DECL)
255     error ("data member %qD cannot be a member template", decl);
256   else if (DECL_TEMPLATE_INFO (decl))
257     {
258       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
259         {
260           check_member_template (DECL_TI_TEMPLATE (decl));
261           return DECL_TI_TEMPLATE (decl);
262         }
263       else
264         return decl;
265     }
266   else
267     error ("invalid member template declaration %qD", decl);
268
269   return error_mark_node;
270 }
271
272 /* Return the template info node corresponding to T, whatever T is.  */
273
274 tree
275 get_template_info (tree t)
276 {
277   tree tinfo = NULL_TREE;
278
279   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
280     tinfo = DECL_TEMPLATE_INFO (t);
281
282   if (!tinfo && TREE_CODE (t) == TYPE_DECL)
283     t = TREE_TYPE (t);
284
285   if (TAGGED_TYPE_P (t))
286     tinfo = TYPE_TEMPLATE_INFO (t);
287
288   return tinfo;
289 }
290
291 /* Returns the template nesting level of the indicated class TYPE.
292
293    For example, in:
294      template <class T>
295      struct A
296      {
297        template <class U>
298        struct B {};
299      };
300
301    A<T>::B<U> has depth two, while A<T> has depth one.
302    Both A<T>::B<int> and A<int>::B<U> have depth one, if
303    they are instantiations, not specializations.
304
305    This function is guaranteed to return 0 if passed NULL_TREE so
306    that, for example, `template_class_depth (current_class_type)' is
307    always safe.  */
308
309 int
310 template_class_depth (tree type)
311 {
312   int depth;
313
314   for (depth = 0;
315        type && TREE_CODE (type) != NAMESPACE_DECL;
316        type = (TREE_CODE (type) == FUNCTION_DECL)
317          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
318     {
319       tree tinfo = get_template_info (type);
320
321       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
322           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
323         ++depth;
324     }
325
326   return depth;
327 }
328
329 /* Subroutine of maybe_begin_member_template_processing.
330    Returns true if processing DECL needs us to push template parms.  */
331
332 static bool
333 inline_needs_template_parms (tree decl)
334 {
335   if (! DECL_TEMPLATE_INFO (decl))
336     return false;
337
338   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
339           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
340 }
341
342 /* Subroutine of maybe_begin_member_template_processing.
343    Push the template parms in PARMS, starting from LEVELS steps into the
344    chain, and ending at the beginning, since template parms are listed
345    innermost first.  */
346
347 static void
348 push_inline_template_parms_recursive (tree parmlist, int levels)
349 {
350   tree parms = TREE_VALUE (parmlist);
351   int i;
352
353   if (levels > 1)
354     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
355
356   ++processing_template_decl;
357   current_template_parms
358     = tree_cons (size_int (processing_template_decl),
359                  parms, current_template_parms);
360   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
361
362   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
363                NULL);
364   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
365     {
366       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
367
368       if (parm == error_mark_node)
369         continue;
370
371       gcc_assert (DECL_P (parm));
372
373       switch (TREE_CODE (parm))
374         {
375         case TYPE_DECL:
376         case TEMPLATE_DECL:
377           pushdecl (parm);
378           break;
379
380         case PARM_DECL:
381           {
382             /* Make a CONST_DECL as is done in process_template_parm.
383                It is ugly that we recreate this here; the original
384                version built in process_template_parm is no longer
385                available.  */
386             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
387                                     CONST_DECL, DECL_NAME (parm),
388                                     TREE_TYPE (parm));
389             DECL_ARTIFICIAL (decl) = 1;
390             TREE_CONSTANT (decl) = 1;
391             TREE_READONLY (decl) = 1;
392             DECL_INITIAL (decl) = DECL_INITIAL (parm);
393             SET_DECL_TEMPLATE_PARM_P (decl);
394             pushdecl (decl);
395           }
396           break;
397
398         default:
399           gcc_unreachable ();
400         }
401     }
402 }
403
404 /* Restore the template parameter context for a member template or
405    a friend template defined in a class definition.  */
406
407 void
408 maybe_begin_member_template_processing (tree decl)
409 {
410   tree parms;
411   int levels = 0;
412
413   if (inline_needs_template_parms (decl))
414     {
415       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
416       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
417
418       if (DECL_TEMPLATE_SPECIALIZATION (decl))
419         {
420           --levels;
421           parms = TREE_CHAIN (parms);
422         }
423
424       push_inline_template_parms_recursive (parms, levels);
425     }
426
427   /* Remember how many levels of template parameters we pushed so that
428      we can pop them later.  */
429   VEC_safe_push (int, heap, inline_parm_levels, levels);
430 }
431
432 /* Undo the effects of maybe_begin_member_template_processing.  */
433
434 void
435 maybe_end_member_template_processing (void)
436 {
437   int i;
438   int last;
439
440   if (VEC_length (int, inline_parm_levels) == 0)
441     return;
442
443   last = VEC_pop (int, inline_parm_levels);
444   for (i = 0; i < last; ++i)
445     {
446       --processing_template_decl;
447       current_template_parms = TREE_CHAIN (current_template_parms);
448       poplevel (0, 0, 0);
449     }
450 }
451
452 /* Return a new template argument vector which contains all of ARGS,
453    but has as its innermost set of arguments the EXTRA_ARGS.  */
454
455 static tree
456 add_to_template_args (tree args, tree extra_args)
457 {
458   tree new_args;
459   int extra_depth;
460   int i;
461   int j;
462
463   extra_depth = TMPL_ARGS_DEPTH (extra_args);
464   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
465
466   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
467     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
468
469   for (j = 1; j <= extra_depth; ++j, ++i)
470     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
471
472   return new_args;
473 }
474
475 /* Like add_to_template_args, but only the outermost ARGS are added to
476    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
477    (EXTRA_ARGS) levels are added.  This function is used to combine
478    the template arguments from a partial instantiation with the
479    template arguments used to attain the full instantiation from the
480    partial instantiation.  */
481
482 static tree
483 add_outermost_template_args (tree args, tree extra_args)
484 {
485   tree new_args;
486
487   /* If there are more levels of EXTRA_ARGS than there are ARGS,
488      something very fishy is going on.  */
489   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
490
491   /* If *all* the new arguments will be the EXTRA_ARGS, just return
492      them.  */
493   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
494     return extra_args;
495
496   /* For the moment, we make ARGS look like it contains fewer levels.  */
497   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
498
499   new_args = add_to_template_args (args, extra_args);
500
501   /* Now, we restore ARGS to its full dimensions.  */
502   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
503
504   return new_args;
505 }
506
507 /* Return the N levels of innermost template arguments from the ARGS.  */
508
509 tree
510 get_innermost_template_args (tree args, int n)
511 {
512   tree new_args;
513   int extra_levels;
514   int i;
515
516   gcc_assert (n >= 0);
517
518   /* If N is 1, just return the innermost set of template arguments.  */
519   if (n == 1)
520     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
521
522   /* If we're not removing anything, just return the arguments we were
523      given.  */
524   extra_levels = TMPL_ARGS_DEPTH (args) - n;
525   gcc_assert (extra_levels >= 0);
526   if (extra_levels == 0)
527     return args;
528
529   /* Make a new set of arguments, not containing the outer arguments.  */
530   new_args = make_tree_vec (n);
531   for (i = 1; i <= n; ++i)
532     SET_TMPL_ARGS_LEVEL (new_args, i,
533                          TMPL_ARGS_LEVEL (args, i + extra_levels));
534
535   return new_args;
536 }
537
538 /* The inverse of get_innermost_template_args: Return all but the innermost
539    EXTRA_LEVELS levels of template arguments from the ARGS.  */
540
541 static tree
542 strip_innermost_template_args (tree args, int extra_levels)
543 {
544   tree new_args;
545   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
546   int i;
547
548   gcc_assert (n >= 0);
549
550   /* If N is 1, just return the outermost set of template arguments.  */
551   if (n == 1)
552     return TMPL_ARGS_LEVEL (args, 1);
553
554   /* If we're not removing anything, just return the arguments we were
555      given.  */
556   gcc_assert (extra_levels >= 0);
557   if (extra_levels == 0)
558     return args;
559
560   /* Make a new set of arguments, not containing the inner arguments.  */
561   new_args = make_tree_vec (n);
562   for (i = 1; i <= n; ++i)
563     SET_TMPL_ARGS_LEVEL (new_args, i,
564                          TMPL_ARGS_LEVEL (args, i));
565
566   return new_args;
567 }
568
569 /* We've got a template header coming up; push to a new level for storing
570    the parms.  */
571
572 void
573 begin_template_parm_list (void)
574 {
575   /* We use a non-tag-transparent scope here, which causes pushtag to
576      put tags in this scope, rather than in the enclosing class or
577      namespace scope.  This is the right thing, since we want
578      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
579      global template class, push_template_decl handles putting the
580      TEMPLATE_DECL into top-level scope.  For a nested template class,
581      e.g.:
582
583        template <class T> struct S1 {
584          template <class T> struct S2 {};
585        };
586
587      pushtag contains special code to call pushdecl_with_scope on the
588      TEMPLATE_DECL for S2.  */
589   begin_scope (sk_template_parms, NULL);
590   ++processing_template_decl;
591   ++processing_template_parmlist;
592   note_template_header (0);
593 }
594
595 /* This routine is called when a specialization is declared.  If it is
596    invalid to declare a specialization here, an error is reported and
597    false is returned, otherwise this routine will return true.  */
598
599 static bool
600 check_specialization_scope (void)
601 {
602   tree scope = current_scope ();
603
604   /* [temp.expl.spec]
605
606      An explicit specialization shall be declared in the namespace of
607      which the template is a member, or, for member templates, in the
608      namespace of which the enclosing class or enclosing class
609      template is a member.  An explicit specialization of a member
610      function, member class or static data member of a class template
611      shall be declared in the namespace of which the class template
612      is a member.  */
613   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
614     {
615       error ("explicit specialization in non-namespace scope %qD", scope);
616       return false;
617     }
618
619   /* [temp.expl.spec]
620
621      In an explicit specialization declaration for a member of a class
622      template or a member template that appears in namespace scope,
623      the member template and some of its enclosing class templates may
624      remain unspecialized, except that the declaration shall not
625      explicitly specialize a class member template if its enclosing
626      class templates are not explicitly specialized as well.  */
627   if (current_template_parms)
628     {
629       error ("enclosing class templates are not explicitly specialized");
630       return false;
631     }
632
633   return true;
634 }
635
636 /* We've just seen template <>.  */
637
638 bool
639 begin_specialization (void)
640 {
641   begin_scope (sk_template_spec, NULL);
642   note_template_header (1);
643   return check_specialization_scope ();
644 }
645
646 /* Called at then end of processing a declaration preceded by
647    template<>.  */
648
649 void
650 end_specialization (void)
651 {
652   finish_scope ();
653   reset_specialization ();
654 }
655
656 /* Any template <>'s that we have seen thus far are not referring to a
657    function specialization.  */
658
659 void
660 reset_specialization (void)
661 {
662   processing_specialization = 0;
663   template_header_count = 0;
664 }
665
666 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
667    it was of the form template <>.  */
668
669 static void
670 note_template_header (int specialization)
671 {
672   processing_specialization = specialization;
673   template_header_count++;
674 }
675
676 /* We're beginning an explicit instantiation.  */
677
678 void
679 begin_explicit_instantiation (void)
680 {
681   gcc_assert (!processing_explicit_instantiation);
682   processing_explicit_instantiation = true;
683 }
684
685
686 void
687 end_explicit_instantiation (void)
688 {
689   gcc_assert (processing_explicit_instantiation);
690   processing_explicit_instantiation = false;
691 }
692
693 /* An explicit specialization or partial specialization TMPL is being
694    declared.  Check that the namespace in which the specialization is
695    occurring is permissible.  Returns false iff it is invalid to
696    specialize TMPL in the current namespace.  */
697
698 static bool
699 check_specialization_namespace (tree tmpl)
700 {
701   tree tpl_ns = decl_namespace_context (tmpl);
702
703   /* [tmpl.expl.spec]
704
705      An explicit specialization shall be declared in the namespace of
706      which the template is a member, or, for member templates, in the
707      namespace of which the enclosing class or enclosing class
708      template is a member.  An explicit specialization of a member
709      function, member class or static data member of a class template
710      shall be declared in the namespace of which the class template is
711      a member.  */
712   if (is_associated_namespace (current_namespace, tpl_ns))
713     /* Same or super-using namespace.  */
714     return true;
715   else
716     {
717       permerror (input_location, "specialization of %qD in different namespace", tmpl);
718       permerror (input_location, "  from definition of %q+#D", tmpl);
719       return false;
720     }
721 }
722
723 /* SPEC is an explicit instantiation.  Check that it is valid to
724    perform this explicit instantiation in the current namespace.  */
725
726 static void
727 check_explicit_instantiation_namespace (tree spec)
728 {
729   tree ns;
730
731   /* DR 275: An explicit instantiation shall appear in an enclosing
732      namespace of its template.  */
733   ns = decl_namespace_context (spec);
734   if (!is_ancestor (current_namespace, ns))
735     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
736                "(which does not enclose namespace %qD)",
737                spec, current_namespace, ns);
738 }
739
740 /* The TYPE is being declared.  If it is a template type, that means it
741    is a partial specialization.  Do appropriate error-checking.  */
742
743 tree
744 maybe_process_partial_specialization (tree type)
745 {
746   tree context;
747
748   if (type == error_mark_node)
749     return error_mark_node;
750
751   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
752     {
753       error ("name of class shadows template template parameter %qD",
754              TYPE_NAME (type));
755       return error_mark_node;
756     }
757
758   context = TYPE_CONTEXT (type);
759
760   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
761     {
762       /* This is for ordinary explicit specialization and partial
763          specialization of a template class such as:
764
765            template <> class C<int>;
766
767          or:
768
769            template <class T> class C<T*>;
770
771          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
772
773       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
774           && !COMPLETE_TYPE_P (type))
775         {
776           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
777           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
778           if (processing_template_decl)
779             {
780               if (push_template_decl (TYPE_MAIN_DECL (type))
781                   == error_mark_node)
782                 return error_mark_node;
783             }
784         }
785       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
786         error ("specialization of %qT after instantiation", type);
787     }
788   else if (CLASS_TYPE_P (type)
789            && !CLASSTYPE_USE_TEMPLATE (type)
790            && CLASSTYPE_TEMPLATE_INFO (type)
791            && context && CLASS_TYPE_P (context)
792            && CLASSTYPE_TEMPLATE_INFO (context))
793     {
794       /* This is for an explicit specialization of member class
795          template according to [temp.expl.spec/18]:
796
797            template <> template <class U> class C<int>::D;
798
799          The context `C<int>' must be an implicit instantiation.
800          Otherwise this is just a member class template declared
801          earlier like:
802
803            template <> class C<int> { template <class U> class D; };
804            template <> template <class U> class C<int>::D;
805
806          In the first case, `C<int>::D' is a specialization of `C<T>::D'
807          while in the second case, `C<int>::D' is a primary template
808          and `C<T>::D' may not exist.  */
809
810       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
811           && !COMPLETE_TYPE_P (type))
812         {
813           tree t;
814
815           if (current_namespace
816               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
817             {
818               permerror (input_location, "specializing %q#T in different namespace", type);
819               permerror (input_location, "  from definition of %q+#D",
820                          CLASSTYPE_TI_TEMPLATE (type));
821             }
822
823           /* Check for invalid specialization after instantiation:
824
825                template <> template <> class C<int>::D<int>;
826                template <> template <class U> class C<int>::D;  */
827
828           for (t = DECL_TEMPLATE_INSTANTIATIONS
829                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
830                t; t = TREE_CHAIN (t))
831             if (TREE_VALUE (t) != type
832                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
833               error ("specialization %qT after instantiation %qT",
834                      type, TREE_VALUE (t));
835
836           /* Mark TYPE as a specialization.  And as a result, we only
837              have one level of template argument for the innermost
838              class template.  */
839           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
840           CLASSTYPE_TI_ARGS (type)
841             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
842         }
843     }
844   else if (processing_specialization)
845     {
846       error ("explicit specialization of non-template %qT", type);
847       return error_mark_node;
848     }
849
850   return type;
851 }
852
853 /* Returns nonzero if we can optimize the retrieval of specializations
854    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
855    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
856
857 static inline bool
858 optimize_specialization_lookup_p (tree tmpl)
859 {
860   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
861           && DECL_CLASS_SCOPE_P (tmpl)
862           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
863              parameter.  */
864           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
865           /* The optimized lookup depends on the fact that the
866              template arguments for the member function template apply
867              purely to the containing class, which is not true if the
868              containing class is an explicit or partial
869              specialization.  */
870           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
871           && !DECL_MEMBER_TEMPLATE_P (tmpl)
872           && !DECL_CONV_FN_P (tmpl)
873           /* It is possible to have a template that is not a member
874              template and is not a member of a template class:
875
876              template <typename T>
877              struct S { friend A::f(); };
878
879              Here, the friend function is a template, but the context does
880              not have template information.  The optimized lookup relies
881              on having ARGS be the template arguments for both the class
882              and the function template.  */
883           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
884 }
885
886 /* Retrieve the specialization (in the sense of [temp.spec] - a
887    specialization is either an instantiation or an explicit
888    specialization) of TMPL for the given template ARGS.  If there is
889    no such specialization, return NULL_TREE.  The ARGS are a vector of
890    arguments, or a vector of vectors of arguments, in the case of
891    templates with more than one level of parameters.
892
893    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
894    then we search for a partial specialization matching ARGS.  This
895    parameter is ignored if TMPL is not a class template.  */
896
897 static tree
898 retrieve_specialization (tree tmpl, tree args,
899                          bool class_specializations_p)
900 {
901   if (args == error_mark_node)
902     return NULL_TREE;
903
904   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
905
906   /* There should be as many levels of arguments as there are
907      levels of parameters.  */
908   gcc_assert (TMPL_ARGS_DEPTH (args)
909               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
910
911   if (optimize_specialization_lookup_p (tmpl))
912     {
913       tree class_template;
914       tree class_specialization;
915       VEC(tree,gc) *methods;
916       tree fns;
917       int idx;
918
919       /* The template arguments actually apply to the containing
920          class.  Find the class specialization with those
921          arguments.  */
922       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
923       class_specialization
924         = retrieve_specialization (class_template, args,
925                                    /*class_specializations_p=*/false);
926       if (!class_specialization)
927         return NULL_TREE;
928       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
929          for the specialization.  */
930       idx = class_method_index_for_fn (class_specialization, tmpl);
931       if (idx == -1)
932         return NULL_TREE;
933       /* Iterate through the methods with the indicated name, looking
934          for the one that has an instance of TMPL.  */
935       methods = CLASSTYPE_METHOD_VEC (class_specialization);
936       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
937         {
938           tree fn = OVL_CURRENT (fns);
939           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
940             return fn;
941         }
942       return NULL_TREE;
943     }
944   else
945     {
946       tree *sp;
947       tree *head;
948
949       /* Class templates store their instantiations on the
950          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
951          DECL_TEMPLATE_SPECIALIZATIONS list.  */
952       if (!class_specializations_p
953           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL
954           && !is_typedef_decl (DECL_TEMPLATE_RESULT (tmpl))
955           && TAGGED_TYPE_P (TREE_TYPE (tmpl)))
956         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
957       else
958         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
959       head = sp;
960       /* Iterate through the list until we find a matching template.  */
961       while (*sp != NULL_TREE)
962         {
963           tree spec = *sp;
964
965           if (comp_template_args (TREE_PURPOSE (spec), args))
966             {
967               /* Use the move-to-front heuristic to speed up future
968                  searches.  */
969               if (spec != *head)
970                 {
971                   *sp = TREE_CHAIN (*sp);
972                   TREE_CHAIN (spec) = *head;
973                   *head = spec;
974                 }
975               return TREE_VALUE (spec);
976             }
977           sp = &TREE_CHAIN (spec);
978         }
979     }
980
981   return NULL_TREE;
982 }
983
984 /* Like retrieve_specialization, but for local declarations.  */
985
986 static tree
987 retrieve_local_specialization (tree tmpl)
988 {
989   tree spec;
990
991   if (local_specializations == NULL)
992     return NULL_TREE;
993
994   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
995                                      htab_hash_pointer (tmpl));
996   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
997 }
998
999 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1000
1001 int
1002 is_specialization_of (tree decl, tree tmpl)
1003 {
1004   tree t;
1005
1006   if (TREE_CODE (decl) == FUNCTION_DECL)
1007     {
1008       for (t = decl;
1009            t != NULL_TREE;
1010            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1011         if (t == tmpl)
1012           return 1;
1013     }
1014   else
1015     {
1016       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1017
1018       for (t = TREE_TYPE (decl);
1019            t != NULL_TREE;
1020            t = CLASSTYPE_USE_TEMPLATE (t)
1021              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1022         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1023           return 1;
1024     }
1025
1026   return 0;
1027 }
1028
1029 /* Returns nonzero iff DECL is a specialization of friend declaration
1030    FRIEND_DECL according to [temp.friend].  */
1031
1032 bool
1033 is_specialization_of_friend (tree decl, tree friend_decl)
1034 {
1035   bool need_template = true;
1036   int template_depth;
1037
1038   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1039               || TREE_CODE (decl) == TYPE_DECL);
1040
1041   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1042      of a template class, we want to check if DECL is a specialization
1043      if this.  */
1044   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1045       && DECL_TEMPLATE_INFO (friend_decl)
1046       && !DECL_USE_TEMPLATE (friend_decl))
1047     {
1048       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1049       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1050       need_template = false;
1051     }
1052   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1053            && !PRIMARY_TEMPLATE_P (friend_decl))
1054     need_template = false;
1055
1056   /* There is nothing to do if this is not a template friend.  */
1057   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1058     return false;
1059
1060   if (is_specialization_of (decl, friend_decl))
1061     return true;
1062
1063   /* [temp.friend/6]
1064      A member of a class template may be declared to be a friend of a
1065      non-template class.  In this case, the corresponding member of
1066      every specialization of the class template is a friend of the
1067      class granting friendship.
1068
1069      For example, given a template friend declaration
1070
1071        template <class T> friend void A<T>::f();
1072
1073      the member function below is considered a friend
1074
1075        template <> struct A<int> {
1076          void f();
1077        };
1078
1079      For this type of template friend, TEMPLATE_DEPTH below will be
1080      nonzero.  To determine if DECL is a friend of FRIEND, we first
1081      check if the enclosing class is a specialization of another.  */
1082
1083   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1084   if (template_depth
1085       && DECL_CLASS_SCOPE_P (decl)
1086       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1087                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1088     {
1089       /* Next, we check the members themselves.  In order to handle
1090          a few tricky cases, such as when FRIEND_DECL's are
1091
1092            template <class T> friend void A<T>::g(T t);
1093            template <class T> template <T t> friend void A<T>::h();
1094
1095          and DECL's are
1096
1097            void A<int>::g(int);
1098            template <int> void A<int>::h();
1099
1100          we need to figure out ARGS, the template arguments from
1101          the context of DECL.  This is required for template substitution
1102          of `T' in the function parameter of `g' and template parameter
1103          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1104
1105       tree context = DECL_CONTEXT (decl);
1106       tree args = NULL_TREE;
1107       int current_depth = 0;
1108
1109       while (current_depth < template_depth)
1110         {
1111           if (CLASSTYPE_TEMPLATE_INFO (context))
1112             {
1113               if (current_depth == 0)
1114                 args = TYPE_TI_ARGS (context);
1115               else
1116                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1117               current_depth++;
1118             }
1119           context = TYPE_CONTEXT (context);
1120         }
1121
1122       if (TREE_CODE (decl) == FUNCTION_DECL)
1123         {
1124           bool is_template;
1125           tree friend_type;
1126           tree decl_type;
1127           tree friend_args_type;
1128           tree decl_args_type;
1129
1130           /* Make sure that both DECL and FRIEND_DECL are templates or
1131              non-templates.  */
1132           is_template = DECL_TEMPLATE_INFO (decl)
1133                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1134           if (need_template ^ is_template)
1135             return false;
1136           else if (is_template)
1137             {
1138               /* If both are templates, check template parameter list.  */
1139               tree friend_parms
1140                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1141                                          args, tf_none);
1142               if (!comp_template_parms
1143                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1144                       friend_parms))
1145                 return false;
1146
1147               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1148             }
1149           else
1150             decl_type = TREE_TYPE (decl);
1151
1152           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1153                                               tf_none, NULL_TREE);
1154           if (friend_type == error_mark_node)
1155             return false;
1156
1157           /* Check if return types match.  */
1158           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1159             return false;
1160
1161           /* Check if function parameter types match, ignoring the
1162              `this' parameter.  */
1163           friend_args_type = TYPE_ARG_TYPES (friend_type);
1164           decl_args_type = TYPE_ARG_TYPES (decl_type);
1165           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1166             friend_args_type = TREE_CHAIN (friend_args_type);
1167           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1168             decl_args_type = TREE_CHAIN (decl_args_type);
1169
1170           return compparms (decl_args_type, friend_args_type);
1171         }
1172       else
1173         {
1174           /* DECL is a TYPE_DECL */
1175           bool is_template;
1176           tree decl_type = TREE_TYPE (decl);
1177
1178           /* Make sure that both DECL and FRIEND_DECL are templates or
1179              non-templates.  */
1180           is_template
1181             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1182               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1183
1184           if (need_template ^ is_template)
1185             return false;
1186           else if (is_template)
1187             {
1188               tree friend_parms;
1189               /* If both are templates, check the name of the two
1190                  TEMPLATE_DECL's first because is_friend didn't.  */
1191               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1192                   != DECL_NAME (friend_decl))
1193                 return false;
1194
1195               /* Now check template parameter list.  */
1196               friend_parms
1197                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1198                                          args, tf_none);
1199               return comp_template_parms
1200                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1201                  friend_parms);
1202             }
1203           else
1204             return (DECL_NAME (decl)
1205                     == DECL_NAME (friend_decl));
1206         }
1207     }
1208   return false;
1209 }
1210
1211 /* Register the specialization SPEC as a specialization of TMPL with
1212    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1213    is actually just a friend declaration.  Returns SPEC, or an
1214    equivalent prior declaration, if available.  */
1215
1216 static tree
1217 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1218 {
1219   tree fn;
1220
1221   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1222
1223   if (TREE_CODE (spec) == FUNCTION_DECL
1224       && uses_template_parms (DECL_TI_ARGS (spec)))
1225     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1226        register it; we want the corresponding TEMPLATE_DECL instead.
1227        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1228        the more obvious `uses_template_parms (spec)' to avoid problems
1229        with default function arguments.  In particular, given
1230        something like this:
1231
1232           template <class T> void f(T t1, T t = T())
1233
1234        the default argument expression is not substituted for in an
1235        instantiation unless and until it is actually needed.  */
1236     return spec;
1237
1238   fn = retrieve_specialization (tmpl, args,
1239                                 /*class_specializations_p=*/false);
1240   /* We can sometimes try to re-register a specialization that we've
1241      already got.  In particular, regenerate_decl_from_template calls
1242      duplicate_decls which will update the specialization list.  But,
1243      we'll still get called again here anyhow.  It's more convenient
1244      to simply allow this than to try to prevent it.  */
1245   if (fn == spec)
1246     return spec;
1247   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1248     {
1249       if (DECL_TEMPLATE_INSTANTIATION (fn))
1250         {
1251           if (TREE_USED (fn)
1252               || DECL_EXPLICIT_INSTANTIATION (fn))
1253             {
1254               error ("specialization of %qD after instantiation",
1255                      fn);
1256               return error_mark_node;
1257             }
1258           else
1259             {
1260               tree clone;
1261               /* This situation should occur only if the first
1262                  specialization is an implicit instantiation, the
1263                  second is an explicit specialization, and the
1264                  implicit instantiation has not yet been used.  That
1265                  situation can occur if we have implicitly
1266                  instantiated a member function and then specialized
1267                  it later.
1268
1269                  We can also wind up here if a friend declaration that
1270                  looked like an instantiation turns out to be a
1271                  specialization:
1272
1273                    template <class T> void foo(T);
1274                    class S { friend void foo<>(int) };
1275                    template <> void foo(int);
1276
1277                  We transform the existing DECL in place so that any
1278                  pointers to it become pointers to the updated
1279                  declaration.
1280
1281                  If there was a definition for the template, but not
1282                  for the specialization, we want this to look as if
1283                  there were no definition, and vice versa.  */
1284               DECL_INITIAL (fn) = NULL_TREE;
1285               duplicate_decls (spec, fn, is_friend);
1286               /* The call to duplicate_decls will have applied
1287                  [temp.expl.spec]:
1288
1289                    An explicit specialization of a function template
1290                    is inline only if it is explicitly declared to be,
1291                    and independently of whether its function template
1292                    is.
1293
1294                 to the primary function; now copy the inline bits to
1295                 the various clones.  */
1296               FOR_EACH_CLONE (clone, fn)
1297                 DECL_DECLARED_INLINE_P (clone)
1298                   = DECL_DECLARED_INLINE_P (fn);
1299               check_specialization_namespace (fn);
1300
1301               return fn;
1302             }
1303         }
1304       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1305         {
1306           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1307             /* Dup decl failed, but this is a new definition. Set the
1308                line number so any errors match this new
1309                definition.  */
1310             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1311
1312           return fn;
1313         }
1314     }
1315
1316   /* A specialization must be declared in the same namespace as the
1317      template it is specializing.  */
1318   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1319       && !check_specialization_namespace (tmpl))
1320     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1321
1322   if (!optimize_specialization_lookup_p (tmpl))
1323     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1324       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1325
1326   return spec;
1327 }
1328
1329 /* Unregister the specialization SPEC as a specialization of TMPL.
1330    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1331    if the SPEC was listed as a specialization of TMPL.  */
1332
1333 bool
1334 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1335 {
1336   tree* s;
1337
1338   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1339        *s != NULL_TREE;
1340        s = &TREE_CHAIN (*s))
1341     if (TREE_VALUE (*s) == spec)
1342       {
1343         if (!new_spec)
1344           *s = TREE_CHAIN (*s);
1345         else
1346           TREE_VALUE (*s) = new_spec;
1347         return 1;
1348       }
1349
1350   return 0;
1351 }
1352
1353 /* Compare an entry in the local specializations hash table P1 (which
1354    is really a pointer to a TREE_LIST) with P2 (which is really a
1355    DECL).  */
1356
1357 static int
1358 eq_local_specializations (const void *p1, const void *p2)
1359 {
1360   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1361 }
1362
1363 /* Hash P1, an entry in the local specializations table.  */
1364
1365 static hashval_t
1366 hash_local_specialization (const void* p1)
1367 {
1368   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1369 }
1370
1371 /* Like register_specialization, but for local declarations.  We are
1372    registering SPEC, an instantiation of TMPL.  */
1373
1374 static void
1375 register_local_specialization (tree spec, tree tmpl)
1376 {
1377   void **slot;
1378
1379   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1380                                    htab_hash_pointer (tmpl), INSERT);
1381   *slot = build_tree_list (spec, tmpl);
1382 }
1383
1384 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1385    specialized class.  */
1386
1387 bool
1388 explicit_class_specialization_p (tree type)
1389 {
1390   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1391     return false;
1392   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1393 }
1394
1395 /* Print the list of candidate FNS in an error message.  */
1396
1397 void
1398 print_candidates (tree fns)
1399 {
1400   tree fn;
1401
1402   const char *str = "candidates are:";
1403
1404   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1405     {
1406       tree f;
1407
1408       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1409         error ("%s %+#D", str, OVL_CURRENT (f));
1410       str = "               ";
1411     }
1412 }
1413
1414 /* Returns the template (one of the functions given by TEMPLATE_ID)
1415    which can be specialized to match the indicated DECL with the
1416    explicit template args given in TEMPLATE_ID.  The DECL may be
1417    NULL_TREE if none is available.  In that case, the functions in
1418    TEMPLATE_ID are non-members.
1419
1420    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1421    specialization of a member template.
1422
1423    The TEMPLATE_COUNT is the number of references to qualifying
1424    template classes that appeared in the name of the function. See
1425    check_explicit_specialization for a more accurate description.
1426
1427    TSK indicates what kind of template declaration (if any) is being
1428    declared.  TSK_TEMPLATE indicates that the declaration given by
1429    DECL, though a FUNCTION_DECL, has template parameters, and is
1430    therefore a template function.
1431
1432    The template args (those explicitly specified and those deduced)
1433    are output in a newly created vector *TARGS_OUT.
1434
1435    If it is impossible to determine the result, an error message is
1436    issued.  The error_mark_node is returned to indicate failure.  */
1437
1438 static tree
1439 determine_specialization (tree template_id,
1440                           tree decl,
1441                           tree* targs_out,
1442                           int need_member_template,
1443                           int template_count,
1444                           tmpl_spec_kind tsk)
1445 {
1446   tree fns;
1447   tree targs;
1448   tree explicit_targs;
1449   tree candidates = NULL_TREE;
1450   /* A TREE_LIST of templates of which DECL may be a specialization.
1451      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1452      corresponding TREE_PURPOSE is the set of template arguments that,
1453      when used to instantiate the template, would produce a function
1454      with the signature of DECL.  */
1455   tree templates = NULL_TREE;
1456   int header_count;
1457   struct cp_binding_level *b;
1458
1459   *targs_out = NULL_TREE;
1460
1461   if (template_id == error_mark_node || decl == error_mark_node)
1462     return error_mark_node;
1463
1464   fns = TREE_OPERAND (template_id, 0);
1465   explicit_targs = TREE_OPERAND (template_id, 1);
1466
1467   if (fns == error_mark_node)
1468     return error_mark_node;
1469
1470   /* Check for baselinks.  */
1471   if (BASELINK_P (fns))
1472     fns = BASELINK_FUNCTIONS (fns);
1473
1474   if (!is_overloaded_fn (fns))
1475     {
1476       error ("%qD is not a function template", fns);
1477       return error_mark_node;
1478     }
1479
1480   /* Count the number of template headers specified for this
1481      specialization.  */
1482   header_count = 0;
1483   for (b = current_binding_level;
1484        b->kind == sk_template_parms;
1485        b = b->level_chain)
1486     ++header_count;
1487
1488   for (; fns; fns = OVL_NEXT (fns))
1489     {
1490       tree fn = OVL_CURRENT (fns);
1491
1492       if (TREE_CODE (fn) == TEMPLATE_DECL)
1493         {
1494           tree decl_arg_types;
1495           tree fn_arg_types;
1496
1497           /* In case of explicit specialization, we need to check if
1498              the number of template headers appearing in the specialization
1499              is correct. This is usually done in check_explicit_specialization,
1500              but the check done there cannot be exhaustive when specializing
1501              member functions. Consider the following code:
1502
1503              template <> void A<int>::f(int);
1504              template <> template <> void A<int>::f(int);
1505
1506              Assuming that A<int> is not itself an explicit specialization
1507              already, the first line specializes "f" which is a non-template
1508              member function, whilst the second line specializes "f" which
1509              is a template member function. So both lines are syntactically
1510              correct, and check_explicit_specialization does not reject
1511              them.
1512
1513              Here, we can do better, as we are matching the specialization
1514              against the declarations. We count the number of template
1515              headers, and we check if they match TEMPLATE_COUNT + 1
1516              (TEMPLATE_COUNT is the number of qualifying template classes,
1517              plus there must be another header for the member template
1518              itself).
1519
1520              Notice that if header_count is zero, this is not a
1521              specialization but rather a template instantiation, so there
1522              is no check we can perform here.  */
1523           if (header_count && header_count != template_count + 1)
1524             continue;
1525
1526           /* Check that the number of template arguments at the
1527              innermost level for DECL is the same as for FN.  */
1528           if (current_binding_level->kind == sk_template_parms
1529               && !current_binding_level->explicit_spec_p
1530               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1531                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1532                                       (current_template_parms))))
1533             continue;
1534
1535           /* DECL might be a specialization of FN.  */
1536           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1537           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1538
1539           /* For a non-static member function, we need to make sure
1540              that the const qualification is the same.  Since
1541              get_bindings does not try to merge the "this" parameter,
1542              we must do the comparison explicitly.  */
1543           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1544               && !same_type_p (TREE_VALUE (fn_arg_types),
1545                                TREE_VALUE (decl_arg_types)))
1546             continue;
1547
1548           /* Skip the "this" parameter and, for constructors of
1549              classes with virtual bases, the VTT parameter.  A
1550              full specialization of a constructor will have a VTT
1551              parameter, but a template never will.  */ 
1552           decl_arg_types 
1553             = skip_artificial_parms_for (decl, decl_arg_types);
1554           fn_arg_types 
1555             = skip_artificial_parms_for (fn, fn_arg_types);
1556
1557           /* Check that the number of function parameters matches.
1558              For example,
1559                template <class T> void f(int i = 0);
1560                template <> void f<int>();
1561              The specialization f<int> is invalid but is not caught
1562              by get_bindings below.  */
1563           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1564             continue;
1565
1566           /* Function templates cannot be specializations; there are
1567              no partial specializations of functions.  Therefore, if
1568              the type of DECL does not match FN, there is no
1569              match.  */
1570           if (tsk == tsk_template)
1571             {
1572               if (compparms (fn_arg_types, decl_arg_types))
1573                 candidates = tree_cons (NULL_TREE, fn, candidates);
1574               continue;
1575             }
1576
1577           /* See whether this function might be a specialization of this
1578              template.  */
1579           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1580
1581           if (!targs)
1582             /* We cannot deduce template arguments that when used to
1583                specialize TMPL will produce DECL.  */
1584             continue;
1585
1586           /* Save this template, and the arguments deduced.  */
1587           templates = tree_cons (targs, fn, templates);
1588         }
1589       else if (need_member_template)
1590         /* FN is an ordinary member function, and we need a
1591            specialization of a member template.  */
1592         ;
1593       else if (TREE_CODE (fn) != FUNCTION_DECL)
1594         /* We can get IDENTIFIER_NODEs here in certain erroneous
1595            cases.  */
1596         ;
1597       else if (!DECL_FUNCTION_MEMBER_P (fn))
1598         /* This is just an ordinary non-member function.  Nothing can
1599            be a specialization of that.  */
1600         ;
1601       else if (DECL_ARTIFICIAL (fn))
1602         /* Cannot specialize functions that are created implicitly.  */
1603         ;
1604       else
1605         {
1606           tree decl_arg_types;
1607
1608           /* This is an ordinary member function.  However, since
1609              we're here, we can assume it's enclosing class is a
1610              template class.  For example,
1611
1612                template <typename T> struct S { void f(); };
1613                template <> void S<int>::f() {}
1614
1615              Here, S<int>::f is a non-template, but S<int> is a
1616              template class.  If FN has the same type as DECL, we
1617              might be in business.  */
1618
1619           if (!DECL_TEMPLATE_INFO (fn))
1620             /* Its enclosing class is an explicit specialization
1621                of a template class.  This is not a candidate.  */
1622             continue;
1623
1624           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1625                             TREE_TYPE (TREE_TYPE (fn))))
1626             /* The return types differ.  */
1627             continue;
1628
1629           /* Adjust the type of DECL in case FN is a static member.  */
1630           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1631           if (DECL_STATIC_FUNCTION_P (fn)
1632               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1633             decl_arg_types = TREE_CHAIN (decl_arg_types);
1634
1635           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1636                          decl_arg_types))
1637             /* They match!  */
1638             candidates = tree_cons (NULL_TREE, fn, candidates);
1639         }
1640     }
1641
1642   if (templates && TREE_CHAIN (templates))
1643     {
1644       /* We have:
1645
1646            [temp.expl.spec]
1647
1648            It is possible for a specialization with a given function
1649            signature to be instantiated from more than one function
1650            template.  In such cases, explicit specification of the
1651            template arguments must be used to uniquely identify the
1652            function template specialization being specialized.
1653
1654          Note that here, there's no suggestion that we're supposed to
1655          determine which of the candidate templates is most
1656          specialized.  However, we, also have:
1657
1658            [temp.func.order]
1659
1660            Partial ordering of overloaded function template
1661            declarations is used in the following contexts to select
1662            the function template to which a function template
1663            specialization refers:
1664
1665            -- when an explicit specialization refers to a function
1666               template.
1667
1668          So, we do use the partial ordering rules, at least for now.
1669          This extension can only serve to make invalid programs valid,
1670          so it's safe.  And, there is strong anecdotal evidence that
1671          the committee intended the partial ordering rules to apply;
1672          the EDG front end has that behavior, and John Spicer claims
1673          that the committee simply forgot to delete the wording in
1674          [temp.expl.spec].  */
1675       tree tmpl = most_specialized_instantiation (templates);
1676       if (tmpl != error_mark_node)
1677         {
1678           templates = tmpl;
1679           TREE_CHAIN (templates) = NULL_TREE;
1680         }
1681     }
1682
1683   if (templates == NULL_TREE && candidates == NULL_TREE)
1684     {
1685       error ("template-id %qD for %q+D does not match any template "
1686              "declaration", template_id, decl);
1687       return error_mark_node;
1688     }
1689   else if ((templates && TREE_CHAIN (templates))
1690            || (candidates && TREE_CHAIN (candidates))
1691            || (templates && candidates))
1692     {
1693       error ("ambiguous template specialization %qD for %q+D",
1694              template_id, decl);
1695       chainon (candidates, templates);
1696       print_candidates (candidates);
1697       return error_mark_node;
1698     }
1699
1700   /* We have one, and exactly one, match.  */
1701   if (candidates)
1702     {
1703       tree fn = TREE_VALUE (candidates);
1704       /* DECL is a re-declaration of a template function.  */
1705       if (TREE_CODE (fn) == TEMPLATE_DECL)
1706         return fn;
1707       /* It was a specialization of an ordinary member function in a
1708          template class.  */
1709       *targs_out = copy_node (DECL_TI_ARGS (fn));
1710       return DECL_TI_TEMPLATE (fn);
1711     }
1712
1713   /* It was a specialization of a template.  */
1714   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1715   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1716     {
1717       *targs_out = copy_node (targs);
1718       SET_TMPL_ARGS_LEVEL (*targs_out,
1719                            TMPL_ARGS_DEPTH (*targs_out),
1720                            TREE_PURPOSE (templates));
1721     }
1722   else
1723     *targs_out = TREE_PURPOSE (templates);
1724   return TREE_VALUE (templates);
1725 }
1726
1727 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1728    but with the default argument values filled in from those in the
1729    TMPL_TYPES.  */
1730
1731 static tree
1732 copy_default_args_to_explicit_spec_1 (tree spec_types,
1733                                       tree tmpl_types)
1734 {
1735   tree new_spec_types;
1736
1737   if (!spec_types)
1738     return NULL_TREE;
1739
1740   if (spec_types == void_list_node)
1741     return void_list_node;
1742
1743   /* Substitute into the rest of the list.  */
1744   new_spec_types =
1745     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1746                                           TREE_CHAIN (tmpl_types));
1747
1748   /* Add the default argument for this parameter.  */
1749   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1750                          TREE_VALUE (spec_types),
1751                          new_spec_types);
1752 }
1753
1754 /* DECL is an explicit specialization.  Replicate default arguments
1755    from the template it specializes.  (That way, code like:
1756
1757      template <class T> void f(T = 3);
1758      template <> void f(double);
1759      void g () { f (); }
1760
1761    works, as required.)  An alternative approach would be to look up
1762    the correct default arguments at the call-site, but this approach
1763    is consistent with how implicit instantiations are handled.  */
1764
1765 static void
1766 copy_default_args_to_explicit_spec (tree decl)
1767 {
1768   tree tmpl;
1769   tree spec_types;
1770   tree tmpl_types;
1771   tree new_spec_types;
1772   tree old_type;
1773   tree new_type;
1774   tree t;
1775   tree object_type = NULL_TREE;
1776   tree in_charge = NULL_TREE;
1777   tree vtt = NULL_TREE;
1778
1779   /* See if there's anything we need to do.  */
1780   tmpl = DECL_TI_TEMPLATE (decl);
1781   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1782   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1783     if (TREE_PURPOSE (t))
1784       break;
1785   if (!t)
1786     return;
1787
1788   old_type = TREE_TYPE (decl);
1789   spec_types = TYPE_ARG_TYPES (old_type);
1790
1791   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1792     {
1793       /* Remove the this pointer, but remember the object's type for
1794          CV quals.  */
1795       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1796       spec_types = TREE_CHAIN (spec_types);
1797       tmpl_types = TREE_CHAIN (tmpl_types);
1798
1799       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1800         {
1801           /* DECL may contain more parameters than TMPL due to the extra
1802              in-charge parameter in constructors and destructors.  */
1803           in_charge = spec_types;
1804           spec_types = TREE_CHAIN (spec_types);
1805         }
1806       if (DECL_HAS_VTT_PARM_P (decl))
1807         {
1808           vtt = spec_types;
1809           spec_types = TREE_CHAIN (spec_types);
1810         }
1811     }
1812
1813   /* Compute the merged default arguments.  */
1814   new_spec_types =
1815     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1816
1817   /* Compute the new FUNCTION_TYPE.  */
1818   if (object_type)
1819     {
1820       if (vtt)
1821         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1822                                          TREE_VALUE (vtt),
1823                                          new_spec_types);
1824
1825       if (in_charge)
1826         /* Put the in-charge parameter back.  */
1827         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1828                                          TREE_VALUE (in_charge),
1829                                          new_spec_types);
1830
1831       new_type = build_method_type_directly (object_type,
1832                                              TREE_TYPE (old_type),
1833                                              new_spec_types);
1834     }
1835   else
1836     new_type = build_function_type (TREE_TYPE (old_type),
1837                                     new_spec_types);
1838   new_type = cp_build_type_attribute_variant (new_type,
1839                                               TYPE_ATTRIBUTES (old_type));
1840   new_type = build_exception_variant (new_type,
1841                                       TYPE_RAISES_EXCEPTIONS (old_type));
1842   TREE_TYPE (decl) = new_type;
1843 }
1844
1845 /* Check to see if the function just declared, as indicated in
1846    DECLARATOR, and in DECL, is a specialization of a function
1847    template.  We may also discover that the declaration is an explicit
1848    instantiation at this point.
1849
1850    Returns DECL, or an equivalent declaration that should be used
1851    instead if all goes well.  Issues an error message if something is
1852    amiss.  Returns error_mark_node if the error is not easily
1853    recoverable.
1854
1855    FLAGS is a bitmask consisting of the following flags:
1856
1857    2: The function has a definition.
1858    4: The function is a friend.
1859
1860    The TEMPLATE_COUNT is the number of references to qualifying
1861    template classes that appeared in the name of the function.  For
1862    example, in
1863
1864      template <class T> struct S { void f(); };
1865      void S<int>::f();
1866
1867    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1868    classes are not counted in the TEMPLATE_COUNT, so that in
1869
1870      template <class T> struct S {};
1871      template <> struct S<int> { void f(); }
1872      template <> void S<int>::f();
1873
1874    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1875    invalid; there should be no template <>.)
1876
1877    If the function is a specialization, it is marked as such via
1878    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1879    is set up correctly, and it is added to the list of specializations
1880    for that template.  */
1881
1882 tree
1883 check_explicit_specialization (tree declarator,
1884                                tree decl,
1885                                int template_count,
1886                                int flags)
1887 {
1888   int have_def = flags & 2;
1889   int is_friend = flags & 4;
1890   int specialization = 0;
1891   int explicit_instantiation = 0;
1892   int member_specialization = 0;
1893   tree ctype = DECL_CLASS_CONTEXT (decl);
1894   tree dname = DECL_NAME (decl);
1895   tmpl_spec_kind tsk;
1896
1897   if (is_friend)
1898     {
1899       if (!processing_specialization)
1900         tsk = tsk_none;
1901       else
1902         tsk = tsk_excessive_parms;
1903     }
1904   else
1905     tsk = current_tmpl_spec_kind (template_count);
1906
1907   switch (tsk)
1908     {
1909     case tsk_none:
1910       if (processing_specialization)
1911         {
1912           specialization = 1;
1913           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1914         }
1915       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1916         {
1917           if (is_friend)
1918             /* This could be something like:
1919
1920                template <class T> void f(T);
1921                class S { friend void f<>(int); }  */
1922             specialization = 1;
1923           else
1924             {
1925               /* This case handles bogus declarations like template <>
1926                  template <class T> void f<int>(); */
1927
1928               error ("template-id %qD in declaration of primary template",
1929                      declarator);
1930               return decl;
1931             }
1932         }
1933       break;
1934
1935     case tsk_invalid_member_spec:
1936       /* The error has already been reported in
1937          check_specialization_scope.  */
1938       return error_mark_node;
1939
1940     case tsk_invalid_expl_inst:
1941       error ("template parameter list used in explicit instantiation");
1942
1943       /* Fall through.  */
1944
1945     case tsk_expl_inst:
1946       if (have_def)
1947         error ("definition provided for explicit instantiation");
1948
1949       explicit_instantiation = 1;
1950       break;
1951
1952     case tsk_excessive_parms:
1953     case tsk_insufficient_parms:
1954       if (tsk == tsk_excessive_parms)
1955         error ("too many template parameter lists in declaration of %qD",
1956                decl);
1957       else if (template_header_count)
1958         error("too few template parameter lists in declaration of %qD", decl);
1959       else
1960         error("explicit specialization of %qD must be introduced by "
1961               "%<template <>%>", decl);
1962
1963       /* Fall through.  */
1964     case tsk_expl_spec:
1965       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1966       if (ctype)
1967         member_specialization = 1;
1968       else
1969         specialization = 1;
1970       break;
1971
1972     case tsk_template:
1973       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1974         {
1975           /* This case handles bogus declarations like template <>
1976              template <class T> void f<int>(); */
1977
1978           if (uses_template_parms (declarator))
1979             error ("function template partial specialization %qD "
1980                    "is not allowed", declarator);
1981           else
1982             error ("template-id %qD in declaration of primary template",
1983                    declarator);
1984           return decl;
1985         }
1986
1987       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1988         /* This is a specialization of a member template, without
1989            specialization the containing class.  Something like:
1990
1991              template <class T> struct S {
1992                template <class U> void f (U);
1993              };
1994              template <> template <class U> void S<int>::f(U) {}
1995
1996            That's a specialization -- but of the entire template.  */
1997         specialization = 1;
1998       break;
1999
2000     default:
2001       gcc_unreachable ();
2002     }
2003
2004   if (specialization || member_specialization)
2005     {
2006       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2007       for (; t; t = TREE_CHAIN (t))
2008         if (TREE_PURPOSE (t))
2009           {
2010             permerror (input_location, 
2011                        "default argument specified in explicit specialization");
2012             break;
2013           }
2014     }
2015
2016   if (specialization || member_specialization || explicit_instantiation)
2017     {
2018       tree tmpl = NULL_TREE;
2019       tree targs = NULL_TREE;
2020
2021       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2022       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2023         {
2024           tree fns;
2025
2026           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2027           if (ctype)
2028             fns = dname;
2029           else
2030             {
2031               /* If there is no class context, the explicit instantiation
2032                  must be at namespace scope.  */
2033               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2034
2035               /* Find the namespace binding, using the declaration
2036                  context.  */
2037               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2038                                            false, true);
2039               if (fns == error_mark_node || !is_overloaded_fn (fns))
2040                 {
2041                   error ("%qD is not a template function", dname);
2042                   fns = error_mark_node;
2043                 }
2044               else
2045                 {
2046                   tree fn = OVL_CURRENT (fns);
2047                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2048                                                 CP_DECL_CONTEXT (fn)))
2049                     error ("%qD is not declared in %qD",
2050                            decl, current_namespace);
2051                 }
2052             }
2053
2054           declarator = lookup_template_function (fns, NULL_TREE);
2055         }
2056
2057       if (declarator == error_mark_node)
2058         return error_mark_node;
2059
2060       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2061         {
2062           if (!explicit_instantiation)
2063             /* A specialization in class scope.  This is invalid,
2064                but the error will already have been flagged by
2065                check_specialization_scope.  */
2066             return error_mark_node;
2067           else
2068             {
2069               /* It's not valid to write an explicit instantiation in
2070                  class scope, e.g.:
2071
2072                    class C { template void f(); }
2073
2074                    This case is caught by the parser.  However, on
2075                    something like:
2076
2077                    template class C { void f(); };
2078
2079                    (which is invalid) we can get here.  The error will be
2080                    issued later.  */
2081               ;
2082             }
2083
2084           return decl;
2085         }
2086       else if (ctype != NULL_TREE
2087                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2088                    IDENTIFIER_NODE))
2089         {
2090           /* Find the list of functions in ctype that have the same
2091              name as the declared function.  */
2092           tree name = TREE_OPERAND (declarator, 0);
2093           tree fns = NULL_TREE;
2094           int idx;
2095
2096           if (constructor_name_p (name, ctype))
2097             {
2098               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2099
2100               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2101                   : !CLASSTYPE_DESTRUCTORS (ctype))
2102                 {
2103                   /* From [temp.expl.spec]:
2104
2105                      If such an explicit specialization for the member
2106                      of a class template names an implicitly-declared
2107                      special member function (clause _special_), the
2108                      program is ill-formed.
2109
2110                      Similar language is found in [temp.explicit].  */
2111                   error ("specialization of implicitly-declared special member function");
2112                   return error_mark_node;
2113                 }
2114
2115               name = is_constructor ? ctor_identifier : dtor_identifier;
2116             }
2117
2118           if (!DECL_CONV_FN_P (decl))
2119             {
2120               idx = lookup_fnfields_1 (ctype, name);
2121               if (idx >= 0)
2122                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2123             }
2124           else
2125             {
2126               VEC(tree,gc) *methods;
2127               tree ovl;
2128
2129               /* For a type-conversion operator, we cannot do a
2130                  name-based lookup.  We might be looking for `operator
2131                  int' which will be a specialization of `operator T'.
2132                  So, we find *all* the conversion operators, and then
2133                  select from them.  */
2134               fns = NULL_TREE;
2135
2136               methods = CLASSTYPE_METHOD_VEC (ctype);
2137               if (methods)
2138                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2139                      VEC_iterate (tree, methods, idx, ovl);
2140                      ++idx)
2141                   {
2142                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2143                       /* There are no more conversion functions.  */
2144                       break;
2145
2146                     /* Glue all these conversion functions together
2147                        with those we already have.  */
2148                     for (; ovl; ovl = OVL_NEXT (ovl))
2149                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2150                   }
2151             }
2152
2153           if (fns == NULL_TREE)
2154             {
2155               error ("no member function %qD declared in %qT", name, ctype);
2156               return error_mark_node;
2157             }
2158           else
2159             TREE_OPERAND (declarator, 0) = fns;
2160         }
2161
2162       /* Figure out what exactly is being specialized at this point.
2163          Note that for an explicit instantiation, even one for a
2164          member function, we cannot tell apriori whether the
2165          instantiation is for a member template, or just a member
2166          function of a template class.  Even if a member template is
2167          being instantiated, the member template arguments may be
2168          elided if they can be deduced from the rest of the
2169          declaration.  */
2170       tmpl = determine_specialization (declarator, decl,
2171                                        &targs,
2172                                        member_specialization,
2173                                        template_count,
2174                                        tsk);
2175
2176       if (!tmpl || tmpl == error_mark_node)
2177         /* We couldn't figure out what this declaration was
2178            specializing.  */
2179         return error_mark_node;
2180       else
2181         {
2182           tree gen_tmpl = most_general_template (tmpl);
2183
2184           if (explicit_instantiation)
2185             {
2186               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2187                  is done by do_decl_instantiation later.  */
2188
2189               int arg_depth = TMPL_ARGS_DEPTH (targs);
2190               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2191
2192               if (arg_depth > parm_depth)
2193                 {
2194                   /* If TMPL is not the most general template (for
2195                      example, if TMPL is a friend template that is
2196                      injected into namespace scope), then there will
2197                      be too many levels of TARGS.  Remove some of them
2198                      here.  */
2199                   int i;
2200                   tree new_targs;
2201
2202                   new_targs = make_tree_vec (parm_depth);
2203                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2204                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2205                       = TREE_VEC_ELT (targs, i);
2206                   targs = new_targs;
2207                 }
2208
2209               return instantiate_template (tmpl, targs, tf_error);
2210             }
2211
2212           /* If we thought that the DECL was a member function, but it
2213              turns out to be specializing a static member function,
2214              make DECL a static member function as well.  */
2215           if (DECL_STATIC_FUNCTION_P (tmpl)
2216               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2217             revert_static_member_fn (decl);
2218
2219           /* If this is a specialization of a member template of a
2220              template class, we want to return the TEMPLATE_DECL, not
2221              the specialization of it.  */
2222           if (tsk == tsk_template)
2223             {
2224               tree result = DECL_TEMPLATE_RESULT (tmpl);
2225               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2226               DECL_INITIAL (result) = NULL_TREE;
2227               if (have_def)
2228                 {
2229                   tree parm;
2230                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2231                   DECL_SOURCE_LOCATION (result)
2232                     = DECL_SOURCE_LOCATION (decl);
2233                   /* We want to use the argument list specified in the
2234                      definition, not in the original declaration.  */
2235                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2236                   for (parm = DECL_ARGUMENTS (result); parm;
2237                        parm = TREE_CHAIN (parm))
2238                     DECL_CONTEXT (parm) = result;
2239                 }
2240               return tmpl;
2241             }
2242
2243           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2244           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2245
2246           /* Inherit default function arguments from the template
2247              DECL is specializing.  */
2248           copy_default_args_to_explicit_spec (decl);
2249
2250           /* This specialization has the same protection as the
2251              template it specializes.  */
2252           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2253           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2254
2255           /* 7.1.1-1 [dcl.stc]
2256
2257              A storage-class-specifier shall not be specified in an
2258              explicit specialization...
2259
2260              The parser rejects these, so unless action is taken here,
2261              explicit function specializations will always appear with
2262              global linkage.
2263
2264              The action recommended by the C++ CWG in response to C++
2265              defect report 605 is to make the storage class and linkage
2266              of the explicit specialization match the templated function:
2267
2268              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2269            */
2270           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2271             {
2272               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2273               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2274
2275               /* This specialization has the same linkage and visibility as
2276                  the function template it specializes.  */
2277               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2278               if (! TREE_PUBLIC (decl))
2279                 {
2280                   DECL_INTERFACE_KNOWN (decl) = 1;
2281                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2282                 }
2283               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2284               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2285                 {
2286                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2287                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2288                 }
2289             }
2290
2291           /* If DECL is a friend declaration, declared using an
2292              unqualified name, the namespace associated with DECL may
2293              have been set incorrectly.  For example, in:
2294
2295                template <typename T> void f(T);
2296                namespace N {
2297                  struct S { friend void f<int>(int); }
2298                }
2299
2300              we will have set the DECL_CONTEXT for the friend
2301              declaration to N, rather than to the global namespace.  */
2302           if (DECL_NAMESPACE_SCOPE_P (decl))
2303             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2304
2305           if (is_friend && !have_def)
2306             /* This is not really a declaration of a specialization.
2307                It's just the name of an instantiation.  But, it's not
2308                a request for an instantiation, either.  */
2309             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2310           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2311             /* This is indeed a specialization.  In case of constructors
2312                and destructors, we need in-charge and not-in-charge
2313                versions in V3 ABI.  */
2314             clone_function_decl (decl, /*update_method_vec_p=*/0);
2315
2316           /* Register this specialization so that we can find it
2317              again.  */
2318           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2319         }
2320     }
2321
2322   return decl;
2323 }
2324
2325 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2326    parameters.  These are represented in the same format used for
2327    DECL_TEMPLATE_PARMS.  */
2328
2329 int
2330 comp_template_parms (const_tree parms1, const_tree parms2)
2331 {
2332   const_tree p1;
2333   const_tree p2;
2334
2335   if (parms1 == parms2)
2336     return 1;
2337
2338   for (p1 = parms1, p2 = parms2;
2339        p1 != NULL_TREE && p2 != NULL_TREE;
2340        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2341     {
2342       tree t1 = TREE_VALUE (p1);
2343       tree t2 = TREE_VALUE (p2);
2344       int i;
2345
2346       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2347       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2348
2349       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2350         return 0;
2351
2352       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2353         {
2354           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2355           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2356
2357           /* If either of the template parameters are invalid, assume
2358              they match for the sake of error recovery. */
2359           if (parm1 == error_mark_node || parm2 == error_mark_node)
2360             return 1;
2361
2362           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2363             return 0;
2364
2365           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2366               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2367                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2368             continue;
2369           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2370             return 0;
2371         }
2372     }
2373
2374   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2375     /* One set of parameters has more parameters lists than the
2376        other.  */
2377     return 0;
2378
2379   return 1;
2380 }
2381
2382 /* Determine whether PARM is a parameter pack.  */
2383 bool 
2384 template_parameter_pack_p (const_tree parm)
2385 {
2386   /* Determine if we have a non-type template parameter pack.  */
2387   if (TREE_CODE (parm) == PARM_DECL)
2388     return (DECL_TEMPLATE_PARM_P (parm) 
2389             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2390
2391   /* If this is a list of template parameters, we could get a
2392      TYPE_DECL or a TEMPLATE_DECL.  */ 
2393   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2394     parm = TREE_TYPE (parm);
2395
2396   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2397            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2398           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2399 }
2400
2401 /* Determine whether ARGS describes a variadic template args list,
2402    i.e., one that is terminated by a template argument pack.  */
2403 static bool 
2404 template_args_variadic_p (tree args)
2405 {
2406   int nargs;
2407   tree last_parm;
2408
2409   if (args == NULL_TREE)
2410     return false;
2411
2412   args = INNERMOST_TEMPLATE_ARGS (args);
2413   nargs = TREE_VEC_LENGTH (args);
2414
2415   if (nargs == 0)
2416     return false;
2417
2418   last_parm = TREE_VEC_ELT (args, nargs - 1);
2419
2420   return ARGUMENT_PACK_P (last_parm);
2421 }
2422
2423 /* Generate a new name for the parameter pack name NAME (an
2424    IDENTIFIER_NODE) that incorporates its */
2425 static tree
2426 make_ith_pack_parameter_name (tree name, int i)
2427 {
2428   /* Munge the name to include the parameter index.  */
2429   char numbuf[128];
2430   char* newname;
2431   
2432   sprintf(numbuf, "%i", i);
2433   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2434   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2435   return get_identifier (newname);
2436 }
2437
2438 /* Structure used to track the progress of find_parameter_packs_r.  */
2439 struct find_parameter_pack_data 
2440 {
2441   /* TREE_LIST that will contain all of the parameter packs found by
2442      the traversal.  */
2443   tree* parameter_packs;
2444
2445   /* Set of AST nodes that have been visited by the traversal.  */
2446   struct pointer_set_t *visited;
2447 };
2448
2449 /* Identifies all of the argument packs that occur in a template
2450    argument and appends them to the TREE_LIST inside DATA, which is a
2451    find_parameter_pack_data structure. This is a subroutine of
2452    make_pack_expansion and uses_parameter_packs.  */
2453 static tree
2454 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2455 {
2456   tree t = *tp;
2457   struct find_parameter_pack_data* ppd = 
2458     (struct find_parameter_pack_data*)data;
2459   bool parameter_pack_p = false;
2460
2461   /* Identify whether this is a parameter pack or not.  */
2462   switch (TREE_CODE (t))
2463     {
2464     case TEMPLATE_PARM_INDEX:
2465       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2466         parameter_pack_p = true;
2467       break;
2468
2469     case TEMPLATE_TYPE_PARM:
2470     case TEMPLATE_TEMPLATE_PARM:
2471       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2472         parameter_pack_p = true;
2473       break;
2474
2475     case PARM_DECL:
2476       if (FUNCTION_PARAMETER_PACK_P (t))
2477         {
2478           /* We don't want to walk into the type of a PARM_DECL,
2479              because we don't want to see the type parameter pack.  */
2480           *walk_subtrees = 0;
2481           parameter_pack_p = true;
2482         }
2483       break;
2484
2485     default:
2486       /* Not a parameter pack.  */
2487       break;
2488     }
2489
2490   if (parameter_pack_p)
2491     {
2492       /* Add this parameter pack to the list.  */
2493       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2494     }
2495
2496   if (TYPE_P (t))
2497     cp_walk_tree (&TYPE_CONTEXT (t), 
2498                   &find_parameter_packs_r, ppd, ppd->visited);
2499
2500   /* This switch statement will return immediately if we don't find a
2501      parameter pack.  */
2502   switch (TREE_CODE (t)) 
2503     {
2504     case TEMPLATE_PARM_INDEX:
2505       return NULL_TREE;
2506
2507     case BOUND_TEMPLATE_TEMPLATE_PARM:
2508       /* Check the template itself.  */
2509       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2510                     &find_parameter_packs_r, ppd, ppd->visited);
2511       /* Check the template arguments.  */
2512       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2513                     ppd->visited);
2514       *walk_subtrees = 0;
2515       return NULL_TREE;
2516
2517     case TEMPLATE_TYPE_PARM:
2518     case TEMPLATE_TEMPLATE_PARM:
2519       return NULL_TREE;
2520
2521     case PARM_DECL:
2522       return NULL_TREE;
2523
2524     case RECORD_TYPE:
2525       if (TYPE_PTRMEMFUNC_P (t))
2526         return NULL_TREE;
2527       /* Fall through.  */
2528
2529     case UNION_TYPE:
2530     case ENUMERAL_TYPE:
2531       if (TYPE_TEMPLATE_INFO (t))
2532         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2533                       &find_parameter_packs_r, ppd, ppd->visited);
2534
2535       *walk_subtrees = 0;
2536       return NULL_TREE;
2537
2538     case TEMPLATE_DECL:
2539       cp_walk_tree (&TREE_TYPE (t),
2540                     &find_parameter_packs_r, ppd, ppd->visited);
2541       return NULL_TREE;
2542  
2543     case TYPENAME_TYPE:
2544       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2545                    ppd, ppd->visited);
2546       *walk_subtrees = 0;
2547       return NULL_TREE;
2548       
2549     case TYPE_PACK_EXPANSION:
2550     case EXPR_PACK_EXPANSION:
2551       *walk_subtrees = 0;
2552       return NULL_TREE;
2553
2554     case INTEGER_TYPE:
2555       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2556                     ppd, ppd->visited);
2557       *walk_subtrees = 0;
2558       return NULL_TREE;
2559
2560     case IDENTIFIER_NODE:
2561       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2562                     ppd->visited);
2563       *walk_subtrees = 0;
2564       return NULL_TREE;
2565
2566     default:
2567       return NULL_TREE;
2568     }
2569
2570   return NULL_TREE;
2571 }
2572
2573 /* Determines if the expression or type T uses any parameter packs.  */
2574 bool
2575 uses_parameter_packs (tree t)
2576 {
2577   tree parameter_packs = NULL_TREE;
2578   struct find_parameter_pack_data ppd;
2579   ppd.parameter_packs = &parameter_packs;
2580   ppd.visited = pointer_set_create ();
2581   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2582   pointer_set_destroy (ppd.visited);
2583   return parameter_packs != NULL_TREE;
2584 }
2585
2586 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2587    representation a base-class initializer into a parameter pack
2588    expansion. If all goes well, the resulting node will be an
2589    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2590    respectively.  */
2591 tree 
2592 make_pack_expansion (tree arg)
2593 {
2594   tree result;
2595   tree parameter_packs = NULL_TREE;
2596   bool for_types = false;
2597   struct find_parameter_pack_data ppd;
2598
2599   if (!arg || arg == error_mark_node)
2600     return arg;
2601
2602   if (TREE_CODE (arg) == TREE_LIST)
2603     {
2604       /* The only time we will see a TREE_LIST here is for a base
2605          class initializer.  In this case, the TREE_PURPOSE will be a
2606          _TYPE node (representing the base class expansion we're
2607          initializing) and the TREE_VALUE will be a TREE_LIST
2608          containing the initialization arguments. 
2609
2610          The resulting expansion looks somewhat different from most
2611          expansions. Rather than returning just one _EXPANSION, we
2612          return a TREE_LIST whose TREE_PURPOSE is a
2613          TYPE_PACK_EXPANSION containing the bases that will be
2614          initialized.  The TREE_VALUE will be identical to the
2615          original TREE_VALUE, which is a list of arguments that will
2616          be passed to each base.  We do not introduce any new pack
2617          expansion nodes into the TREE_VALUE (although it is possible
2618          that some already exist), because the TREE_PURPOSE and
2619          TREE_VALUE all need to be expanded together with the same
2620          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2621          resulting TREE_PURPOSE will mention the parameter packs in
2622          both the bases and the arguments to the bases.  */
2623       tree purpose;
2624       tree value;
2625       tree parameter_packs = NULL_TREE;
2626
2627       /* Determine which parameter packs will be used by the base
2628          class expansion.  */
2629       ppd.visited = pointer_set_create ();
2630       ppd.parameter_packs = &parameter_packs;
2631       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2632                     &ppd, ppd.visited);
2633
2634       if (parameter_packs == NULL_TREE)
2635         {
2636           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2637           pointer_set_destroy (ppd.visited);
2638           return error_mark_node;
2639         }
2640
2641       if (TREE_VALUE (arg) != void_type_node)
2642         {
2643           /* Collect the sets of parameter packs used in each of the
2644              initialization arguments.  */
2645           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2646             {
2647               /* Determine which parameter packs will be expanded in this
2648                  argument.  */
2649               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2650                             &ppd, ppd.visited);
2651             }
2652         }
2653
2654       pointer_set_destroy (ppd.visited);
2655
2656       /* Create the pack expansion type for the base type.  */
2657       purpose = make_node (TYPE_PACK_EXPANSION);
2658       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2659       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2660
2661       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2662          they will rarely be compared to anything.  */
2663       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2664
2665       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2666     }
2667
2668   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2669     for_types = true;
2670
2671   /* Build the PACK_EXPANSION_* node.  */
2672   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2673   SET_PACK_EXPANSION_PATTERN (result, arg);
2674   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2675     {
2676       /* Propagate type and const-expression information.  */
2677       TREE_TYPE (result) = TREE_TYPE (arg);
2678       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2679     }
2680   else
2681     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2682        they will rarely be compared to anything.  */
2683     SET_TYPE_STRUCTURAL_EQUALITY (result);
2684
2685   /* Determine which parameter packs will be expanded.  */
2686   ppd.parameter_packs = &parameter_packs;
2687   ppd.visited = pointer_set_create ();
2688   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2689   pointer_set_destroy (ppd.visited);
2690
2691   /* Make sure we found some parameter packs.  */
2692   if (parameter_packs == NULL_TREE)
2693     {
2694       if (TYPE_P (arg))
2695         error ("expansion pattern %<%T%> contains no argument packs", arg);
2696       else
2697         error ("expansion pattern %<%E%> contains no argument packs", arg);
2698       return error_mark_node;
2699     }
2700   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2701
2702   return result;
2703 }
2704
2705 /* Checks T for any "bare" parameter packs, which have not yet been
2706    expanded, and issues an error if any are found. This operation can
2707    only be done on full expressions or types (e.g., an expression
2708    statement, "if" condition, etc.), because we could have expressions like:
2709
2710      foo(f(g(h(args)))...)
2711
2712    where "args" is a parameter pack. check_for_bare_parameter_packs
2713    should not be called for the subexpressions args, h(args),
2714    g(h(args)), or f(g(h(args))), because we would produce erroneous
2715    error messages. 
2716
2717    Returns TRUE and emits an error if there were bare parameter packs,
2718    returns FALSE otherwise.  */
2719 bool 
2720 check_for_bare_parameter_packs (tree t)
2721 {
2722   tree parameter_packs = NULL_TREE;
2723   struct find_parameter_pack_data ppd;
2724
2725   if (!processing_template_decl || !t || t == error_mark_node)
2726     return false;
2727
2728   if (TREE_CODE (t) == TYPE_DECL)
2729     t = TREE_TYPE (t);
2730
2731   ppd.parameter_packs = &parameter_packs;
2732   ppd.visited = pointer_set_create ();
2733   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2734   pointer_set_destroy (ppd.visited);
2735
2736   if (parameter_packs) 
2737     {
2738       error ("parameter packs not expanded with %<...%>:");
2739       while (parameter_packs)
2740         {
2741           tree pack = TREE_VALUE (parameter_packs);
2742           tree name = NULL_TREE;
2743
2744           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2745               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2746             name = TYPE_NAME (pack);
2747           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2748             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2749           else
2750             name = DECL_NAME (pack);
2751
2752           if (name)
2753             inform (input_location, "        %qD", name);
2754           else
2755             inform (input_location, "        <anonymous>");
2756
2757           parameter_packs = TREE_CHAIN (parameter_packs);
2758         }
2759
2760       return true;
2761     }
2762
2763   return false;
2764 }
2765
2766 /* Expand any parameter packs that occur in the template arguments in
2767    ARGS.  */
2768 tree
2769 expand_template_argument_pack (tree args)
2770 {
2771   tree result_args = NULL_TREE;
2772   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2773   int num_result_args = -1;
2774
2775   /* First, determine if we need to expand anything, and the number of
2776      slots we'll need.  */
2777   for (in_arg = 0; in_arg < nargs; ++in_arg)
2778     {
2779       tree arg = TREE_VEC_ELT (args, in_arg);
2780       if (ARGUMENT_PACK_P (arg))
2781         {
2782           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2783           if (num_result_args < 0)
2784             num_result_args = in_arg + num_packed;
2785           else
2786             num_result_args += num_packed;
2787         }
2788       else
2789         {
2790           if (num_result_args >= 0)
2791             num_result_args++;
2792         }
2793     }
2794
2795   /* If no expansion is necessary, we're done.  */
2796   if (num_result_args < 0)
2797     return args;
2798
2799   /* Expand arguments.  */
2800   result_args = make_tree_vec (num_result_args);
2801   for (in_arg = 0; in_arg < nargs; ++in_arg)
2802     {
2803       tree arg = TREE_VEC_ELT (args, in_arg);
2804       if (ARGUMENT_PACK_P (arg))
2805         {
2806           tree packed = ARGUMENT_PACK_ARGS (arg);
2807           int i, num_packed = TREE_VEC_LENGTH (packed);
2808           for (i = 0; i < num_packed; ++i, ++out_arg)
2809             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2810         }
2811       else
2812         {
2813           TREE_VEC_ELT (result_args, out_arg) = arg;
2814           ++out_arg;
2815         }
2816     }
2817
2818   return result_args;
2819 }
2820
2821 /* Checks if DECL shadows a template parameter.
2822
2823    [temp.local]: A template-parameter shall not be redeclared within its
2824    scope (including nested scopes).
2825
2826    Emits an error and returns TRUE if the DECL shadows a parameter,
2827    returns FALSE otherwise.  */
2828
2829 bool
2830 check_template_shadow (tree decl)
2831 {
2832   tree olddecl;
2833
2834   /* If we're not in a template, we can't possibly shadow a template
2835      parameter.  */
2836   if (!current_template_parms)
2837     return true;
2838
2839   /* Figure out what we're shadowing.  */
2840   if (TREE_CODE (decl) == OVERLOAD)
2841     decl = OVL_CURRENT (decl);
2842   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2843
2844   /* If there's no previous binding for this name, we're not shadowing
2845      anything, let alone a template parameter.  */
2846   if (!olddecl)
2847     return true;
2848
2849   /* If we're not shadowing a template parameter, we're done.  Note
2850      that OLDDECL might be an OVERLOAD (or perhaps even an
2851      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2852      node.  */
2853   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2854     return true;
2855
2856   /* We check for decl != olddecl to avoid bogus errors for using a
2857      name inside a class.  We check TPFI to avoid duplicate errors for
2858      inline member templates.  */
2859   if (decl == olddecl
2860       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2861     return true;
2862
2863   error ("declaration of %q+#D", decl);
2864   error (" shadows template parm %q+#D", olddecl);
2865   return false;
2866 }
2867
2868 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2869    ORIG_LEVEL, DECL, and TYPE.  */
2870
2871 static tree
2872 build_template_parm_index (int index,
2873                            int level,
2874                            int orig_level,
2875                            tree decl,
2876                            tree type)
2877 {
2878   tree t = make_node (TEMPLATE_PARM_INDEX);
2879   TEMPLATE_PARM_IDX (t) = index;
2880   TEMPLATE_PARM_LEVEL (t) = level;
2881   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2882   TEMPLATE_PARM_DECL (t) = decl;
2883   TREE_TYPE (t) = type;
2884   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2885   TREE_READONLY (t) = TREE_READONLY (decl);
2886
2887   return t;
2888 }
2889
2890 /* Find the canonical type parameter for the given template type
2891    parameter.  Returns the canonical type parameter, which may be TYPE
2892    if no such parameter existed.  */
2893 static tree
2894 canonical_type_parameter (tree type)
2895 {
2896   tree list;
2897   int idx = TEMPLATE_TYPE_IDX (type);
2898   if (!canonical_template_parms)
2899     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2900
2901   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2902     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2903
2904   list = VEC_index (tree, canonical_template_parms, idx);
2905   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2906     list = TREE_CHAIN (list);
2907
2908   if (list)
2909     return TREE_VALUE (list);
2910   else
2911     {
2912       VEC_replace(tree, canonical_template_parms, idx,
2913                   tree_cons (NULL_TREE, type, 
2914                              VEC_index (tree, canonical_template_parms, idx)));
2915       return type;
2916     }
2917 }
2918
2919 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2920    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2921    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2922    new one is created.  */
2923
2924 static tree
2925 reduce_template_parm_level (tree index, tree type, int levels, tree args,
2926                             tsubst_flags_t complain)
2927 {
2928   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2929       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2930           != TEMPLATE_PARM_LEVEL (index) - levels))
2931     {
2932       tree orig_decl = TEMPLATE_PARM_DECL (index);
2933       tree decl, t;
2934
2935       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
2936                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2937       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2938       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2939       DECL_ARTIFICIAL (decl) = 1;
2940       SET_DECL_TEMPLATE_PARM_P (decl);
2941
2942       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2943                                      TEMPLATE_PARM_LEVEL (index) - levels,
2944                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2945                                      decl, type);
2946       TEMPLATE_PARM_DESCENDANTS (index) = t;
2947       TEMPLATE_PARM_PARAMETER_PACK (t) 
2948         = TEMPLATE_PARM_PARAMETER_PACK (index);
2949
2950         /* Template template parameters need this.  */
2951       if (TREE_CODE (decl) == TEMPLATE_DECL)
2952         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
2953           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
2954            args, complain);
2955     }
2956
2957   return TEMPLATE_PARM_DESCENDANTS (index);
2958 }
2959
2960 /* Process information from new template parameter PARM and append it to the
2961    LIST being built.  This new parameter is a non-type parameter iff
2962    IS_NON_TYPE is true. This new parameter is a parameter
2963    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
2964    PARM_LOC.  */
2965
2966 tree
2967 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
2968                        bool is_parameter_pack)
2969 {
2970   tree decl = 0;
2971   tree defval;
2972   tree err_parm_list;
2973   int idx = 0;
2974
2975   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2976   defval = TREE_PURPOSE (parm);
2977
2978   if (list)
2979     {
2980       tree p = tree_last (list);
2981
2982       if (p && TREE_VALUE (p) != error_mark_node)
2983         {
2984           p = TREE_VALUE (p);
2985           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2986             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2987           else
2988             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2989         }
2990
2991       ++idx;
2992     }
2993   else
2994     idx = 0;
2995
2996   if (is_non_type)
2997     {
2998       parm = TREE_VALUE (parm);
2999
3000       SET_DECL_TEMPLATE_PARM_P (parm);
3001
3002       if (TREE_TYPE (parm) == error_mark_node)
3003         {
3004           err_parm_list = build_tree_list (defval, parm);
3005           TREE_VALUE (err_parm_list) = error_mark_node;
3006            return chainon (list, err_parm_list);
3007         }
3008       else
3009       {
3010         /* [temp.param]
3011
3012            The top-level cv-qualifiers on the template-parameter are
3013            ignored when determining its type.  */
3014         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3015         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3016           {
3017             err_parm_list = build_tree_list (defval, parm);
3018             TREE_VALUE (err_parm_list) = error_mark_node;
3019              return chainon (list, err_parm_list);
3020           }
3021
3022         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3023           {
3024             /* This template parameter is not a parameter pack, but it
3025                should be. Complain about "bare" parameter packs.  */
3026             check_for_bare_parameter_packs (TREE_TYPE (parm));
3027             
3028             /* Recover by calling this a parameter pack.  */
3029             is_parameter_pack = true;
3030           }
3031       }
3032
3033       /* A template parameter is not modifiable.  */
3034       TREE_CONSTANT (parm) = 1;
3035       TREE_READONLY (parm) = 1;
3036       decl = build_decl (parm_loc,
3037                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3038       TREE_CONSTANT (decl) = 1;
3039       TREE_READONLY (decl) = 1;
3040       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3041         = build_template_parm_index (idx, processing_template_decl,
3042                                      processing_template_decl,
3043                                      decl, TREE_TYPE (parm));
3044
3045       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3046         = is_parameter_pack;
3047     }
3048   else
3049     {
3050       tree t;
3051       parm = TREE_VALUE (TREE_VALUE (parm));
3052
3053       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3054         {
3055           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3056           /* This is for distinguishing between real templates and template
3057              template parameters */
3058           TREE_TYPE (parm) = t;
3059           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3060           decl = parm;
3061         }
3062       else
3063         {
3064           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3065           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3066           decl = build_decl (parm_loc,
3067                              TYPE_DECL, parm, t);
3068         }
3069
3070       TYPE_NAME (t) = decl;
3071       TYPE_STUB_DECL (t) = decl;
3072       parm = decl;
3073       TEMPLATE_TYPE_PARM_INDEX (t)
3074         = build_template_parm_index (idx, processing_template_decl,
3075                                      processing_template_decl,
3076                                      decl, TREE_TYPE (parm));
3077       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3078       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3079     }
3080   DECL_ARTIFICIAL (decl) = 1;
3081   SET_DECL_TEMPLATE_PARM_P (decl);
3082   pushdecl (decl);
3083   parm = build_tree_list (defval, parm);
3084   return chainon (list, parm);
3085 }
3086
3087 /* The end of a template parameter list has been reached.  Process the
3088    tree list into a parameter vector, converting each parameter into a more
3089    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3090    as PARM_DECLs.  */
3091
3092 tree
3093 end_template_parm_list (tree parms)
3094 {
3095   int nparms;
3096   tree parm, next;
3097   tree saved_parmlist = make_tree_vec (list_length (parms));
3098
3099   current_template_parms
3100     = tree_cons (size_int (processing_template_decl),
3101                  saved_parmlist, current_template_parms);
3102
3103   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3104     {
3105       next = TREE_CHAIN (parm);
3106       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3107       TREE_CHAIN (parm) = NULL_TREE;
3108     }
3109
3110   --processing_template_parmlist;
3111
3112   return saved_parmlist;
3113 }
3114
3115 /* end_template_decl is called after a template declaration is seen.  */
3116
3117 void
3118 end_template_decl (void)
3119 {
3120   reset_specialization ();
3121
3122   if (! processing_template_decl)
3123     return;
3124
3125   /* This matches the pushlevel in begin_template_parm_list.  */
3126   finish_scope ();
3127
3128   --processing_template_decl;
3129   current_template_parms = TREE_CHAIN (current_template_parms);
3130 }
3131
3132 /* Within the declaration of a template, return all levels of template
3133    parameters that apply.  The template parameters are represented as
3134    a TREE_VEC, in the form documented in cp-tree.h for template
3135    arguments.  */
3136
3137 static tree
3138 current_template_args (void)
3139 {
3140   tree header;
3141   tree args = NULL_TREE;
3142   int length = TMPL_PARMS_DEPTH (current_template_parms);
3143   int l = length;
3144
3145   /* If there is only one level of template parameters, we do not
3146      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3147      TREE_VEC containing the arguments.  */
3148   if (length > 1)
3149     args = make_tree_vec (length);
3150
3151   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3152     {
3153       tree a = copy_node (TREE_VALUE (header));
3154       int i;
3155
3156       TREE_TYPE (a) = NULL_TREE;
3157       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3158         {
3159           tree t = TREE_VEC_ELT (a, i);
3160
3161           /* T will be a list if we are called from within a
3162              begin/end_template_parm_list pair, but a vector directly
3163              if within a begin/end_member_template_processing pair.  */
3164           if (TREE_CODE (t) == TREE_LIST)
3165             {
3166               t = TREE_VALUE (t);
3167
3168               if (!error_operand_p (t))
3169                 {
3170                   if (TREE_CODE (t) == TYPE_DECL
3171                       || TREE_CODE (t) == TEMPLATE_DECL)
3172                     {
3173                       t = TREE_TYPE (t);
3174                       
3175                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3176                         {
3177                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3178                              with a single element, which expands T.  */
3179                           tree vec = make_tree_vec (1);
3180                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3181                           
3182                           t = make_node (TYPE_ARGUMENT_PACK);
3183                           SET_ARGUMENT_PACK_ARGS (t, vec);
3184                         }
3185                     }
3186                   else
3187                     {
3188                       t = DECL_INITIAL (t);
3189                       
3190                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3191                         {
3192                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3193                              with a single element, which expands T.  */
3194                           tree vec = make_tree_vec (1);
3195                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3196                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3197                           
3198                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3199                           SET_ARGUMENT_PACK_ARGS (t, vec);
3200                           TREE_TYPE (t) = type;
3201                         }
3202                     }
3203                   TREE_VEC_ELT (a, i) = t;
3204                 }
3205             }
3206         }
3207
3208       if (length > 1)
3209         TREE_VEC_ELT (args, --l) = a;
3210       else
3211         args = a;
3212     }
3213
3214   return args;
3215 }
3216
3217 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3218    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3219    a member template.  Used by push_template_decl below.  */
3220
3221 static tree
3222 build_template_decl (tree decl, tree parms, bool member_template_p)
3223 {
3224   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3225   DECL_TEMPLATE_PARMS (tmpl) = parms;
3226   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3227   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3228   if (DECL_LANG_SPECIFIC (decl))
3229     {
3230       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3231       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3232       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3233       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3234       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3235       if (DECL_OVERLOADED_OPERATOR_P (decl))
3236         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3237                                       DECL_OVERLOADED_OPERATOR_P (decl));
3238     }
3239
3240   return tmpl;
3241 }
3242
3243 struct template_parm_data
3244 {
3245   /* The level of the template parameters we are currently
3246      processing.  */
3247   int level;
3248
3249   /* The index of the specialization argument we are currently
3250      processing.  */
3251   int current_arg;
3252
3253   /* An array whose size is the number of template parameters.  The
3254      elements are nonzero if the parameter has been used in any one
3255      of the arguments processed so far.  */
3256   int* parms;
3257
3258   /* An array whose size is the number of template arguments.  The
3259      elements are nonzero if the argument makes use of template
3260      parameters of this level.  */
3261   int* arg_uses_template_parms;
3262 };
3263
3264 /* Subroutine of push_template_decl used to see if each template
3265    parameter in a partial specialization is used in the explicit
3266    argument list.  If T is of the LEVEL given in DATA (which is
3267    treated as a template_parm_data*), then DATA->PARMS is marked
3268    appropriately.  */
3269
3270 static int
3271 mark_template_parm (tree t, void* data)
3272 {
3273   int level;
3274   int idx;
3275   struct template_parm_data* tpd = (struct template_parm_data*) data;
3276
3277   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3278     {
3279       level = TEMPLATE_PARM_LEVEL (t);
3280       idx = TEMPLATE_PARM_IDX (t);
3281     }
3282   else
3283     {
3284       level = TEMPLATE_TYPE_LEVEL (t);
3285       idx = TEMPLATE_TYPE_IDX (t);
3286     }
3287
3288   if (level == tpd->level)
3289     {
3290       tpd->parms[idx] = 1;
3291       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3292     }
3293
3294   /* Return zero so that for_each_template_parm will continue the
3295      traversal of the tree; we want to mark *every* template parm.  */
3296   return 0;
3297 }
3298
3299 /* Process the partial specialization DECL.  */
3300
3301 static tree
3302 process_partial_specialization (tree decl)
3303 {
3304   tree type = TREE_TYPE (decl);
3305   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3306   tree specargs = CLASSTYPE_TI_ARGS (type);
3307   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3308   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3309   tree inner_parms;
3310   int nargs = TREE_VEC_LENGTH (inner_args);
3311   int ntparms;
3312   int  i;
3313   int did_error_intro = 0;
3314   struct template_parm_data tpd;
3315   struct template_parm_data tpd2;
3316
3317   gcc_assert (current_template_parms);
3318
3319   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3320   ntparms = TREE_VEC_LENGTH (inner_parms);
3321
3322   /* We check that each of the template parameters given in the
3323      partial specialization is used in the argument list to the
3324      specialization.  For example:
3325
3326        template <class T> struct S;
3327        template <class T> struct S<T*>;
3328
3329      The second declaration is OK because `T*' uses the template
3330      parameter T, whereas
3331
3332        template <class T> struct S<int>;
3333
3334      is no good.  Even trickier is:
3335
3336        template <class T>
3337        struct S1
3338        {
3339           template <class U>
3340           struct S2;
3341           template <class U>
3342           struct S2<T>;
3343        };
3344
3345      The S2<T> declaration is actually invalid; it is a
3346      full-specialization.  Of course,
3347
3348           template <class U>
3349           struct S2<T (*)(U)>;
3350
3351      or some such would have been OK.  */
3352   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3353   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3354   memset (tpd.parms, 0, sizeof (int) * ntparms);
3355
3356   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3357   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3358   for (i = 0; i < nargs; ++i)
3359     {
3360       tpd.current_arg = i;
3361       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3362                               &mark_template_parm,
3363                               &tpd,
3364                               NULL,
3365                               /*include_nondeduced_p=*/false);
3366     }
3367   for (i = 0; i < ntparms; ++i)
3368     if (tpd.parms[i] == 0)
3369       {
3370         /* One of the template parms was not used in the
3371            specialization.  */
3372         if (!did_error_intro)
3373           {
3374             error ("template parameters not used in partial specialization:");
3375             did_error_intro = 1;
3376           }
3377
3378         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3379       }
3380
3381   /* [temp.class.spec]
3382
3383      The argument list of the specialization shall not be identical to
3384      the implicit argument list of the primary template.  */
3385   if (comp_template_args
3386       (inner_args,
3387        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3388                                                    (maintmpl)))))
3389     error ("partial specialization %qT does not specialize any template arguments", type);
3390
3391   /* [temp.class.spec]
3392
3393      A partially specialized non-type argument expression shall not
3394      involve template parameters of the partial specialization except
3395      when the argument expression is a simple identifier.
3396
3397      The type of a template parameter corresponding to a specialized
3398      non-type argument shall not be dependent on a parameter of the
3399      specialization. 
3400
3401      Also, we verify that pack expansions only occur at the
3402      end of the argument list.  */
3403   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3404   tpd2.parms = 0;
3405   for (i = 0; i < nargs; ++i)
3406     {
3407       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3408       tree arg = TREE_VEC_ELT (inner_args, i);
3409       tree packed_args = NULL_TREE;
3410       int j, len = 1;
3411
3412       if (ARGUMENT_PACK_P (arg))
3413         {
3414           /* Extract the arguments from the argument pack. We'll be
3415              iterating over these in the following loop.  */
3416           packed_args = ARGUMENT_PACK_ARGS (arg);
3417           len = TREE_VEC_LENGTH (packed_args);
3418         }
3419
3420       for (j = 0; j < len; j++)
3421         {
3422           if (packed_args)
3423             /* Get the Jth argument in the parameter pack.  */
3424             arg = TREE_VEC_ELT (packed_args, j);
3425
3426           if (PACK_EXPANSION_P (arg))
3427             {
3428               /* Pack expansions must come at the end of the
3429                  argument list.  */
3430               if ((packed_args && j < len - 1)
3431                   || (!packed_args && i < nargs - 1))
3432                 {
3433                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3434                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3435                   else
3436                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3437
3438                   if (packed_args)
3439                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3440                 }
3441             }
3442
3443           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3444             /* We only care about the pattern.  */
3445             arg = PACK_EXPANSION_PATTERN (arg);
3446
3447           if (/* These first two lines are the `non-type' bit.  */
3448               !TYPE_P (arg)
3449               && TREE_CODE (arg) != TEMPLATE_DECL
3450               /* This next line is the `argument expression is not just a
3451                  simple identifier' condition and also the `specialized
3452                  non-type argument' bit.  */
3453               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3454             {
3455               if ((!packed_args && tpd.arg_uses_template_parms[i])
3456                   || (packed_args && uses_template_parms (arg)))
3457                 error ("template argument %qE involves template parameter(s)",
3458                        arg);
3459               else 
3460                 {
3461                   /* Look at the corresponding template parameter,
3462                      marking which template parameters its type depends
3463                      upon.  */
3464                   tree type = TREE_TYPE (parm);
3465
3466                   if (!tpd2.parms)
3467                     {
3468                       /* We haven't yet initialized TPD2.  Do so now.  */
3469                       tpd2.arg_uses_template_parms 
3470                         = (int *) alloca (sizeof (int) * nargs);
3471                       /* The number of parameters here is the number in the
3472                          main template, which, as checked in the assertion
3473                          above, is NARGS.  */
3474                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3475                       tpd2.level = 
3476                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3477                     }
3478
3479                   /* Mark the template parameters.  But this time, we're
3480                      looking for the template parameters of the main
3481                      template, not in the specialization.  */
3482                   tpd2.current_arg = i;
3483                   tpd2.arg_uses_template_parms[i] = 0;
3484                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3485                   for_each_template_parm (type,
3486                                           &mark_template_parm,
3487                                           &tpd2,
3488                                           NULL,
3489                                           /*include_nondeduced_p=*/false);
3490
3491                   if (tpd2.arg_uses_template_parms [i])
3492                     {
3493                       /* The type depended on some template parameters.
3494                          If they are fully specialized in the
3495                          specialization, that's OK.  */
3496                       int j;
3497                       for (j = 0; j < nargs; ++j)
3498                         if (tpd2.parms[j] != 0
3499                             && tpd.arg_uses_template_parms [j])
3500                           {
3501                             error ("type %qT of template argument %qE depends "
3502                                    "on template parameter(s)", 
3503                                    type,
3504                                    arg);
3505                             break;
3506                           }
3507                     }
3508                 }
3509             }
3510         }
3511     }
3512
3513   if (retrieve_specialization (maintmpl, specargs,
3514                                /*class_specializations_p=*/true))
3515     /* We've already got this specialization.  */
3516     return decl;
3517
3518   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3519     = tree_cons (specargs, inner_parms,
3520                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3521   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3522   return decl;
3523 }
3524
3525 /* Check that a template declaration's use of default arguments and
3526    parameter packs is not invalid.  Here, PARMS are the template
3527    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3528    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3529    specialization.
3530    
3531
3532    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3533    declaration (but not a definition); 1 indicates a declaration, 2
3534    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3535    emitted for extraneous default arguments.
3536
3537    Returns TRUE if there were no errors found, FALSE otherwise. */
3538
3539 bool
3540 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3541                          int is_partial, int is_friend_decl)
3542 {
3543   const char *msg;
3544   int last_level_to_check;
3545   tree parm_level;
3546   bool no_errors = true;
3547
3548   /* [temp.param]
3549
3550      A default template-argument shall not be specified in a
3551      function template declaration or a function template definition, nor
3552      in the template-parameter-list of the definition of a member of a
3553      class template.  */
3554
3555   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3556     /* You can't have a function template declaration in a local
3557        scope, nor you can you define a member of a class template in a
3558        local scope.  */
3559     return true;
3560
3561   if (current_class_type
3562       && !TYPE_BEING_DEFINED (current_class_type)
3563       && DECL_LANG_SPECIFIC (decl)
3564       /* If this is either a friend defined in the scope of the class
3565          or a member function.  */
3566       && (DECL_FUNCTION_MEMBER_P (decl)
3567           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3568           : DECL_FRIEND_CONTEXT (decl)
3569           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3570           : false)
3571       /* And, if it was a member function, it really was defined in
3572          the scope of the class.  */
3573       && (!DECL_FUNCTION_MEMBER_P (decl)
3574           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3575     /* We already checked these parameters when the template was
3576        declared, so there's no need to do it again now.  This function
3577        was defined in class scope, but we're processing it's body now
3578        that the class is complete.  */
3579     return true;
3580
3581   /* Core issue 226 (C++0x only): the following only applies to class
3582      templates.  */
3583   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3584     {
3585       /* [temp.param]
3586
3587          If a template-parameter has a default template-argument, all
3588          subsequent template-parameters shall have a default
3589          template-argument supplied.  */
3590       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3591         {
3592           tree inner_parms = TREE_VALUE (parm_level);
3593           int ntparms = TREE_VEC_LENGTH (inner_parms);
3594           int seen_def_arg_p = 0;
3595           int i;
3596
3597           for (i = 0; i < ntparms; ++i)
3598             {
3599               tree parm = TREE_VEC_ELT (inner_parms, i);
3600
3601               if (parm == error_mark_node)
3602                 continue;
3603
3604               if (TREE_PURPOSE (parm))
3605                 seen_def_arg_p = 1;
3606               else if (seen_def_arg_p
3607                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3608                 {
3609                   error ("no default argument for %qD", TREE_VALUE (parm));
3610                   /* For better subsequent error-recovery, we indicate that
3611                      there should have been a default argument.  */
3612                   TREE_PURPOSE (parm) = error_mark_node;
3613                   no_errors = false;
3614                 }
3615               else if (is_primary
3616                        && !is_partial
3617                        && !is_friend_decl
3618                        /* Don't complain about an enclosing partial
3619                           specialization.  */
3620                        && parm_level == parms
3621                        && TREE_CODE (decl) == TYPE_DECL
3622                        && i < ntparms - 1
3623                        && template_parameter_pack_p (TREE_VALUE (parm)))
3624                 {
3625                   /* A primary class template can only have one
3626                      parameter pack, at the end of the template
3627                      parameter list.  */
3628
3629                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3630                     error ("parameter pack %qE must be at the end of the"
3631                            " template parameter list", TREE_VALUE (parm));
3632                   else
3633                     error ("parameter pack %qT must be at the end of the"
3634                            " template parameter list", 
3635                            TREE_TYPE (TREE_VALUE (parm)));
3636
3637                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3638                     = error_mark_node;
3639                   no_errors = false;
3640                 }
3641             }
3642         }
3643     }
3644
3645   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3646       || is_partial 
3647       || !is_primary
3648       || is_friend_decl)
3649     /* For an ordinary class template, default template arguments are
3650        allowed at the innermost level, e.g.:
3651          template <class T = int>
3652          struct S {};
3653        but, in a partial specialization, they're not allowed even
3654        there, as we have in [temp.class.spec]:
3655
3656          The template parameter list of a specialization shall not
3657          contain default template argument values.
3658
3659        So, for a partial specialization, or for a function template
3660        (in C++98/C++03), we look at all of them.  */
3661     ;
3662   else
3663     /* But, for a primary class template that is not a partial
3664        specialization we look at all template parameters except the
3665        innermost ones.  */
3666     parms = TREE_CHAIN (parms);
3667
3668   /* Figure out what error message to issue.  */
3669   if (is_friend_decl == 2)
3670     msg = "default template arguments may not be used in function template friend re-declaration";
3671   else if (is_friend_decl)
3672     msg = "default template arguments may not be used in function template friend declarations";
3673   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3674     msg = "default template arguments may not be used in function templates";
3675   else if (is_partial)
3676     msg = "default template arguments may not be used in partial specializations";
3677   else
3678     msg = "default argument for template parameter for class enclosing %qD";
3679
3680   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3681     /* If we're inside a class definition, there's no need to
3682        examine the parameters to the class itself.  On the one
3683        hand, they will be checked when the class is defined, and,
3684        on the other, default arguments are valid in things like:
3685          template <class T = double>
3686          struct S { template <class U> void f(U); };
3687        Here the default argument for `S' has no bearing on the
3688        declaration of `f'.  */
3689     last_level_to_check = template_class_depth (current_class_type) + 1;
3690   else
3691     /* Check everything.  */
3692     last_level_to_check = 0;
3693
3694   for (parm_level = parms;
3695        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3696        parm_level = TREE_CHAIN (parm_level))
3697     {
3698       tree inner_parms = TREE_VALUE (parm_level);
3699       int i;
3700       int ntparms;
3701
3702       ntparms = TREE_VEC_LENGTH (inner_parms);
3703       for (i = 0; i < ntparms; ++i)
3704         {
3705           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3706             continue;
3707
3708           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3709             {
3710               if (msg)
3711                 {
3712                   no_errors = false;
3713                   if (is_friend_decl == 2)
3714                     return no_errors;
3715
3716                   error (msg, decl);
3717                   msg = 0;
3718                 }
3719
3720               /* Clear out the default argument so that we are not
3721                  confused later.  */
3722               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3723             }
3724         }
3725
3726       /* At this point, if we're still interested in issuing messages,
3727          they must apply to classes surrounding the object declared.  */
3728       if (msg)
3729         msg = "default argument for template parameter for class enclosing %qD";
3730     }
3731
3732   return no_errors;
3733 }
3734
3735 /* Worker for push_template_decl_real, called via
3736    for_each_template_parm.  DATA is really an int, indicating the
3737    level of the parameters we are interested in.  If T is a template
3738    parameter of that level, return nonzero.  */
3739
3740 static int
3741 template_parm_this_level_p (tree t, void* data)
3742 {
3743   int this_level = *(int *)data;
3744   int level;
3745
3746   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3747     level = TEMPLATE_PARM_LEVEL (t);
3748   else
3749     level = TEMPLATE_TYPE_LEVEL (t);
3750   return level == this_level;
3751 }
3752
3753 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3754    parameters given by current_template_args, or reuses a
3755    previously existing one, if appropriate.  Returns the DECL, or an
3756    equivalent one, if it is replaced via a call to duplicate_decls.
3757
3758    If IS_FRIEND is true, DECL is a friend declaration.  */
3759
3760 tree
3761 push_template_decl_real (tree decl, bool is_friend)
3762 {
3763   tree tmpl;
3764   tree args;
3765   tree info;
3766   tree ctx;
3767   int primary;
3768   int is_partial;
3769   int new_template_p = 0;
3770   /* True if the template is a member template, in the sense of
3771      [temp.mem].  */
3772   bool member_template_p = false;
3773
3774   if (decl == error_mark_node || !current_template_parms)
3775     return error_mark_node;
3776
3777   /* See if this is a partial specialization.  */
3778   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3779                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3780                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3781
3782   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3783     is_friend = true;
3784
3785   if (is_friend)
3786     /* For a friend, we want the context of the friend function, not
3787        the type of which it is a friend.  */
3788     ctx = DECL_CONTEXT (decl);
3789   else if (CP_DECL_CONTEXT (decl)
3790            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3791     /* In the case of a virtual function, we want the class in which
3792        it is defined.  */
3793     ctx = CP_DECL_CONTEXT (decl);
3794   else
3795     /* Otherwise, if we're currently defining some class, the DECL
3796        is assumed to be a member of the class.  */
3797     ctx = current_scope ();
3798
3799   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3800     ctx = NULL_TREE;
3801
3802   if (!DECL_CONTEXT (decl))
3803     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3804
3805   /* See if this is a primary template.  */
3806   if (is_friend && ctx)
3807     /* A friend template that specifies a class context, i.e.
3808          template <typename T> friend void A<T>::f();
3809        is not primary.  */
3810     primary = 0;
3811   else
3812     primary = template_parm_scope_p ();
3813
3814   if (primary)
3815     {
3816       if (DECL_CLASS_SCOPE_P (decl))
3817         member_template_p = true;
3818       if (TREE_CODE (decl) == TYPE_DECL
3819           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3820         {
3821           error ("template class without a name");
3822           return error_mark_node;
3823         }
3824       else if (TREE_CODE (decl) == FUNCTION_DECL)
3825         {
3826           if (DECL_DESTRUCTOR_P (decl))
3827             {
3828               /* [temp.mem]
3829
3830                  A destructor shall not be a member template.  */
3831               error ("destructor %qD declared as member template", decl);
3832               return error_mark_node;
3833             }
3834           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3835               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3836                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3837                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3838                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3839                       == void_list_node)))
3840             {
3841               /* [basic.stc.dynamic.allocation]
3842
3843                  An allocation function can be a function
3844                  template. ... Template allocation functions shall
3845                  have two or more parameters.  */
3846               error ("invalid template declaration of %qD", decl);
3847               return error_mark_node;
3848             }
3849         }
3850       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3851                && CLASS_TYPE_P (TREE_TYPE (decl)))
3852         /* OK */;
3853       else
3854         {
3855           error ("template declaration of %q#D", decl);
3856           return error_mark_node;
3857         }
3858     }
3859
3860   /* Check to see that the rules regarding the use of default
3861      arguments are not being violated.  */
3862   check_default_tmpl_args (decl, current_template_parms,
3863                            primary, is_partial, /*is_friend_decl=*/0);
3864
3865   /* Ensure that there are no parameter packs in the type of this
3866      declaration that have not been expanded.  */
3867   if (TREE_CODE (decl) == FUNCTION_DECL)
3868     {
3869       /* Check each of the arguments individually to see if there are
3870          any bare parameter packs.  */
3871       tree type = TREE_TYPE (decl);
3872       tree arg = DECL_ARGUMENTS (decl);
3873       tree argtype = TYPE_ARG_TYPES (type);
3874
3875       while (arg && argtype)
3876         {
3877           if (!FUNCTION_PARAMETER_PACK_P (arg)
3878               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
3879             {
3880             /* This is a PARM_DECL that contains unexpanded parameter
3881                packs. We have already complained about this in the
3882                check_for_bare_parameter_packs call, so just replace
3883                these types with ERROR_MARK_NODE.  */
3884               TREE_TYPE (arg) = error_mark_node;
3885               TREE_VALUE (argtype) = error_mark_node;
3886             }
3887
3888           arg = TREE_CHAIN (arg);
3889           argtype = TREE_CHAIN (argtype);
3890         }
3891
3892       /* Check for bare parameter packs in the return type and the
3893          exception specifiers.  */
3894       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
3895         /* Errors were already issued, set return type to int
3896            as the frontend doesn't expect error_mark_node as
3897            the return type.  */
3898         TREE_TYPE (type) = integer_type_node;
3899       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
3900         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
3901     }
3902   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
3903     {
3904       TREE_TYPE (decl) = error_mark_node;
3905       return error_mark_node;
3906     }
3907
3908   if (is_partial)
3909     return process_partial_specialization (decl);
3910
3911   args = current_template_args ();
3912
3913   if (!ctx
3914       || TREE_CODE (ctx) == FUNCTION_DECL
3915       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3916       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3917     {
3918       if (DECL_LANG_SPECIFIC (decl)
3919           && DECL_TEMPLATE_INFO (decl)
3920           && DECL_TI_TEMPLATE (decl))
3921         tmpl = DECL_TI_TEMPLATE (decl);
3922       /* If DECL is a TYPE_DECL for a class-template, then there won't
3923          be DECL_LANG_SPECIFIC.  The information equivalent to
3924          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3925       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3926                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3927                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3928         {
3929           /* Since a template declaration already existed for this
3930              class-type, we must be redeclaring it here.  Make sure
3931              that the redeclaration is valid.  */
3932           redeclare_class_template (TREE_TYPE (decl),
3933                                     current_template_parms);
3934           /* We don't need to create a new TEMPLATE_DECL; just use the
3935              one we already had.  */
3936           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3937         }
3938       else
3939         {
3940           tmpl = build_template_decl (decl, current_template_parms,
3941                                       member_template_p);
3942           new_template_p = 1;
3943
3944           if (DECL_LANG_SPECIFIC (decl)
3945               && DECL_TEMPLATE_SPECIALIZATION (decl))
3946             {
3947               /* A specialization of a member template of a template
3948                  class.  */
3949               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3950               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3951               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3952             }
3953         }
3954     }
3955   else
3956     {
3957       tree a, t, current, parms;
3958       int i;
3959       tree tinfo = get_template_info (decl);
3960
3961       if (!tinfo)
3962         {
3963           error ("template definition of non-template %q#D", decl);
3964           return error_mark_node;
3965         }
3966
3967       tmpl = TI_TEMPLATE (tinfo);
3968
3969       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3970           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3971           && DECL_TEMPLATE_SPECIALIZATION (decl)
3972           && DECL_MEMBER_TEMPLATE_P (tmpl))
3973         {
3974           tree new_tmpl;
3975
3976           /* The declaration is a specialization of a member
3977              template, declared outside the class.  Therefore, the
3978              innermost template arguments will be NULL, so we
3979              replace them with the arguments determined by the
3980              earlier call to check_explicit_specialization.  */
3981           args = DECL_TI_ARGS (decl);
3982
3983           new_tmpl
3984             = build_template_decl (decl, current_template_parms,
3985                                    member_template_p);
3986           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3987           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3988           DECL_TI_TEMPLATE (decl) = new_tmpl;
3989           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3990           DECL_TEMPLATE_INFO (new_tmpl)
3991             = tree_cons (tmpl, args, NULL_TREE);
3992
3993           register_specialization (new_tmpl,
3994                                    most_general_template (tmpl),
3995                                    args,
3996                                    is_friend);
3997           return decl;
3998         }
3999
4000       /* Make sure the template headers we got make sense.  */
4001
4002       parms = DECL_TEMPLATE_PARMS (tmpl);
4003       i = TMPL_PARMS_DEPTH (parms);
4004       if (TMPL_ARGS_DEPTH (args) != i)
4005         {
4006           error ("expected %d levels of template parms for %q#D, got %d",
4007                  i, decl, TMPL_ARGS_DEPTH (args));
4008         }
4009       else
4010         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4011           {
4012             a = TMPL_ARGS_LEVEL (args, i);
4013             t = INNERMOST_TEMPLATE_PARMS (parms);
4014
4015             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4016               {
4017                 if (current == decl)
4018                   error ("got %d template parameters for %q#D",
4019                          TREE_VEC_LENGTH (a), decl);
4020                 else
4021                   error ("got %d template parameters for %q#T",
4022                          TREE_VEC_LENGTH (a), current);
4023                 error ("  but %d required", TREE_VEC_LENGTH (t));
4024                 return error_mark_node;
4025               }
4026
4027             if (current == decl)
4028               current = ctx;
4029             else
4030               current = (TYPE_P (current)
4031                          ? TYPE_CONTEXT (current)
4032                          : DECL_CONTEXT (current));
4033           }
4034
4035       /* Check that the parms are used in the appropriate qualifying scopes
4036          in the declarator.  */
4037       if (!comp_template_args
4038           (TI_ARGS (tinfo),
4039            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4040         {
4041           error ("\
4042 template arguments to %qD do not match original template %qD",
4043                  decl, DECL_TEMPLATE_RESULT (tmpl));
4044           if (!uses_template_parms (TI_ARGS (tinfo)))
4045             inform (input_location, "use template<> for an explicit specialization");
4046           /* Avoid crash in import_export_decl.  */
4047           DECL_INTERFACE_KNOWN (decl) = 1;
4048           return error_mark_node;
4049         }
4050     }
4051
4052   DECL_TEMPLATE_RESULT (tmpl) = decl;
4053   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4054
4055   /* Push template declarations for global functions and types.  Note
4056      that we do not try to push a global template friend declared in a
4057      template class; such a thing may well depend on the template
4058      parameters of the class.  */
4059   if (new_template_p && !ctx
4060       && !(is_friend && template_class_depth (current_class_type) > 0))
4061     {
4062       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4063       if (tmpl == error_mark_node)
4064         return error_mark_node;
4065
4066       /* Hide template friend classes that haven't been declared yet.  */
4067       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4068         {
4069           DECL_ANTICIPATED (tmpl) = 1;
4070           DECL_FRIEND_P (tmpl) = 1;
4071         }
4072     }
4073
4074   if (primary)
4075     {
4076       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4077       int i;
4078
4079       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4080       if (DECL_CONV_FN_P (tmpl))
4081         {
4082           int depth = TMPL_PARMS_DEPTH (parms);
4083
4084           /* It is a conversion operator. See if the type converted to
4085              depends on innermost template operands.  */
4086
4087           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4088                                          depth))
4089             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4090         }
4091
4092       /* Give template template parms a DECL_CONTEXT of the template
4093          for which they are a parameter.  */
4094       parms = INNERMOST_TEMPLATE_PARMS (parms);
4095       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4096         {
4097           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4098           if (TREE_CODE (parm) == TEMPLATE_DECL)
4099             DECL_CONTEXT (parm) = tmpl;
4100         }
4101     }
4102
4103   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4104      back to its most general template.  If TMPL is a specialization,
4105      ARGS may only have the innermost set of arguments.  Add the missing
4106      argument levels if necessary.  */
4107   if (DECL_TEMPLATE_INFO (tmpl))
4108     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4109
4110   info = tree_cons (tmpl, args, NULL_TREE);
4111
4112   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4113     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4114   else if (DECL_LANG_SPECIFIC (decl))
4115     DECL_TEMPLATE_INFO (decl) = info;
4116
4117   return DECL_TEMPLATE_RESULT (tmpl);
4118 }
4119
4120 tree
4121 push_template_decl (tree decl)
4122 {
4123   return push_template_decl_real (decl, false);
4124 }
4125
4126 /* Called when a class template TYPE is redeclared with the indicated
4127    template PARMS, e.g.:
4128
4129      template <class T> struct S;
4130      template <class T> struct S {};  */
4131
4132 bool
4133 redeclare_class_template (tree type, tree parms)
4134 {
4135   tree tmpl;
4136   tree tmpl_parms;
4137   int i;
4138
4139   if (!TYPE_TEMPLATE_INFO (type))
4140     {
4141       error ("%qT is not a template type", type);
4142       return false;
4143     }
4144
4145   tmpl = TYPE_TI_TEMPLATE (type);
4146   if (!PRIMARY_TEMPLATE_P (tmpl))
4147     /* The type is nested in some template class.  Nothing to worry
4148        about here; there are no new template parameters for the nested
4149        type.  */
4150     return true;
4151
4152   if (!parms)
4153     {
4154       error ("template specifiers not specified in declaration of %qD",
4155              tmpl);
4156       return false;
4157     }
4158
4159   parms = INNERMOST_TEMPLATE_PARMS (parms);
4160   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4161
4162   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4163     {
4164       error ("redeclared with %d template parameter(s)", 
4165              TREE_VEC_LENGTH (parms));
4166       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4167              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4168       return false;
4169     }
4170
4171   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4172     {
4173       tree tmpl_parm;
4174       tree parm;
4175       tree tmpl_default;
4176       tree parm_default;
4177
4178       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4179           || TREE_VEC_ELT (parms, i) == error_mark_node)
4180         continue;
4181
4182       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4183       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4184       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4185       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4186
4187       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4188          TEMPLATE_DECL.  */
4189       if (tmpl_parm != error_mark_node
4190           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4191               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4192                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4193               || (TREE_CODE (tmpl_parm) != PARM_DECL
4194                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4195                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4196               || (TREE_CODE (tmpl_parm) == PARM_DECL
4197                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4198                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4199         {
4200           error ("template parameter %q+#D", tmpl_parm);
4201           error ("redeclared here as %q#D", parm);
4202           return false;
4203         }
4204
4205       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4206         {
4207           /* We have in [temp.param]:
4208
4209              A template-parameter may not be given default arguments
4210              by two different declarations in the same scope.  */
4211           error ("redefinition of default argument for %q#D", parm);
4212           inform (input_location, "%Joriginal definition appeared here", tmpl_parm);
4213           return false;
4214         }
4215
4216       if (parm_default != NULL_TREE)
4217         /* Update the previous template parameters (which are the ones
4218            that will really count) with the new default value.  */
4219         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4220       else if (tmpl_default != NULL_TREE)
4221         /* Update the new parameters, too; they'll be used as the
4222            parameters for any members.  */
4223         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4224     }
4225
4226     return true;
4227 }
4228
4229 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4230    (possibly simplified) expression.  */
4231
4232 tree
4233 fold_non_dependent_expr (tree expr)
4234 {
4235   if (expr == NULL_TREE)
4236     return NULL_TREE;
4237
4238   /* If we're in a template, but EXPR isn't value dependent, simplify
4239      it.  We're supposed to treat:
4240
4241        template <typename T> void f(T[1 + 1]);
4242        template <typename T> void f(T[2]);
4243
4244      as two declarations of the same function, for example.  */
4245   if (processing_template_decl
4246       && !type_dependent_expression_p (expr)
4247       && !value_dependent_expression_p (expr))
4248     {
4249       HOST_WIDE_INT saved_processing_template_decl;
4250
4251       saved_processing_template_decl = processing_template_decl;
4252       processing_template_decl = 0;
4253       expr = tsubst_copy_and_build (expr,
4254                                     /*args=*/NULL_TREE,
4255                                     tf_error,
4256                                     /*in_decl=*/NULL_TREE,
4257                                     /*function_p=*/false,
4258                                     /*integral_constant_expression_p=*/true);
4259       processing_template_decl = saved_processing_template_decl;
4260     }
4261   return expr;
4262 }
4263
4264 /* EXPR is an expression which is used in a constant-expression context.
4265    For instance, it could be a VAR_DECL with a constant initializer.
4266    Extract the innermost constant expression.
4267
4268    This is basically a more powerful version of
4269    integral_constant_value, which can be used also in templates where
4270    initializers can maintain a syntactic rather than semantic form
4271    (even if they are non-dependent, for access-checking purposes).  */
4272
4273 static tree
4274 fold_decl_constant_value (tree expr)
4275 {
4276   tree const_expr = expr;
4277   do
4278     {
4279       expr = fold_non_dependent_expr (const_expr);
4280       const_expr = integral_constant_value (expr);
4281     }
4282   while (expr != const_expr);
4283
4284   return expr;
4285 }
4286
4287 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4288    must be a function or a pointer-to-function type, as specified
4289    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4290    and check that the resulting function has external linkage.  */
4291
4292 static tree
4293 convert_nontype_argument_function (tree type, tree expr)
4294 {
4295   tree fns = expr;
4296   tree fn, fn_no_ptr;
4297
4298   fn = instantiate_type (type, fns, tf_none);
4299   if (fn == error_mark_node)
4300     return error_mark_node;
4301
4302   fn_no_ptr = fn;
4303   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4304     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4305   if (TREE_CODE (fn_no_ptr) == BASELINK)
4306     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4307  
4308   /* [temp.arg.nontype]/1
4309
4310      A template-argument for a non-type, non-template template-parameter
4311      shall be one of:
4312      [...]
4313      -- the address of an object or function with external linkage.  */
4314   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4315     {
4316       error ("%qE is not a valid template argument for type %qT "
4317              "because function %qD has not external linkage",
4318              expr, type, fn_no_ptr);
4319       return NULL_TREE;
4320     }
4321
4322   return fn;
4323 }
4324
4325 /* Attempt to convert the non-type template parameter EXPR to the
4326    indicated TYPE.  If the conversion is successful, return the
4327    converted value.  If the conversion is unsuccessful, return
4328    NULL_TREE if we issued an error message, or error_mark_node if we
4329    did not.  We issue error messages for out-and-out bad template
4330    parameters, but not simply because the conversion failed, since we
4331    might be just trying to do argument deduction.  Both TYPE and EXPR
4332    must be non-dependent.
4333
4334    The conversion follows the special rules described in
4335    [temp.arg.nontype], and it is much more strict than an implicit
4336    conversion.
4337
4338    This function is called twice for each template argument (see
4339    lookup_template_class for a more accurate description of this
4340    problem). This means that we need to handle expressions which
4341    are not valid in a C++ source, but can be created from the
4342    first call (for instance, casts to perform conversions). These
4343    hacks can go away after we fix the double coercion problem.  */
4344
4345 static tree
4346 convert_nontype_argument (tree type, tree expr)
4347 {
4348   tree expr_type;
4349
4350   /* Detect immediately string literals as invalid non-type argument.
4351      This special-case is not needed for correctness (we would easily
4352      catch this later), but only to provide better diagnostic for this
4353      common user mistake. As suggested by DR 100, we do not mention
4354      linkage issues in the diagnostic as this is not the point.  */
4355   if (TREE_CODE (expr) == STRING_CST)
4356     {
4357       error ("%qE is not a valid template argument for type %qT "
4358              "because string literals can never be used in this context",
4359              expr, type);
4360       return NULL_TREE;
4361     }
4362
4363   /* If we are in a template, EXPR may be non-dependent, but still
4364      have a syntactic, rather than semantic, form.  For example, EXPR
4365      might be a SCOPE_REF, rather than the VAR_DECL to which the
4366      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4367      so that access checking can be performed when the template is
4368      instantiated -- but here we need the resolved form so that we can
4369      convert the argument.  */
4370   expr = fold_non_dependent_expr (expr);
4371   if (error_operand_p (expr))
4372     return error_mark_node;
4373   expr_type = TREE_TYPE (expr);
4374
4375   /* HACK: Due to double coercion, we can get a
4376      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4377      which is the tree that we built on the first call (see
4378      below when coercing to reference to object or to reference to
4379      function). We just strip everything and get to the arg.
4380      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4381      for examples.  */
4382   if (TREE_CODE (expr) == NOP_EXPR)
4383     {
4384       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4385         {
4386           /* ??? Maybe we could use convert_from_reference here, but we
4387              would need to relax its constraints because the NOP_EXPR
4388              could actually change the type to something more cv-qualified,
4389              and this is not folded by convert_from_reference.  */
4390           tree addr = TREE_OPERAND (expr, 0);
4391           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4392           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4393           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4394           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4395                       (TREE_TYPE (expr_type),
4396                        TREE_TYPE (TREE_TYPE (addr))));
4397
4398           expr = TREE_OPERAND (addr, 0);
4399           expr_type = TREE_TYPE (expr);
4400         }
4401
4402       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4403          parameter is a pointer to object, through decay and
4404          qualification conversion. Let's strip everything.  */
4405       else if (TYPE_PTROBV_P (type))
4406         {
4407           STRIP_NOPS (expr);
4408           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4409           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4410           /* Skip the ADDR_EXPR only if it is part of the decay for
4411              an array. Otherwise, it is part of the original argument
4412              in the source code.  */
4413           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4414             expr = TREE_OPERAND (expr, 0);
4415           expr_type = TREE_TYPE (expr);
4416         }
4417     }
4418
4419   /* [temp.arg.nontype]/5, bullet 1
4420
4421      For a non-type template-parameter of integral or enumeration type,
4422      integral promotions (_conv.prom_) and integral conversions
4423      (_conv.integral_) are applied.  */
4424   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4425     {
4426       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4427         return error_mark_node;
4428
4429       expr = fold_decl_constant_value (expr);
4430       /* Notice that there are constant expressions like '4 % 0' which
4431          do not fold into integer constants.  */
4432       if (TREE_CODE (expr) != INTEGER_CST)
4433         {
4434           error ("%qE is not a valid template argument for type %qT "
4435                  "because it is a non-constant expression", expr, type);
4436           return NULL_TREE;
4437         }
4438
4439       /* At this point, an implicit conversion does what we want,
4440          because we already know that the expression is of integral
4441          type.  */
4442       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4443       if (expr == error_mark_node)
4444         return error_mark_node;
4445
4446       /* Conversion was allowed: fold it to a bare integer constant.  */
4447       expr = fold (expr);
4448     }
4449   /* [temp.arg.nontype]/5, bullet 2
4450
4451      For a non-type template-parameter of type pointer to object,
4452      qualification conversions (_conv.qual_) and the array-to-pointer
4453      conversion (_conv.array_) are applied.  */
4454   else if (TYPE_PTROBV_P (type))
4455     {
4456       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4457
4458          A template-argument for a non-type, non-template template-parameter
4459          shall be one of: [...]
4460
4461          -- the name of a non-type template-parameter;
4462          -- the address of an object or function with external linkage, [...]
4463             expressed as "& id-expression" where the & is optional if the name
4464             refers to a function or array, or if the corresponding
4465             template-parameter is a reference.
4466
4467         Here, we do not care about functions, as they are invalid anyway
4468         for a parameter of type pointer-to-object.  */
4469
4470       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4471         /* Non-type template parameters are OK.  */
4472         ;
4473       else if (TREE_CODE (expr) != ADDR_EXPR
4474                && TREE_CODE (expr_type) != ARRAY_TYPE)
4475         {
4476           if (TREE_CODE (expr) == VAR_DECL)
4477             {
4478               error ("%qD is not a valid template argument "
4479                      "because %qD is a variable, not the address of "
4480                      "a variable",
4481                      expr, expr);
4482               return NULL_TREE;
4483             }
4484           /* Other values, like integer constants, might be valid
4485              non-type arguments of some other type.  */
4486           return error_mark_node;
4487         }
4488       else
4489         {
4490           tree decl;
4491
4492           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4493                   ? TREE_OPERAND (expr, 0) : expr);
4494           if (TREE_CODE (decl) != VAR_DECL)
4495             {
4496               error ("%qE is not a valid template argument of type %qT "
4497                      "because %qE is not a variable",
4498                      expr, type, decl);
4499               return NULL_TREE;
4500             }
4501           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4502             {
4503               error ("%qE is not a valid template argument of type %qT "
4504                      "because %qD does not have external linkage",
4505                      expr, type, decl);
4506               return NULL_TREE;
4507             }
4508         }
4509
4510       expr = decay_conversion (expr);
4511       if (expr == error_mark_node)
4512         return error_mark_node;
4513
4514       expr = perform_qualification_conversions (type, expr);
4515       if (expr == error_mark_node)
4516         return error_mark_node;
4517     }
4518   /* [temp.arg.nontype]/5, bullet 3
4519
4520      For a non-type template-parameter of type reference to object, no
4521      conversions apply. The type referred to by the reference may be more
4522      cv-qualified than the (otherwise identical) type of the
4523      template-argument. The template-parameter is bound directly to the
4524      template-argument, which must be an lvalue.  */
4525   else if (TYPE_REF_OBJ_P (type))
4526     {
4527       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4528                                                       expr_type))
4529         return error_mark_node;
4530
4531       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4532         {
4533           error ("%qE is not a valid template argument for type %qT "
4534                  "because of conflicts in cv-qualification", expr, type);
4535           return NULL_TREE;
4536         }
4537
4538       if (!real_lvalue_p (expr))
4539         {
4540           error ("%qE is not a valid template argument for type %qT "
4541                  "because it is not an lvalue", expr, type);
4542           return NULL_TREE;
4543         }
4544
4545       /* [temp.arg.nontype]/1
4546
4547          A template-argument for a non-type, non-template template-parameter
4548          shall be one of: [...]
4549
4550          -- the address of an object or function with external linkage.  */
4551       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4552         {
4553           error ("%qE is not a valid template argument for type %qT "
4554                  "because object %qD has not external linkage",
4555                  expr, type, expr);
4556           return NULL_TREE;
4557         }
4558
4559       expr = build_nop (type, build_address (expr));
4560     }
4561   /* [temp.arg.nontype]/5, bullet 4
4562
4563      For a non-type template-parameter of type pointer to function, only
4564      the function-to-pointer conversion (_conv.func_) is applied. If the
4565      template-argument represents a set of overloaded functions (or a
4566      pointer to such), the matching function is selected from the set
4567      (_over.over_).  */
4568   else if (TYPE_PTRFN_P (type))
4569     {
4570       /* If the argument is a template-id, we might not have enough
4571          context information to decay the pointer.  */
4572       if (!type_unknown_p (expr_type))
4573         {
4574           expr = decay_conversion (expr);
4575           if (expr == error_mark_node)
4576             return error_mark_node;
4577         }
4578
4579       expr = convert_nontype_argument_function (type, expr);
4580       if (!expr || expr == error_mark_node)
4581         return expr;
4582
4583       if (TREE_CODE (expr) != ADDR_EXPR)
4584         {
4585           error ("%qE is not a valid template argument for type %qT", expr, type);
4586           error ("it must be the address of a function with external linkage");
4587           return NULL_TREE;
4588         }
4589     }
4590   /* [temp.arg.nontype]/5, bullet 5
4591
4592      For a non-type template-parameter of type reference to function, no
4593      conversions apply. If the template-argument represents a set of
4594      overloaded functions, the matching function is selected from the set
4595      (_over.over_).  */
4596   else if (TYPE_REFFN_P (type))
4597     {
4598       if (TREE_CODE (expr) == ADDR_EXPR)
4599         {
4600           error ("%qE is not a valid template argument for type %qT "
4601                  "because it is a pointer", expr, type);
4602           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4603           return NULL_TREE;
4604         }
4605
4606       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4607       if (!expr || expr == error_mark_node)
4608         return expr;
4609
4610       expr = build_nop (type, build_address (expr));
4611     }
4612   /* [temp.arg.nontype]/5, bullet 6
4613
4614      For a non-type template-parameter of type pointer to member function,
4615      no conversions apply. If the template-argument represents a set of
4616      overloaded member functions, the matching member function is selected
4617      from the set (_over.over_).  */
4618   else if (TYPE_PTRMEMFUNC_P (type))
4619     {
4620       expr = instantiate_type (type, expr, tf_none);
4621       if (expr == error_mark_node)
4622         return error_mark_node;
4623
4624       /* There is no way to disable standard conversions in
4625          resolve_address_of_overloaded_function (called by
4626          instantiate_type). It is possible that the call succeeded by
4627          converting &B::I to &D::I (where B is a base of D), so we need
4628          to reject this conversion here.
4629
4630          Actually, even if there was a way to disable standard conversions,
4631          it would still be better to reject them here so that we can
4632          provide a superior diagnostic.  */
4633       if (!same_type_p (TREE_TYPE (expr), type))
4634         {
4635           /* Make sure we are just one standard conversion off.  */
4636           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4637           error ("%qE is not a valid template argument for type %qT "
4638                  "because it is of type %qT", expr, type,
4639                  TREE_TYPE (expr));
4640           inform (input_location, "standard conversions are not allowed in this context");
4641           return NULL_TREE;
4642         }
4643     }
4644   /* [temp.arg.nontype]/5, bullet 7
4645
4646      For a non-type template-parameter of type pointer to data member,
4647      qualification conversions (_conv.qual_) are applied.  */
4648   else if (TYPE_PTRMEM_P (type))
4649     {
4650       expr = perform_qualification_conversions (type, expr);
4651       if (expr == error_mark_node)
4652         return expr;
4653     }
4654   /* A template non-type parameter must be one of the above.  */
4655   else
4656     gcc_unreachable ();
4657
4658   /* Sanity check: did we actually convert the argument to the
4659      right type?  */
4660   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4661   return expr;
4662 }
4663
4664 /* Subroutine of coerce_template_template_parms, which returns 1 if
4665    PARM_PARM and ARG_PARM match using the rule for the template
4666    parameters of template template parameters. Both PARM and ARG are
4667    template parameters; the rest of the arguments are the same as for
4668    coerce_template_template_parms.
4669  */
4670 static int
4671 coerce_template_template_parm (tree parm,
4672                               tree arg,
4673                               tsubst_flags_t complain,
4674                               tree in_decl,
4675                               tree outer_args)
4676 {
4677   if (arg == NULL_TREE || arg == error_mark_node
4678       || parm == NULL_TREE || parm == error_mark_node)
4679     return 0;
4680   
4681   if (TREE_CODE (arg) != TREE_CODE (parm))
4682     return 0;
4683   
4684   switch (TREE_CODE (parm))
4685     {
4686     case TEMPLATE_DECL:
4687       /* We encounter instantiations of templates like
4688          template <template <template <class> class> class TT>
4689          class C;  */
4690       {
4691         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4692         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4693         
4694         if (!coerce_template_template_parms
4695             (parmparm, argparm, complain, in_decl, outer_args))
4696           return 0;
4697       }
4698       /* Fall through.  */
4699       
4700     case TYPE_DECL:
4701       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
4702           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4703         /* Argument is a parameter pack but parameter is not.  */
4704         return 0;
4705       break;
4706       
4707     case PARM_DECL:
4708       /* The tsubst call is used to handle cases such as
4709          
4710            template <int> class C {};
4711            template <class T, template <T> class TT> class D {};
4712            D<int, C> d;
4713
4714          i.e. the parameter list of TT depends on earlier parameters.  */
4715       if (!uses_template_parms (TREE_TYPE (arg))
4716           && !same_type_p
4717                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4718                  TREE_TYPE (arg)))
4719         return 0;
4720       
4721       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
4722           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4723         /* Argument is a parameter pack but parameter is not.  */
4724         return 0;
4725       
4726       break;
4727
4728     default:
4729       gcc_unreachable ();
4730     }
4731
4732   return 1;
4733 }
4734
4735
4736 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4737    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4738    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4739    or PARM_DECL.
4740
4741    Consider the example:
4742      template <class T> class A;
4743      template<template <class U> class TT> class B;
4744
4745    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4746    the parameters to A, and OUTER_ARGS contains A.  */
4747
4748 static int
4749 coerce_template_template_parms (tree parm_parms,
4750                                 tree arg_parms,
4751                                 tsubst_flags_t complain,
4752                                 tree in_decl,
4753                                 tree outer_args)
4754 {
4755   int nparms, nargs, i;
4756   tree parm, arg;
4757   int variadic_p = 0;
4758
4759   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4760   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4761
4762   nparms = TREE_VEC_LENGTH (parm_parms);
4763   nargs = TREE_VEC_LENGTH (arg_parms);
4764
4765   /* Determine whether we have a parameter pack at the end of the
4766      template template parameter's template parameter list.  */
4767   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
4768     {
4769       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
4770       
4771       if (parm == error_mark_node)
4772         return 0;
4773
4774       switch (TREE_CODE (parm))
4775         {
4776         case TEMPLATE_DECL:
4777         case TYPE_DECL:
4778           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4779             variadic_p = 1;
4780           break;
4781           
4782         case PARM_DECL:
4783           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4784             variadic_p = 1;
4785           break;
4786           
4787         default:
4788           gcc_unreachable ();
4789         }
4790     }
4791  
4792   if (nargs != nparms
4793       && !(variadic_p && nargs >= nparms - 1))
4794     return 0;
4795
4796   /* Check all of the template parameters except the parameter pack at
4797      the end (if any).  */
4798   for (i = 0; i < nparms - variadic_p; ++i)
4799     {
4800       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4801           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4802         continue;
4803
4804       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4805       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4806
4807       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4808                                           outer_args))
4809         return 0;
4810
4811     }
4812
4813   if (variadic_p)
4814     {
4815       /* Check each of the template parameters in the template
4816          argument against the template parameter pack at the end of
4817          the template template parameter.  */
4818       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
4819         return 0;
4820
4821       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4822
4823       for (; i < nargs; ++i)
4824         {
4825           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4826             continue;
4827  
4828           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4829  
4830           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4831                                               outer_args))
4832             return 0;
4833         }
4834     }
4835
4836   return 1;
4837 }
4838
4839 /* Verifies that the deduced template arguments (in TARGS) for the
4840    template template parameters (in TPARMS) represent valid bindings,
4841    by comparing the template parameter list of each template argument
4842    to the template parameter list of its corresponding template
4843    template parameter, in accordance with DR150. This
4844    routine can only be called after all template arguments have been
4845    deduced. It will return TRUE if all of the template template
4846    parameter bindings are okay, FALSE otherwise.  */
4847 bool 
4848 template_template_parm_bindings_ok_p (tree tparms, tree targs)
4849 {
4850   int i, ntparms = TREE_VEC_LENGTH (tparms);
4851   bool ret = true;
4852
4853   /* We're dealing with template parms in this process.  */
4854   ++processing_template_decl;
4855
4856   targs = INNERMOST_TEMPLATE_ARGS (targs);
4857
4858   for (i = 0; i < ntparms; ++i)
4859     {
4860       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
4861       tree targ = TREE_VEC_ELT (targs, i);
4862
4863       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
4864         {
4865           tree packed_args = NULL_TREE;
4866           int idx, len = 1;
4867
4868           if (ARGUMENT_PACK_P (targ))
4869             {
4870               /* Look inside the argument pack.  */
4871               packed_args = ARGUMENT_PACK_ARGS (targ);
4872               len = TREE_VEC_LENGTH (packed_args);
4873             }
4874
4875           for (idx = 0; idx < len; ++idx)
4876             {
4877               tree targ_parms = NULL_TREE;
4878
4879               if (packed_args)
4880                 /* Extract the next argument from the argument
4881                    pack.  */
4882                 targ = TREE_VEC_ELT (packed_args, idx);
4883
4884               if (PACK_EXPANSION_P (targ))
4885                 /* Look at the pattern of the pack expansion.  */
4886                 targ = PACK_EXPANSION_PATTERN (targ);
4887
4888               /* Extract the template parameters from the template
4889                  argument.  */
4890               if (TREE_CODE (targ) == TEMPLATE_DECL)
4891                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
4892               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
4893                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
4894
4895               /* Verify that we can coerce the template template
4896                  parameters from the template argument to the template
4897                  parameter.  This requires an exact match.  */
4898               if (targ_parms
4899                   && !coerce_template_template_parms
4900                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
4901                         targ_parms,
4902                         tf_none,
4903                         tparm,
4904                         targs))
4905                 {
4906                   ret = false;
4907                   goto out;
4908                 }
4909             }
4910         }
4911     }
4912
4913  out:
4914
4915   --processing_template_decl;
4916   return ret;
4917 }
4918
4919 /* Convert the indicated template ARG as necessary to match the
4920    indicated template PARM.  Returns the converted ARG, or
4921    error_mark_node if the conversion was unsuccessful.  Error and
4922    warning messages are issued under control of COMPLAIN.  This
4923    conversion is for the Ith parameter in the parameter list.  ARGS is
4924    the full set of template arguments deduced so far.  */
4925
4926 static tree
4927 convert_template_argument (tree parm,
4928                            tree arg,
4929                            tree args,
4930                            tsubst_flags_t complain,
4931                            int i,
4932                            tree in_decl)
4933 {
4934   tree orig_arg;
4935   tree val;
4936   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4937
4938   if (TREE_CODE (arg) == TREE_LIST
4939       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4940     {
4941       /* The template argument was the name of some
4942          member function.  That's usually
4943          invalid, but static members are OK.  In any
4944          case, grab the underlying fields/functions
4945          and issue an error later if required.  */
4946       orig_arg = TREE_VALUE (arg);
4947       TREE_TYPE (arg) = unknown_type_node;
4948     }
4949
4950   orig_arg = arg;
4951
4952   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4953   requires_type = (TREE_CODE (parm) == TYPE_DECL
4954                    || requires_tmpl_type);
4955
4956   /* When determining whether an argument pack expansion is a template,
4957      look at the pattern.  */
4958   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
4959     arg = PACK_EXPANSION_PATTERN (arg);
4960
4961   is_tmpl_type = 
4962     ((TREE_CODE (arg) == TEMPLATE_DECL
4963       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
4964      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4965      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
4966
4967   if (is_tmpl_type
4968       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4969           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4970     arg = TYPE_STUB_DECL (arg);
4971
4972   is_type = TYPE_P (arg) || is_tmpl_type;
4973
4974   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4975       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4976     {
4977       permerror (input_location, "to refer to a type member of a template parameter, "
4978                  "use %<typename %E%>", orig_arg);
4979
4980       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
4981                                      TREE_OPERAND (arg, 1),
4982                                      typename_type,
4983                                      complain & tf_error);
4984       arg = orig_arg;
4985       is_type = 1;
4986     }
4987   if (is_type != requires_type)
4988     {
4989       if (in_decl)
4990         {
4991           if (complain & tf_error)
4992             {
4993               error ("type/value mismatch at argument %d in template "
4994                      "parameter list for %qD",
4995                      i + 1, in_decl);
4996               if (is_type)
4997                 error ("  expected a constant of type %qT, got %qT",
4998                        TREE_TYPE (parm),
4999                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5000               else if (requires_tmpl_type)
5001                 error ("  expected a class template, got %qE", orig_arg);
5002               else
5003                 error ("  expected a type, got %qE", orig_arg);
5004             }
5005         }
5006       return error_mark_node;
5007     }
5008   if (is_tmpl_type ^ requires_tmpl_type)
5009     {
5010       if (in_decl && (complain & tf_error))
5011         {
5012           error ("type/value mismatch at argument %d in template "
5013                  "parameter list for %qD",
5014                  i + 1, in_decl);
5015           if (is_tmpl_type)
5016             error ("  expected a type, got %qT", DECL_NAME (arg));
5017           else
5018             error ("  expected a class template, got %qT", orig_arg);
5019         }
5020       return error_mark_node;
5021     }
5022
5023   if (is_type)
5024     {
5025       if (requires_tmpl_type)
5026         {
5027           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5028             /* The number of argument required is not known yet.
5029                Just accept it for now.  */
5030             val = TREE_TYPE (arg);
5031           else
5032             {
5033               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5034               tree argparm;
5035
5036               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5037
5038               if (coerce_template_template_parms (parmparm, argparm,
5039                                                   complain, in_decl,
5040                                                   args))
5041                 {
5042                   val = orig_arg;
5043
5044                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5045                      TEMPLATE_DECL.  */
5046                   if (val != error_mark_node)
5047                     {
5048                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5049                         val = TREE_TYPE (val);
5050                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5051                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5052                         {
5053                           val = TREE_TYPE (arg);
5054                           val = make_pack_expansion (val);
5055                         }
5056                     }
5057                 }
5058               else
5059                 {
5060                   if (in_decl && (complain & tf_error))
5061                     {
5062                       error ("type/value mismatch at argument %d in "
5063                              "template parameter list for %qD",
5064                              i + 1, in_decl);
5065                       error ("  expected a template of type %qD, got %qD",
5066                              parm, orig_arg);
5067                     }
5068
5069                   val = error_mark_node;
5070                 }
5071             }
5072         }
5073       else
5074         val = orig_arg;
5075       /* We only form one instance of each template specialization.
5076          Therefore, if we use a non-canonical variant (i.e., a
5077          typedef), any future messages referring to the type will use
5078          the typedef, which is confusing if those future uses do not
5079          themselves also use the typedef.  */
5080       if (TYPE_P (val))
5081         val = strip_typedefs (val);
5082     }
5083   else
5084     {
5085       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5086
5087       if (invalid_nontype_parm_type_p (t, complain))
5088         return error_mark_node;
5089
5090       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5091         {
5092           if (same_type_p (t, TREE_TYPE (orig_arg)))
5093             val = orig_arg;
5094           else
5095             {
5096               /* Not sure if this is reachable, but it doesn't hurt
5097                  to be robust.  */
5098               error ("type mismatch in nontype parameter pack");
5099               val = error_mark_node;
5100             }
5101         }
5102       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5103         /* We used to call digest_init here.  However, digest_init
5104            will report errors, which we don't want when complain
5105            is zero.  More importantly, digest_init will try too
5106            hard to convert things: for example, `0' should not be
5107            converted to pointer type at this point according to
5108            the standard.  Accepting this is not merely an
5109            extension, since deciding whether or not these
5110            conversions can occur is part of determining which
5111            function template to call, or whether a given explicit
5112            argument specification is valid.  */
5113         val = convert_nontype_argument (t, orig_arg);
5114       else
5115         val = orig_arg;
5116
5117       if (val == NULL_TREE)
5118         val = error_mark_node;
5119       else if (val == error_mark_node && (complain & tf_error))
5120         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5121     }
5122
5123   return val;
5124 }
5125
5126 /* Coerces the remaining template arguments in INNER_ARGS (from
5127    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5128    Returns the coerced argument pack. PARM_IDX is the position of this
5129    parameter in the template parameter list. ARGS is the original
5130    template argument list.  */
5131 static tree
5132 coerce_template_parameter_pack (tree parms,
5133                                 int parm_idx,
5134                                 tree args,
5135                                 tree inner_args,
5136                                 int arg_idx,
5137                                 tree new_args,
5138                                 int* lost,
5139                                 tree in_decl,
5140                                 tsubst_flags_t complain)
5141 {
5142   tree parm = TREE_VEC_ELT (parms, parm_idx);
5143   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5144   tree packed_args;
5145   tree argument_pack;
5146   tree packed_types = NULL_TREE;
5147
5148   if (arg_idx > nargs)
5149     arg_idx = nargs;
5150
5151   packed_args = make_tree_vec (nargs - arg_idx);
5152
5153   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5154       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5155     {
5156       /* When the template parameter is a non-type template
5157          parameter pack whose type uses parameter packs, we need
5158          to look at each of the template arguments
5159          separately. Build a vector of the types for these
5160          non-type template parameters in PACKED_TYPES.  */
5161       tree expansion 
5162         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5163       packed_types = tsubst_pack_expansion (expansion, args,
5164                                             complain, in_decl);
5165
5166       if (packed_types == error_mark_node)
5167         return error_mark_node;
5168
5169       /* Check that we have the right number of arguments.  */
5170       if (arg_idx < nargs
5171           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5172           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5173         {
5174           int needed_parms 
5175             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5176           error ("wrong number of template arguments (%d, should be %d)",
5177                  nargs, needed_parms);
5178           return error_mark_node;
5179         }
5180
5181       /* If we aren't able to check the actual arguments now
5182          (because they haven't been expanded yet), we can at least
5183          verify that all of the types used for the non-type
5184          template parameter pack are, in fact, valid for non-type
5185          template parameters.  */
5186       if (arg_idx < nargs 
5187           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5188         {
5189           int j, len = TREE_VEC_LENGTH (packed_types);
5190           for (j = 0; j < len; ++j)
5191             {
5192               tree t = TREE_VEC_ELT (packed_types, j);
5193               if (invalid_nontype_parm_type_p (t, complain))
5194                 return error_mark_node;
5195             }
5196         }
5197     }
5198
5199   /* Convert the remaining arguments, which will be a part of the
5200      parameter pack "parm".  */
5201   for (; arg_idx < nargs; ++arg_idx)
5202     {
5203       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5204       tree actual_parm = TREE_VALUE (parm);
5205
5206       if (packed_types && !PACK_EXPANSION_P (arg))
5207         {
5208           /* When we have a vector of types (corresponding to the
5209              non-type template parameter pack that uses parameter
5210              packs in its type, as mention above), and the
5211              argument is not an expansion (which expands to a
5212              currently unknown number of arguments), clone the
5213              parm and give it the next type in PACKED_TYPES.  */
5214           actual_parm = copy_node (actual_parm);
5215           TREE_TYPE (actual_parm) = 
5216             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5217         }
5218
5219       if (arg != error_mark_node)
5220         arg = convert_template_argument (actual_parm, 
5221                                          arg, new_args, complain, parm_idx,
5222                                          in_decl);
5223       if (arg == error_mark_node)
5224         (*lost)++;
5225       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5226     }
5227
5228   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5229       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5230     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5231   else
5232     {
5233       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5234       TREE_TYPE (argument_pack) 
5235         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5236       TREE_CONSTANT (argument_pack) = 1;
5237     }
5238
5239   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5240   return argument_pack;
5241 }
5242
5243 /* Convert all template arguments to their appropriate types, and
5244    return a vector containing the innermost resulting template
5245    arguments.  If any error occurs, return error_mark_node. Error and
5246    warning messages are issued under control of COMPLAIN.
5247
5248    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5249    for arguments not specified in ARGS.  Otherwise, if
5250    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5251    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5252    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5253    ARGS.  */
5254
5255 static tree
5256 coerce_template_parms (tree parms,
5257                        tree args,
5258                        tree in_decl,
5259                        tsubst_flags_t complain,
5260                        bool require_all_args,
5261                        bool use_default_args)
5262 {
5263   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5264   tree inner_args;
5265   tree new_args;
5266   tree new_inner_args;
5267   int saved_unevaluated_operand;
5268   int saved_inhibit_evaluation_warnings;
5269
5270   /* When used as a boolean value, indicates whether this is a
5271      variadic template parameter list. Since it's an int, we can also
5272      subtract it from nparms to get the number of non-variadic
5273      parameters.  */
5274   int variadic_p = 0;
5275
5276   nparms = TREE_VEC_LENGTH (parms);
5277
5278   /* Determine if there are any parameter packs.  */
5279   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5280     {
5281       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5282       if (template_parameter_pack_p (tparm))
5283         ++variadic_p;
5284     }
5285
5286   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5287   /* If there are 0 or 1 parameter packs, we need to expand any argument
5288      packs so that we can deduce a parameter pack from some non-packed args
5289      followed by an argument pack, as in variadic85.C.  If there are more
5290      than that, we need to leave argument packs intact so the arguments are
5291      assigned to the right parameter packs.  This should only happen when
5292      dealing with a nested class inside a partial specialization of a class
5293      template, as in variadic92.C.  */
5294   if (variadic_p <= 1)
5295     inner_args = expand_template_argument_pack (inner_args);
5296
5297   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5298   if ((nargs > nparms && !variadic_p)
5299       || (nargs < nparms - variadic_p
5300           && require_all_args
5301           && (!use_default_args
5302               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5303                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5304     {
5305       if (complain & tf_error)
5306         {
5307           const char *or_more = "";
5308           if (variadic_p)
5309             {
5310               or_more = " or more";
5311               --nparms;
5312             }
5313
5314           error ("wrong number of template arguments (%d, should be %d%s)",
5315                  nargs, nparms, or_more);
5316
5317           if (in_decl)
5318             error ("provided for %q+D", in_decl);
5319         }
5320
5321       return error_mark_node;
5322     }
5323
5324   /* We need to evaluate the template arguments, even though this
5325      template-id may be nested within a "sizeof".  */
5326   saved_unevaluated_operand = cp_unevaluated_operand;
5327   cp_unevaluated_operand = 0;
5328   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5329   c_inhibit_evaluation_warnings = 0;
5330   new_inner_args = make_tree_vec (nparms);
5331   new_args = add_outermost_template_args (args, new_inner_args);
5332   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5333     {
5334       tree arg;
5335       tree parm;
5336
5337       /* Get the Ith template parameter.  */
5338       parm = TREE_VEC_ELT (parms, parm_idx);
5339  
5340       if (parm == error_mark_node)
5341       {
5342         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5343         continue;
5344       }
5345
5346       /* Calculate the next argument.  */
5347       if (arg_idx < nargs)
5348         arg = TREE_VEC_ELT (inner_args, arg_idx);
5349       else
5350         arg = NULL_TREE;
5351
5352       if (template_parameter_pack_p (TREE_VALUE (parm))
5353           && !(arg && ARGUMENT_PACK_P (arg)))
5354         {
5355           /* All remaining arguments will be placed in the
5356              template parameter pack PARM.  */
5357           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5358                                                 inner_args, arg_idx,
5359                                                 new_args, &lost,
5360                                                 in_decl, complain);
5361
5362           /* Store this argument.  */
5363           if (arg == error_mark_node)
5364             lost++;
5365           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5366
5367           /* We are done with all of the arguments.  */
5368           arg_idx = nargs;
5369           
5370           continue;
5371         }
5372       else if (arg)
5373         {
5374           if (PACK_EXPANSION_P (arg))
5375             {
5376               if (complain & tf_error)
5377                 {
5378                   /* FIXME this restriction was removed by N2555; see
5379                      bug 35722.  */
5380                   /* If ARG is a pack expansion, but PARM is not a
5381                      template parameter pack (if it were, we would have
5382                      handled it above), we're trying to expand into a
5383                      fixed-length argument list.  */
5384                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5385                     sorry ("cannot expand %<%E%> into a fixed-length "
5386                            "argument list", arg);
5387                   else
5388                     sorry ("cannot expand %<%T%> into a fixed-length "
5389                            "argument list", arg);
5390                 }
5391               return error_mark_node;
5392             }
5393         }
5394       else if (require_all_args)
5395         /* There must be a default arg in this case.  */
5396         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5397                                    complain, in_decl);
5398       else
5399         break;
5400
5401       if (arg == error_mark_node)
5402         {
5403           if (complain & tf_error)
5404             error ("template argument %d is invalid", arg_idx + 1);
5405         }
5406       else if (!arg)
5407         /* This only occurs if there was an error in the template
5408            parameter list itself (which we would already have
5409            reported) that we are trying to recover from, e.g., a class
5410            template with a parameter list such as
5411            template<typename..., typename>.  */
5412         return error_mark_node;
5413       else
5414         arg = convert_template_argument (TREE_VALUE (parm),
5415                                          arg, new_args, complain, 
5416                                          parm_idx, in_decl);
5417
5418       if (arg == error_mark_node)
5419         lost++;
5420       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5421     }
5422   cp_unevaluated_operand = saved_unevaluated_operand;
5423   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
5424
5425   if (lost)
5426     return error_mark_node;
5427
5428   return new_inner_args;
5429 }
5430
5431 /* Returns 1 if template args OT and NT are equivalent.  */
5432
5433 static int
5434 template_args_equal (tree ot, tree nt)
5435 {
5436   if (nt == ot)
5437     return 1;
5438
5439   if (TREE_CODE (nt) == TREE_VEC)
5440     /* For member templates */
5441     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5442   else if (PACK_EXPANSION_P (ot))
5443     return PACK_EXPANSION_P (nt) 
5444       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5445                               PACK_EXPANSION_PATTERN (nt));
5446   else if (ARGUMENT_PACK_P (ot))
5447     {
5448       int i, len;
5449       tree opack, npack;
5450
5451       if (!ARGUMENT_PACK_P (nt))
5452         return 0;
5453
5454       opack = ARGUMENT_PACK_ARGS (ot);
5455       npack = ARGUMENT_PACK_ARGS (nt);
5456       len = TREE_VEC_LENGTH (opack);
5457       if (TREE_VEC_LENGTH (npack) != len)
5458         return 0;
5459       for (i = 0; i < len; ++i)
5460         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5461                                   TREE_VEC_ELT (npack, i)))
5462           return 0;
5463       return 1;
5464     }
5465   else if (TYPE_P (nt))
5466     return TYPE_P (ot) && same_type_p (ot, nt);
5467   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5468     return 0;
5469   else
5470     return cp_tree_equal (ot, nt);
5471 }
5472
5473 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5474    of template arguments.  Returns 0 otherwise.  */
5475
5476 int
5477 comp_template_args (tree oldargs, tree newargs)
5478 {
5479   int i;
5480
5481   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5482     return 0;
5483
5484   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5485     {
5486       tree nt = TREE_VEC_ELT (newargs, i);
5487       tree ot = TREE_VEC_ELT (oldargs, i);
5488
5489       if (! template_args_equal (ot, nt))
5490         return 0;
5491     }
5492   return 1;
5493 }
5494
5495 static void
5496 add_pending_template (tree d)
5497 {
5498   tree ti = (TYPE_P (d)
5499              ? CLASSTYPE_TEMPLATE_INFO (d)
5500              : DECL_TEMPLATE_INFO (d));
5501   struct pending_template *pt;
5502   int level;
5503
5504   if (TI_PENDING_TEMPLATE_FLAG (ti))
5505     return;
5506
5507   /* We are called both from instantiate_decl, where we've already had a
5508      tinst_level pushed, and instantiate_template, where we haven't.
5509      Compensate.  */
5510   level = !current_tinst_level || current_tinst_level->decl != d;
5511
5512   if (level)
5513     push_tinst_level (d);
5514
5515   pt = GGC_NEW (struct pending_template);
5516   pt->next = NULL;
5517   pt->tinst = current_tinst_level;
5518   if (last_pending_template)
5519     last_pending_template->next = pt;
5520   else
5521     pending_templates = pt;
5522
5523   last_pending_template = pt;
5524
5525   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5526
5527   if (level)
5528     pop_tinst_level ();
5529 }
5530
5531
5532 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5533    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5534    documentation for TEMPLATE_ID_EXPR.  */
5535
5536 tree
5537 lookup_template_function (tree fns, tree arglist)
5538 {
5539   tree type;
5540
5541   if (fns == error_mark_node || arglist == error_mark_node)
5542     return error_mark_node;
5543
5544   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5545   gcc_assert (fns && (is_overloaded_fn (fns)
5546                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5547
5548   if (BASELINK_P (fns))
5549     {
5550       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5551                                          unknown_type_node,
5552                                          BASELINK_FUNCTIONS (fns),
5553                                          arglist);
5554       return fns;
5555     }
5556
5557   type = TREE_TYPE (fns);
5558   if (TREE_CODE (fns) == OVERLOAD || !type)
5559     type = unknown_type_node;
5560
5561   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5562 }
5563
5564 /* Within the scope of a template class S<T>, the name S gets bound
5565    (in build_self_reference) to a TYPE_DECL for the class, not a
5566    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5567    or one of its enclosing classes, and that type is a template,
5568    return the associated TEMPLATE_DECL.  Otherwise, the original
5569    DECL is returned.  */
5570
5571 tree
5572 maybe_get_template_decl_from_type_decl (tree decl)
5573 {
5574   return (decl != NULL_TREE
5575           && TREE_CODE (decl) == TYPE_DECL
5576           && DECL_ARTIFICIAL (decl)
5577           && CLASS_TYPE_P (TREE_TYPE (decl))
5578           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5579     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5580 }
5581
5582 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5583    parameters, find the desired type.
5584
5585    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5586
5587    IN_DECL, if non-NULL, is the template declaration we are trying to
5588    instantiate.
5589
5590    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5591    the class we are looking up.
5592
5593    Issue error and warning messages under control of COMPLAIN.
5594
5595    If the template class is really a local class in a template
5596    function, then the FUNCTION_CONTEXT is the function in which it is
5597    being instantiated.
5598
5599    ??? Note that this function is currently called *twice* for each
5600    template-id: the first time from the parser, while creating the
5601    incomplete type (finish_template_type), and the second type during the
5602    real instantiation (instantiate_template_class). This is surely something
5603    that we want to avoid. It also causes some problems with argument
5604    coercion (see convert_nontype_argument for more information on this).  */
5605
5606 tree
5607 lookup_template_class (tree d1,
5608                        tree arglist,
5609                        tree in_decl,
5610                        tree context,
5611                        int entering_scope,
5612                        tsubst_flags_t complain)
5613 {
5614   tree templ = NULL_TREE, parmlist;
5615   tree t;
5616
5617   timevar_push (TV_NAME_LOOKUP);
5618
5619   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5620     {
5621       tree value = innermost_non_namespace_value (d1);
5622       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5623         templ = value;
5624       else
5625         {
5626           if (context)
5627             push_decl_namespace (context);
5628           templ = lookup_name (d1);
5629           templ = maybe_get_template_decl_from_type_decl (templ);
5630           if (context)
5631             pop_decl_namespace ();
5632         }
5633       if (templ)
5634         context = DECL_CONTEXT (templ);
5635     }
5636   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
5637     {
5638       tree type = TREE_TYPE (d1);
5639
5640       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5641          an implicit typename for the second A.  Deal with it.  */
5642       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5643         type = TREE_TYPE (type);
5644
5645       if (CLASSTYPE_TEMPLATE_INFO (type))
5646         {
5647           templ = CLASSTYPE_TI_TEMPLATE (type);
5648           d1 = DECL_NAME (templ);
5649         }
5650     }
5651   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5652            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
5653     {
5654       templ = TYPE_TI_TEMPLATE (d1);
5655       d1 = DECL_NAME (templ);
5656     }
5657   else if (TREE_CODE (d1) == TEMPLATE_DECL
5658            && DECL_TEMPLATE_RESULT (d1)
5659            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5660     {
5661       templ = d1;
5662       d1 = DECL_NAME (templ);
5663       context = DECL_CONTEXT (templ);
5664     }
5665
5666   /* Issue an error message if we didn't find a template.  */
5667   if (! templ)
5668     {
5669       if (complain & tf_error)
5670         error ("%qT is not a template", d1);
5671       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5672     }
5673
5674   if (TREE_CODE (templ) != TEMPLATE_DECL
5675          /* Make sure it's a user visible template, if it was named by
5676             the user.  */
5677       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
5678           && !PRIMARY_TEMPLATE_P (templ)))
5679     {
5680       if (complain & tf_error)
5681         {
5682           error ("non-template type %qT used as a template", d1);
5683           if (in_decl)
5684             error ("for template declaration %q+D", in_decl);
5685         }
5686       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5687     }
5688
5689   complain &= ~tf_user;
5690
5691   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
5692     {
5693       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5694          template arguments */
5695
5696       tree parm;
5697       tree arglist2;
5698       tree outer;
5699
5700       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
5701
5702       /* Consider an example where a template template parameter declared as
5703
5704            template <class T, class U = std::allocator<T> > class TT
5705
5706          The template parameter level of T and U are one level larger than
5707          of TT.  To proper process the default argument of U, say when an
5708          instantiation `TT<int>' is seen, we need to build the full
5709          arguments containing {int} as the innermost level.  Outer levels,
5710          available when not appearing as default template argument, can be
5711          obtained from the arguments of the enclosing template.
5712
5713          Suppose that TT is later substituted with std::vector.  The above
5714          instantiation is `TT<int, std::allocator<T> >' with TT at
5715          level 1, and T at level 2, while the template arguments at level 1
5716          becomes {std::vector} and the inner level 2 is {int}.  */
5717
5718       outer = DECL_CONTEXT (templ);
5719       if (outer)
5720         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5721       else if (current_template_parms)
5722         /* This is an argument of the current template, so we haven't set
5723            DECL_CONTEXT yet.  */
5724         outer = current_template_args ();
5725
5726       if (outer)
5727         arglist = add_to_template_args (outer, arglist);
5728
5729       arglist2 = coerce_template_parms (parmlist, arglist, templ,
5730                                         complain,
5731                                         /*require_all_args=*/true,
5732                                         /*use_default_args=*/true);
5733       if (arglist2 == error_mark_node
5734           || (!uses_template_parms (arglist2)
5735               && check_instantiated_args (templ, arglist2, complain)))
5736         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5737
5738       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
5739       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5740     }
5741   else
5742     {
5743       tree template_type = TREE_TYPE (templ);
5744       tree gen_tmpl;
5745       tree type_decl;
5746       tree found = NULL_TREE;
5747       int arg_depth;
5748       int parm_depth;
5749       int is_partial_instantiation;
5750
5751       gen_tmpl = most_general_template (templ);
5752       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5753       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5754       arg_depth = TMPL_ARGS_DEPTH (arglist);
5755
5756       if (arg_depth == 1 && parm_depth > 1)
5757         {
5758           /* We've been given an incomplete set of template arguments.
5759              For example, given:
5760
5761                template <class T> struct S1 {
5762                  template <class U> struct S2 {};
5763                  template <class U> struct S2<U*> {};
5764                 };
5765
5766              we will be called with an ARGLIST of `U*', but the
5767              TEMPLATE will be `template <class T> template
5768              <class U> struct S1<T>::S2'.  We must fill in the missing
5769              arguments.  */
5770           arglist
5771             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
5772                                            arglist);
5773           arg_depth = TMPL_ARGS_DEPTH (arglist);
5774         }
5775
5776       /* Now we should have enough arguments.  */
5777       gcc_assert (parm_depth == arg_depth);
5778
5779       /* From here on, we're only interested in the most general
5780          template.  */
5781       templ = gen_tmpl;
5782
5783       /* Calculate the BOUND_ARGS.  These will be the args that are
5784          actually tsubst'd into the definition to create the
5785          instantiation.  */
5786       if (parm_depth > 1)
5787         {
5788           /* We have multiple levels of arguments to coerce, at once.  */
5789           int i;
5790           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5791
5792           tree bound_args = make_tree_vec (parm_depth);
5793
5794           for (i = saved_depth,
5795                  t = DECL_TEMPLATE_PARMS (templ);
5796                i > 0 && t != NULL_TREE;
5797                --i, t = TREE_CHAIN (t))
5798             {
5799               tree a = coerce_template_parms (TREE_VALUE (t),
5800                                               arglist, templ,
5801                                               complain,
5802                                               /*require_all_args=*/true,
5803                                               /*use_default_args=*/true);
5804
5805               /* Don't process further if one of the levels fails.  */
5806               if (a == error_mark_node)
5807                 {
5808                   /* Restore the ARGLIST to its full size.  */
5809                   TREE_VEC_LENGTH (arglist) = saved_depth;
5810                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5811                 }
5812
5813               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5814
5815               /* We temporarily reduce the length of the ARGLIST so
5816                  that coerce_template_parms will see only the arguments
5817                  corresponding to the template parameters it is
5818                  examining.  */
5819               TREE_VEC_LENGTH (arglist)--;
5820             }
5821
5822           /* Restore the ARGLIST to its full size.  */
5823           TREE_VEC_LENGTH (arglist) = saved_depth;
5824
5825           arglist = bound_args;
5826         }
5827       else
5828         arglist
5829           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5830                                    INNERMOST_TEMPLATE_ARGS (arglist),
5831                                    templ,
5832                                    complain,
5833                                    /*require_all_args=*/true,
5834                                    /*use_default_args=*/true);
5835
5836       if (arglist == error_mark_node)
5837         /* We were unable to bind the arguments.  */
5838         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5839
5840       /* In the scope of a template class, explicit references to the
5841          template class refer to the type of the template, not any
5842          instantiation of it.  For example, in:
5843
5844            template <class T> class C { void f(C<T>); }
5845
5846          the `C<T>' is just the same as `C'.  Outside of the
5847          class, however, such a reference is an instantiation.  */
5848       if ((entering_scope
5849            || !PRIMARY_TEMPLATE_P (templ)
5850            || currently_open_class (template_type))
5851           /* comp_template_args is expensive, check it last.  */
5852           && comp_template_args (TYPE_TI_ARGS (template_type),
5853                                  arglist))
5854         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
5855
5856       /* If we already have this specialization, return it.  */
5857       found = retrieve_specialization (templ, arglist,
5858                                        /*class_specializations_p=*/false);
5859       if (found)
5860         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5861
5862       /* This type is a "partial instantiation" if any of the template
5863          arguments still involve template parameters.  Note that we set
5864          IS_PARTIAL_INSTANTIATION for partial specializations as
5865          well.  */
5866       is_partial_instantiation = uses_template_parms (arglist);
5867
5868       /* If the deduced arguments are invalid, then the binding
5869          failed.  */
5870       if (!is_partial_instantiation
5871           && check_instantiated_args (templ,
5872                                       INNERMOST_TEMPLATE_ARGS (arglist),
5873                                       complain))
5874         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5875
5876       if (!is_partial_instantiation
5877           && !PRIMARY_TEMPLATE_P (templ)
5878           && TREE_CODE (CP_DECL_CONTEXT (templ)) == NAMESPACE_DECL)
5879         {
5880           found = xref_tag_from_type (TREE_TYPE (templ),
5881                                       DECL_NAME (templ),
5882                                       /*tag_scope=*/ts_global);
5883           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5884         }
5885
5886       context = tsubst (DECL_CONTEXT (templ), arglist,
5887                         complain, in_decl);
5888       if (!context)
5889         context = global_namespace;
5890
5891       /* Create the type.  */
5892       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5893         {
5894           if (!is_partial_instantiation)
5895             {
5896               set_current_access_from_decl (TYPE_NAME (template_type));
5897               t = start_enum (TYPE_IDENTIFIER (template_type),
5898                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
5899                                       arglist, complain, in_decl),
5900                               SCOPED_ENUM_P (template_type));
5901             }
5902           else
5903             {
5904               /* We don't want to call start_enum for this type, since
5905                  the values for the enumeration constants may involve
5906                  template parameters.  And, no one should be interested
5907                  in the enumeration constants for such a type.  */
5908               t = make_node (ENUMERAL_TYPE);
5909               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
5910             }
5911         }
5912       else
5913         {
5914           t = make_class_type (TREE_CODE (template_type));
5915           CLASSTYPE_DECLARED_CLASS (t)
5916             = CLASSTYPE_DECLARED_CLASS (template_type);
5917           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5918           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5919
5920           /* A local class.  Make sure the decl gets registered properly.  */
5921           if (context == current_function_decl)
5922             pushtag (DECL_NAME (templ), t, /*tag_scope=*/ts_current);
5923
5924           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5925             /* This instantiation is another name for the primary
5926                template type. Set the TYPE_CANONICAL field
5927                appropriately. */
5928             TYPE_CANONICAL (t) = template_type;
5929           else if (any_template_arguments_need_structural_equality_p (arglist))
5930             /* Some of the template arguments require structural
5931                equality testing, so this template class requires
5932                structural equality testing. */
5933             SET_TYPE_STRUCTURAL_EQUALITY (t);
5934         }
5935
5936       /* If we called start_enum or pushtag above, this information
5937          will already be set up.  */
5938       if (!TYPE_NAME (t))
5939         {
5940           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5941
5942           type_decl = create_implicit_typedef (DECL_NAME (templ), t);
5943           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5944           TYPE_STUB_DECL (t) = type_decl;
5945           DECL_SOURCE_LOCATION (type_decl)
5946             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5947         }
5948       else
5949         type_decl = TYPE_NAME (t);
5950
5951       TREE_PRIVATE (type_decl)
5952         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5953       TREE_PROTECTED (type_decl)
5954         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5955       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5956         {
5957           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5958           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5959         }
5960
5961       /* Set up the template information.  We have to figure out which
5962          template is the immediate parent if this is a full
5963          instantiation.  */
5964       if (parm_depth == 1 || is_partial_instantiation
5965           || !PRIMARY_TEMPLATE_P (templ))
5966         /* This case is easy; there are no member templates involved.  */
5967         found = templ;
5968       else
5969         {
5970           /* This is a full instantiation of a member template.  Look
5971              for a partial instantiation of which this is an instance.  */
5972
5973           for (found = DECL_TEMPLATE_INSTANTIATIONS (templ);
5974                found; found = TREE_CHAIN (found))
5975             {
5976               int success;
5977               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5978
5979               /* We only want partial instantiations, here, not
5980                  specializations or full instantiations.  */
5981               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5982                   || !uses_template_parms (TREE_VALUE (found)))
5983                 continue;
5984
5985               /* Temporarily reduce by one the number of levels in the
5986                  ARGLIST and in FOUND so as to avoid comparing the
5987                  last set of arguments.  */
5988               TREE_VEC_LENGTH (arglist)--;
5989               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
5990
5991               /* See if the arguments match.  If they do, then TMPL is
5992                  the partial instantiation we want.  */
5993               success = comp_template_args (TREE_PURPOSE (found), arglist);
5994
5995               /* Restore the argument vectors to their full size.  */
5996               TREE_VEC_LENGTH (arglist)++;
5997               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
5998
5999               if (success)
6000                 {
6001                   found = tmpl;
6002                   break;
6003                 }
6004             }
6005
6006           if (!found)
6007             {
6008               /* There was no partial instantiation. This happens
6009                  where C<T> is a member template of A<T> and it's used
6010                  in something like
6011
6012                   template <typename T> struct B { A<T>::C<int> m; };
6013                   B<float>;
6014
6015                  Create the partial instantiation.
6016                */
6017               TREE_VEC_LENGTH (arglist)--;
6018               found = tsubst (templ, arglist, complain, NULL_TREE);
6019               TREE_VEC_LENGTH (arglist)++;
6020             }
6021         }
6022
6023       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6024       DECL_TEMPLATE_INSTANTIATIONS (templ)
6025         = tree_cons (arglist, t,
6026                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6027
6028       if (TREE_CODE (t) == ENUMERAL_TYPE
6029           && !is_partial_instantiation)
6030         /* Now that the type has been registered on the instantiations
6031            list, we set up the enumerators.  Because the enumeration
6032            constants may involve the enumeration type itself, we make
6033            sure to register the type first, and then create the
6034            constants.  That way, doing tsubst_expr for the enumeration
6035            constants won't result in recursive calls here; we'll find
6036            the instantiation and exit above.  */
6037         tsubst_enum (template_type, t, arglist);
6038
6039       if (is_partial_instantiation)
6040         /* If the type makes use of template parameters, the
6041            code that generates debugging information will crash.  */
6042         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6043
6044       /* Possibly limit visibility based on template args.  */
6045       TREE_PUBLIC (type_decl) = 1;
6046       determine_visibility (type_decl);
6047
6048       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6049     }
6050   timevar_pop (TV_NAME_LOOKUP);
6051 }
6052 \f
6053 struct pair_fn_data
6054 {
6055   tree_fn_t fn;
6056   void *data;
6057   /* True when we should also visit template parameters that occur in
6058      non-deduced contexts.  */
6059   bool include_nondeduced_p;
6060   struct pointer_set_t *visited;
6061 };
6062
6063 /* Called from for_each_template_parm via walk_tree.  */
6064
6065 static tree
6066 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6067 {
6068   tree t = *tp;
6069   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6070   tree_fn_t fn = pfd->fn;
6071   void *data = pfd->data;
6072
6073   if (TYPE_P (t)
6074       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6075       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6076                                  pfd->include_nondeduced_p))
6077     return error_mark_node;
6078
6079   switch (TREE_CODE (t))
6080     {
6081     case RECORD_TYPE:
6082       if (TYPE_PTRMEMFUNC_P (t))
6083         break;
6084       /* Fall through.  */
6085
6086     case UNION_TYPE:
6087     case ENUMERAL_TYPE:
6088       if (!TYPE_TEMPLATE_INFO (t))
6089         *walk_subtrees = 0;
6090       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6091                                        fn, data, pfd->visited, 
6092                                        pfd->include_nondeduced_p))
6093         return error_mark_node;
6094       break;
6095
6096     case INTEGER_TYPE:
6097       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6098                                   fn, data, pfd->visited, 
6099                                   pfd->include_nondeduced_p)
6100           || for_each_template_parm (TYPE_MAX_VALUE (t),
6101                                      fn, data, pfd->visited,
6102                                      pfd->include_nondeduced_p))
6103         return error_mark_node;
6104       break;
6105
6106     case METHOD_TYPE:
6107       /* Since we're not going to walk subtrees, we have to do this
6108          explicitly here.  */
6109       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6110                                   pfd->visited, pfd->include_nondeduced_p))
6111         return error_mark_node;
6112       /* Fall through.  */
6113
6114     case FUNCTION_TYPE:
6115       /* Check the return type.  */
6116       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6117                                   pfd->include_nondeduced_p))
6118         return error_mark_node;
6119
6120       /* Check the parameter types.  Since default arguments are not
6121          instantiated until they are needed, the TYPE_ARG_TYPES may
6122          contain expressions that involve template parameters.  But,
6123          no-one should be looking at them yet.  And, once they're
6124          instantiated, they don't contain template parameters, so
6125          there's no point in looking at them then, either.  */
6126       {
6127         tree parm;
6128
6129         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6130           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6131                                       pfd->visited, pfd->include_nondeduced_p))
6132             return error_mark_node;
6133
6134         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6135            want walk_tree walking into them itself.  */
6136         *walk_subtrees = 0;
6137       }
6138       break;
6139
6140     case TYPEOF_TYPE:
6141       if (pfd->include_nondeduced_p
6142           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6143                                      pfd->visited, 
6144                                      pfd->include_nondeduced_p))
6145         return error_mark_node;
6146       break;
6147
6148     case FUNCTION_DECL:
6149     case VAR_DECL:
6150       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6151           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6152                                      pfd->visited, pfd->include_nondeduced_p))
6153         return error_mark_node;
6154       /* Fall through.  */
6155
6156     case PARM_DECL:
6157     case CONST_DECL:
6158       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6159           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6160                                      pfd->visited, pfd->include_nondeduced_p))
6161         return error_mark_node;
6162       if (DECL_CONTEXT (t)
6163           && pfd->include_nondeduced_p
6164           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6165                                      pfd->visited, pfd->include_nondeduced_p))
6166         return error_mark_node;
6167       break;
6168
6169     case BOUND_TEMPLATE_TEMPLATE_PARM:
6170       /* Record template parameters such as `T' inside `TT<T>'.  */
6171       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6172                                   pfd->include_nondeduced_p))
6173         return error_mark_node;
6174       /* Fall through.  */
6175
6176     case TEMPLATE_TEMPLATE_PARM:
6177     case TEMPLATE_TYPE_PARM:
6178     case TEMPLATE_PARM_INDEX:
6179       if (fn && (*fn)(t, data))
6180         return error_mark_node;
6181       else if (!fn)
6182         return error_mark_node;
6183       break;
6184
6185     case TEMPLATE_DECL:
6186       /* A template template parameter is encountered.  */
6187       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6188           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6189                                      pfd->include_nondeduced_p))
6190         return error_mark_node;
6191
6192       /* Already substituted template template parameter */
6193       *walk_subtrees = 0;
6194       break;
6195
6196     case TYPENAME_TYPE:
6197       if (!fn
6198           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6199                                      data, pfd->visited, 
6200                                      pfd->include_nondeduced_p))
6201         return error_mark_node;
6202       break;
6203
6204     case CONSTRUCTOR:
6205       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6206           && pfd->include_nondeduced_p
6207           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6208                                      (TREE_TYPE (t)), fn, data,
6209                                      pfd->visited, pfd->include_nondeduced_p))
6210         return error_mark_node;
6211       break;
6212
6213     case INDIRECT_REF:
6214     case COMPONENT_REF:
6215       /* If there's no type, then this thing must be some expression
6216          involving template parameters.  */
6217       if (!fn && !TREE_TYPE (t))
6218         return error_mark_node;
6219       break;
6220
6221     case MODOP_EXPR:
6222     case CAST_EXPR:
6223     case REINTERPRET_CAST_EXPR:
6224     case CONST_CAST_EXPR:
6225     case STATIC_CAST_EXPR:
6226     case DYNAMIC_CAST_EXPR:
6227     case ARROW_EXPR:
6228     case DOTSTAR_EXPR:
6229     case TYPEID_EXPR:
6230     case PSEUDO_DTOR_EXPR:
6231       if (!fn)
6232         return error_mark_node;
6233       break;
6234
6235     default:
6236       break;
6237     }
6238
6239   /* We didn't find any template parameters we liked.  */
6240   return NULL_TREE;
6241 }
6242
6243 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6244    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6245    call FN with the parameter and the DATA.
6246    If FN returns nonzero, the iteration is terminated, and
6247    for_each_template_parm returns 1.  Otherwise, the iteration
6248    continues.  If FN never returns a nonzero value, the value
6249    returned by for_each_template_parm is 0.  If FN is NULL, it is
6250    considered to be the function which always returns 1.
6251
6252    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6253    parameters that occur in non-deduced contexts.  When false, only
6254    visits those template parameters that can be deduced.  */
6255
6256 static int
6257 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6258                         struct pointer_set_t *visited,
6259                         bool include_nondeduced_p)
6260 {
6261   struct pair_fn_data pfd;
6262   int result;
6263
6264   /* Set up.  */
6265   pfd.fn = fn;
6266   pfd.data = data;
6267   pfd.include_nondeduced_p = include_nondeduced_p;
6268
6269   /* Walk the tree.  (Conceptually, we would like to walk without
6270      duplicates, but for_each_template_parm_r recursively calls
6271      for_each_template_parm, so we would need to reorganize a fair
6272      bit to use walk_tree_without_duplicates, so we keep our own
6273      visited list.)  */
6274   if (visited)
6275     pfd.visited = visited;
6276   else
6277     pfd.visited = pointer_set_create ();
6278   result = cp_walk_tree (&t,
6279                          for_each_template_parm_r,
6280                          &pfd,
6281                          pfd.visited) != NULL_TREE;
6282
6283   /* Clean up.  */
6284   if (!visited)
6285     {
6286       pointer_set_destroy (pfd.visited);
6287       pfd.visited = 0;
6288     }
6289
6290   return result;
6291 }
6292
6293 /* Returns true if T depends on any template parameter.  */
6294
6295 int
6296 uses_template_parms (tree t)
6297 {
6298   bool dependent_p;
6299   int saved_processing_template_decl;
6300
6301   saved_processing_template_decl = processing_template_decl;
6302   if (!saved_processing_template_decl)
6303     processing_template_decl = 1;
6304   if (TYPE_P (t))
6305     dependent_p = dependent_type_p (t);
6306   else if (TREE_CODE (t) == TREE_VEC)
6307     dependent_p = any_dependent_template_arguments_p (t);
6308   else if (TREE_CODE (t) == TREE_LIST)
6309     dependent_p = (uses_template_parms (TREE_VALUE (t))
6310                    || uses_template_parms (TREE_CHAIN (t)));
6311   else if (TREE_CODE (t) == TYPE_DECL)
6312     dependent_p = dependent_type_p (TREE_TYPE (t));
6313   else if (DECL_P (t)
6314            || EXPR_P (t)
6315            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6316            || TREE_CODE (t) == OVERLOAD
6317            || TREE_CODE (t) == BASELINK
6318            || TREE_CODE (t) == IDENTIFIER_NODE
6319            || TREE_CODE (t) == TRAIT_EXPR
6320            || TREE_CODE (t) == CONSTRUCTOR
6321            || CONSTANT_CLASS_P (t))
6322     dependent_p = (type_dependent_expression_p (t)
6323                    || value_dependent_expression_p (t));
6324   else
6325     {
6326       gcc_assert (t == error_mark_node);
6327       dependent_p = false;
6328     }
6329
6330   processing_template_decl = saved_processing_template_decl;
6331
6332   return dependent_p;
6333 }
6334
6335 /* Returns true if T depends on any template parameter with level LEVEL.  */
6336
6337 int
6338 uses_template_parms_level (tree t, int level)
6339 {
6340   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6341                                  /*include_nondeduced_p=*/true);
6342 }
6343
6344 static int tinst_depth;
6345 extern int max_tinst_depth;
6346 #ifdef GATHER_STATISTICS
6347 int depth_reached;
6348 #endif
6349 static int tinst_level_tick;
6350 static int last_template_error_tick;
6351
6352 /* We're starting to instantiate D; record the template instantiation context
6353    for diagnostics and to restore it later.  */
6354
6355 static int
6356 push_tinst_level (tree d)
6357 {
6358   struct tinst_level *new_level;
6359
6360   if (tinst_depth >= max_tinst_depth)
6361     {
6362       /* If the instantiation in question still has unbound template parms,
6363          we don't really care if we can't instantiate it, so just return.
6364          This happens with base instantiation for implicit `typename'.  */
6365       if (uses_template_parms (d))
6366         return 0;
6367
6368       last_template_error_tick = tinst_level_tick;
6369       error ("template instantiation depth exceeds maximum of %d (use "
6370              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6371              max_tinst_depth, d);
6372
6373       print_instantiation_context ();
6374
6375       return 0;
6376     }
6377
6378   new_level = GGC_NEW (struct tinst_level);
6379   new_level->decl = d;
6380   new_level->locus = input_location;
6381   new_level->in_system_header_p = in_system_header;
6382   new_level->next = current_tinst_level;
6383   current_tinst_level = new_level;
6384
6385   ++tinst_depth;
6386 #ifdef GATHER_STATISTICS
6387   if (tinst_depth > depth_reached)
6388     depth_reached = tinst_depth;
6389 #endif
6390
6391   ++tinst_level_tick;
6392   return 1;
6393 }
6394
6395 /* We're done instantiating this template; return to the instantiation
6396    context.  */
6397
6398 static void
6399 pop_tinst_level (void)
6400 {
6401   /* Restore the filename and line number stashed away when we started
6402      this instantiation.  */
6403   input_location = current_tinst_level->locus;
6404   current_tinst_level = current_tinst_level->next;
6405   --tinst_depth;
6406   ++tinst_level_tick;
6407 }
6408
6409 /* We're instantiating a deferred template; restore the template
6410    instantiation context in which the instantiation was requested, which
6411    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6412
6413 static tree
6414 reopen_tinst_level (struct tinst_level *level)
6415 {
6416   struct tinst_level *t;
6417
6418   tinst_depth = 0;
6419   for (t = level; t; t = t->next)
6420     ++tinst_depth;
6421
6422   current_tinst_level = level;
6423   pop_tinst_level ();
6424   return level->decl;
6425 }
6426
6427 /* Returns the TINST_LEVEL which gives the original instantiation
6428    context.  */
6429
6430 struct tinst_level *
6431 outermost_tinst_level (void)
6432 {
6433   struct tinst_level *level = current_tinst_level;
6434   if (level)
6435     while (level->next)
6436       level = level->next;
6437   return level;
6438 }
6439
6440 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6441
6442 bool
6443 parameter_of_template_p (tree parm, tree templ)
6444 {
6445   tree parms;
6446   int i;
6447
6448   if (!parm || !templ)
6449     return false;
6450
6451   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6452   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6453
6454   parms = DECL_TEMPLATE_PARMS (templ);
6455   parms = INNERMOST_TEMPLATE_PARMS (parms);
6456
6457   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6458     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6459       return true;
6460
6461   return false;
6462 }
6463
6464 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6465    vector of template arguments, as for tsubst.
6466
6467    Returns an appropriate tsubst'd friend declaration.  */
6468
6469 static tree
6470 tsubst_friend_function (tree decl, tree args)
6471 {
6472   tree new_friend;
6473
6474   if (TREE_CODE (decl) == FUNCTION_DECL
6475       && DECL_TEMPLATE_INSTANTIATION (decl)
6476       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6477     /* This was a friend declared with an explicit template
6478        argument list, e.g.:
6479
6480        friend void f<>(T);
6481
6482        to indicate that f was a template instantiation, not a new
6483        function declaration.  Now, we have to figure out what
6484        instantiation of what template.  */
6485     {
6486       tree template_id, arglist, fns;
6487       tree new_args;
6488       tree tmpl;
6489       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6490
6491       /* Friend functions are looked up in the containing namespace scope.
6492          We must enter that scope, to avoid finding member functions of the
6493          current class with same name.  */
6494       push_nested_namespace (ns);
6495       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6496                          tf_warning_or_error, NULL_TREE,
6497                          /*integral_constant_expression_p=*/false);
6498       pop_nested_namespace (ns);
6499       arglist = tsubst (DECL_TI_ARGS (decl), args,
6500                         tf_warning_or_error, NULL_TREE);
6501       template_id = lookup_template_function (fns, arglist);
6502
6503       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6504       tmpl = determine_specialization (template_id, new_friend,
6505                                        &new_args,
6506                                        /*need_member_template=*/0,
6507                                        TREE_VEC_LENGTH (args),
6508                                        tsk_none);
6509       return instantiate_template (tmpl, new_args, tf_error);
6510     }
6511
6512   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6513
6514   /* The NEW_FRIEND will look like an instantiation, to the
6515      compiler, but is not an instantiation from the point of view of
6516      the language.  For example, we might have had:
6517
6518      template <class T> struct S {
6519        template <class U> friend void f(T, U);
6520      };
6521
6522      Then, in S<int>, template <class U> void f(int, U) is not an
6523      instantiation of anything.  */
6524   if (new_friend == error_mark_node)
6525     return error_mark_node;
6526
6527   DECL_USE_TEMPLATE (new_friend) = 0;
6528   if (TREE_CODE (decl) == TEMPLATE_DECL)
6529     {
6530       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6531       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6532         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6533     }
6534
6535   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6536      is not a template instantiation and should not be mangled like
6537      one.  Therefore, we forget the mangling here; we'll recompute it
6538      later if we need it.  */
6539   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6540     {
6541       SET_DECL_RTL (new_friend, NULL_RTX);
6542       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6543     }
6544
6545   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6546     {
6547       tree old_decl;
6548       tree new_friend_template_info;
6549       tree new_friend_result_template_info;
6550       tree ns;
6551       int  new_friend_is_defn;
6552
6553       /* We must save some information from NEW_FRIEND before calling
6554          duplicate decls since that function will free NEW_FRIEND if
6555          possible.  */
6556       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6557       new_friend_is_defn =
6558             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6559                            (template_for_substitution (new_friend)))
6560              != NULL_TREE);
6561       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6562         {
6563           /* This declaration is a `primary' template.  */
6564           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6565
6566           new_friend_result_template_info
6567             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6568         }
6569       else
6570         new_friend_result_template_info = NULL_TREE;
6571
6572       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6573       if (new_friend_is_defn)
6574         DECL_INITIAL (new_friend) = error_mark_node;
6575
6576       /* Inside pushdecl_namespace_level, we will push into the
6577          current namespace. However, the friend function should go
6578          into the namespace of the template.  */
6579       ns = decl_namespace_context (new_friend);
6580       push_nested_namespace (ns);
6581       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6582       pop_nested_namespace (ns);
6583
6584       if (old_decl == error_mark_node)
6585         return error_mark_node;
6586
6587       if (old_decl != new_friend)
6588         {
6589           /* This new friend declaration matched an existing
6590              declaration.  For example, given:
6591
6592                template <class T> void f(T);
6593                template <class U> class C {
6594                  template <class T> friend void f(T) {}
6595                };
6596
6597              the friend declaration actually provides the definition
6598              of `f', once C has been instantiated for some type.  So,
6599              old_decl will be the out-of-class template declaration,
6600              while new_friend is the in-class definition.
6601
6602              But, if `f' was called before this point, the
6603              instantiation of `f' will have DECL_TI_ARGS corresponding
6604              to `T' but not to `U', references to which might appear
6605              in the definition of `f'.  Previously, the most general
6606              template for an instantiation of `f' was the out-of-class
6607              version; now it is the in-class version.  Therefore, we
6608              run through all specialization of `f', adding to their
6609              DECL_TI_ARGS appropriately.  In particular, they need a
6610              new set of outer arguments, corresponding to the
6611              arguments for this class instantiation.
6612
6613              The same situation can arise with something like this:
6614
6615                friend void f(int);
6616                template <class T> class C {
6617                  friend void f(T) {}
6618                };
6619
6620              when `C<int>' is instantiated.  Now, `f(int)' is defined
6621              in the class.  */
6622
6623           if (!new_friend_is_defn)
6624             /* On the other hand, if the in-class declaration does
6625                *not* provide a definition, then we don't want to alter
6626                existing definitions.  We can just leave everything
6627                alone.  */
6628             ;
6629           else
6630             {
6631               /* Overwrite whatever template info was there before, if
6632                  any, with the new template information pertaining to
6633                  the declaration.  */
6634               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6635
6636               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6637                 reregister_specialization (new_friend,
6638                                            most_general_template (old_decl),
6639                                            old_decl);
6640               else
6641                 {
6642                   tree t;
6643                   tree new_friend_args;
6644
6645                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6646                     = new_friend_result_template_info;
6647
6648                   new_friend_args = TI_ARGS (new_friend_template_info);
6649                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6650                        t != NULL_TREE;
6651                        t = TREE_CHAIN (t))
6652                     {
6653                       tree spec = TREE_VALUE (t);
6654
6655                       DECL_TI_ARGS (spec)
6656                         = add_outermost_template_args (new_friend_args,
6657                                                        DECL_TI_ARGS (spec));
6658                     }
6659
6660                   /* Now, since specializations are always supposed to
6661                      hang off of the most general template, we must move
6662                      them.  */
6663                   t = most_general_template (old_decl);
6664                   if (t != old_decl)
6665                     {
6666                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6667                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6668                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6669                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6670                     }
6671                 }
6672             }
6673
6674           /* The information from NEW_FRIEND has been merged into OLD_DECL
6675              by duplicate_decls.  */
6676           new_friend = old_decl;
6677         }
6678     }
6679   else
6680     {
6681       tree context = DECL_CONTEXT (new_friend);
6682       bool dependent_p;
6683
6684       /* In the code
6685            template <class T> class C {
6686              template <class U> friend void C1<U>::f (); // case 1
6687              friend void C2<T>::f ();                    // case 2
6688            };
6689          we only need to make sure CONTEXT is a complete type for
6690          case 2.  To distinguish between the two cases, we note that
6691          CONTEXT of case 1 remains dependent type after tsubst while
6692          this isn't true for case 2.  */
6693       ++processing_template_decl;
6694       dependent_p = dependent_type_p (context);
6695       --processing_template_decl;
6696
6697       if (!dependent_p
6698           && !complete_type_or_else (context, NULL_TREE))
6699         return error_mark_node;
6700
6701       if (COMPLETE_TYPE_P (context))
6702         {
6703           /* Check to see that the declaration is really present, and,
6704              possibly obtain an improved declaration.  */
6705           tree fn = check_classfn (context,
6706                                    new_friend, NULL_TREE);
6707
6708           if (fn)
6709             new_friend = fn;
6710         }
6711     }
6712
6713   return new_friend;
6714 }
6715
6716 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6717    template arguments, as for tsubst.
6718
6719    Returns an appropriate tsubst'd friend type or error_mark_node on
6720    failure.  */
6721
6722 static tree
6723 tsubst_friend_class (tree friend_tmpl, tree args)
6724 {
6725   tree friend_type;
6726   tree tmpl;
6727   tree context;
6728
6729   context = DECL_CONTEXT (friend_tmpl);
6730
6731   if (context)
6732     {
6733       if (TREE_CODE (context) == NAMESPACE_DECL)
6734         push_nested_namespace (context);
6735       else
6736         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6737     }
6738
6739   /* Look for a class template declaration.  We look for hidden names
6740      because two friend declarations of the same template are the
6741      same.  For example, in:
6742
6743        struct A { 
6744          template <typename> friend class F;
6745        };
6746        template <typename> struct B { 
6747          template <typename> friend class F;
6748        };
6749
6750      both F templates are the same.  */
6751   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6752                            /*block_p=*/true, 0, 
6753                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6754
6755   /* But, if we don't find one, it might be because we're in a
6756      situation like this:
6757
6758        template <class T>
6759        struct S {
6760          template <class U>
6761          friend struct S;
6762        };
6763
6764      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6765      for `S<int>', not the TEMPLATE_DECL.  */
6766   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6767     {
6768       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6769       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6770     }
6771
6772   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6773     {
6774       /* The friend template has already been declared.  Just
6775          check to see that the declarations match, and install any new
6776          default parameters.  We must tsubst the default parameters,
6777          of course.  We only need the innermost template parameters
6778          because that is all that redeclare_class_template will look
6779          at.  */
6780       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6781           > TMPL_ARGS_DEPTH (args))
6782         {
6783           tree parms;
6784           location_t saved_input_location;
6785           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6786                                          args, tf_warning_or_error);
6787
6788           saved_input_location = input_location;
6789           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6790           redeclare_class_template (TREE_TYPE (tmpl), parms);
6791           input_location = saved_input_location;
6792           
6793         }
6794
6795       friend_type = TREE_TYPE (tmpl);
6796     }
6797   else
6798     {
6799       /* The friend template has not already been declared.  In this
6800          case, the instantiation of the template class will cause the
6801          injection of this template into the global scope.  */
6802       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6803       if (tmpl == error_mark_node)
6804         return error_mark_node;
6805
6806       /* The new TMPL is not an instantiation of anything, so we
6807          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6808          the new type because that is supposed to be the corresponding
6809          template decl, i.e., TMPL.  */
6810       DECL_USE_TEMPLATE (tmpl) = 0;
6811       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6812       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6813       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6814         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6815
6816       /* Inject this template into the global scope.  */
6817       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6818     }
6819
6820   if (context)
6821     {
6822       if (TREE_CODE (context) == NAMESPACE_DECL)
6823         pop_nested_namespace (context);
6824       else
6825         pop_nested_class ();
6826     }
6827
6828   return friend_type;
6829 }
6830
6831 /* Returns zero if TYPE cannot be completed later due to circularity.
6832    Otherwise returns one.  */
6833
6834 static int
6835 can_complete_type_without_circularity (tree type)
6836 {
6837   if (type == NULL_TREE || type == error_mark_node)
6838     return 0;
6839   else if (COMPLETE_TYPE_P (type))
6840     return 1;
6841   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6842     return can_complete_type_without_circularity (TREE_TYPE (type));
6843   else if (CLASS_TYPE_P (type)
6844            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6845     return 0;
6846   else
6847     return 1;
6848 }
6849
6850 /* Apply any attributes which had to be deferred until instantiation
6851    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6852    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6853
6854 static void
6855 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6856                                 tree args, tsubst_flags_t complain, tree in_decl)
6857 {
6858   tree last_dep = NULL_TREE;
6859   tree t;
6860   tree *p;
6861
6862   for (t = attributes; t; t = TREE_CHAIN (t))
6863     if (ATTR_IS_DEPENDENT (t))
6864       {
6865         last_dep = t;
6866         attributes = copy_list (attributes);
6867         break;
6868       }
6869
6870   if (DECL_P (*decl_p))
6871     {
6872       if (TREE_TYPE (*decl_p) == error_mark_node)
6873         return;
6874       p = &DECL_ATTRIBUTES (*decl_p);
6875     }
6876   else
6877     p = &TYPE_ATTRIBUTES (*decl_p);
6878
6879   if (last_dep)
6880     {
6881       tree late_attrs = NULL_TREE;
6882       tree *q = &late_attrs;
6883
6884       for (*p = attributes; *p; )
6885         {
6886           t = *p;
6887           if (ATTR_IS_DEPENDENT (t))
6888             {
6889               *p = TREE_CHAIN (t);
6890               TREE_CHAIN (t) = NULL_TREE;
6891               /* If the first attribute argument is an identifier, don't
6892                  pass it through tsubst.  Attributes like mode, format,
6893                  cleanup and several target specific attributes expect it
6894                  unmodified.  */
6895               if (TREE_VALUE (t)
6896                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
6897                   && TREE_VALUE (TREE_VALUE (t))
6898                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
6899                       == IDENTIFIER_NODE))
6900                 {
6901                   tree chain
6902                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
6903                                    in_decl,
6904                                    /*integral_constant_expression_p=*/false);
6905                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
6906                     TREE_VALUE (t)
6907                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
6908                                    chain);
6909                 }
6910               else
6911                 TREE_VALUE (t)
6912                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6913                                  /*integral_constant_expression_p=*/false);
6914               *q = t;
6915               q = &TREE_CHAIN (t);
6916             }
6917           else
6918             p = &TREE_CHAIN (t);
6919         }
6920
6921       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
6922     }
6923 }
6924
6925 /* Perform (or defer) access check for typedefs that were referenced
6926    from within the template TMPL code.
6927    This is a subroutine of instantiate_template and instantiate_class_template.
6928    TMPL is the template to consider and TARGS is the list of arguments of
6929    that template.  */
6930
6931 static void
6932 perform_typedefs_access_check (tree tmpl, tree targs)
6933 {
6934   tree t;
6935
6936   if (!tmpl
6937       || (TREE_CODE (tmpl) != RECORD_TYPE
6938           && TREE_CODE (tmpl) != FUNCTION_DECL))
6939     return;
6940
6941   for (t = get_types_needing_access_check (tmpl); t; t = TREE_CHAIN (t))
6942     {
6943       tree type_decl = TREE_PURPOSE (t);
6944       tree type_scope = TREE_VALUE (t);
6945
6946       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
6947         continue;
6948
6949       if (uses_template_parms (type_decl))
6950         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
6951       if (uses_template_parms (type_scope))
6952         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
6953
6954       perform_or_defer_access_check (TYPE_BINFO (type_scope),
6955                                      type_decl, type_decl);
6956     }
6957 }
6958
6959 tree
6960 instantiate_class_template (tree type)
6961 {
6962   tree templ, args, pattern, t, member;
6963   tree typedecl;
6964   tree pbinfo;
6965   tree base_list;
6966
6967   if (type == error_mark_node)
6968     return error_mark_node;
6969
6970   if (TYPE_BEING_DEFINED (type)
6971       || COMPLETE_TYPE_P (type)
6972       || dependent_type_p (type))
6973     return type;
6974
6975   /* Figure out which template is being instantiated.  */
6976   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6977   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6978
6979   /* Determine what specialization of the original template to
6980      instantiate.  */
6981   t = most_specialized_class (type, templ);
6982   if (t == error_mark_node)
6983     {
6984       TYPE_BEING_DEFINED (type) = 1;
6985       return error_mark_node;
6986     }
6987   else if (t)
6988     {
6989       /* This TYPE is actually an instantiation of a partial
6990          specialization.  We replace the innermost set of ARGS with
6991          the arguments appropriate for substitution.  For example,
6992          given:
6993
6994            template <class T> struct S {};
6995            template <class T> struct S<T*> {};
6996
6997          and supposing that we are instantiating S<int*>, ARGS will
6998          presently be {int*} -- but we need {int}.  */
6999       pattern = TREE_TYPE (t);
7000       args = TREE_PURPOSE (t);
7001     }
7002   else
7003     {
7004       pattern = TREE_TYPE (templ);
7005       args = CLASSTYPE_TI_ARGS (type);
7006     }
7007
7008   /* If the template we're instantiating is incomplete, then clearly
7009      there's nothing we can do.  */
7010   if (!COMPLETE_TYPE_P (pattern))
7011     return type;
7012
7013   /* If we've recursively instantiated too many templates, stop.  */
7014   if (! push_tinst_level (type))
7015     return type;
7016
7017   /* Now we're really doing the instantiation.  Mark the type as in
7018      the process of being defined.  */
7019   TYPE_BEING_DEFINED (type) = 1;
7020
7021   /* We may be in the middle of deferred access check.  Disable
7022      it now.  */
7023   push_deferring_access_checks (dk_no_deferred);
7024
7025   push_to_top_level ();
7026
7027   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7028
7029   /* Set the input location to the most specialized template definition.
7030      This is needed if tsubsting causes an error.  */
7031   typedecl = TYPE_MAIN_DECL (pattern);
7032   input_location = DECL_SOURCE_LOCATION (typedecl);
7033
7034   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7035   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7036   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7037   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7038   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7039   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7040   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7041   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7042   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7043   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7044   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7045   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7046   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7047   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7048   if (ANON_AGGR_TYPE_P (pattern))
7049     SET_ANON_AGGR_TYPE_P (type);
7050   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7051     {
7052       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7053       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7054     }
7055
7056   pbinfo = TYPE_BINFO (pattern);
7057
7058   /* We should never instantiate a nested class before its enclosing
7059      class; we need to look up the nested class by name before we can
7060      instantiate it, and that lookup should instantiate the enclosing
7061      class.  */
7062   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7063               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7064               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7065
7066   base_list = NULL_TREE;
7067   if (BINFO_N_BASE_BINFOS (pbinfo))
7068     {
7069       tree pbase_binfo;
7070       tree context = TYPE_CONTEXT (type);
7071       tree pushed_scope;
7072       int i;
7073
7074       /* We must enter the scope containing the type, as that is where
7075          the accessibility of types named in dependent bases are
7076          looked up from.  */
7077       pushed_scope = push_scope (context ? context : global_namespace);
7078
7079       /* Substitute into each of the bases to determine the actual
7080          basetypes.  */
7081       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7082         {
7083           tree base;
7084           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7085           tree expanded_bases = NULL_TREE;
7086           int idx, len = 1;
7087
7088           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7089             {
7090               expanded_bases = 
7091                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7092                                        args, tf_error, NULL_TREE);
7093               if (expanded_bases == error_mark_node)
7094                 continue;
7095
7096               len = TREE_VEC_LENGTH (expanded_bases);
7097             }
7098
7099           for (idx = 0; idx < len; idx++)
7100             {
7101               if (expanded_bases)
7102                 /* Extract the already-expanded base class.  */
7103                 base = TREE_VEC_ELT (expanded_bases, idx);
7104               else
7105                 /* Substitute to figure out the base class.  */
7106                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7107                                NULL_TREE);
7108
7109               if (base == error_mark_node)
7110                 continue;
7111
7112               base_list = tree_cons (access, base, base_list);
7113               if (BINFO_VIRTUAL_P (pbase_binfo))
7114                 TREE_TYPE (base_list) = integer_type_node;
7115             }
7116         }
7117
7118       /* The list is now in reverse order; correct that.  */
7119       base_list = nreverse (base_list);
7120
7121       if (pushed_scope)
7122         pop_scope (pushed_scope);
7123     }
7124   /* Now call xref_basetypes to set up all the base-class
7125      information.  */
7126   xref_basetypes (type, base_list);
7127
7128   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7129                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7130                                   args, tf_error, NULL_TREE);
7131
7132   /* Now that our base classes are set up, enter the scope of the
7133      class, so that name lookups into base classes, etc. will work
7134      correctly.  This is precisely analogous to what we do in
7135      begin_class_definition when defining an ordinary non-template
7136      class, except we also need to push the enclosing classes.  */
7137   push_nested_class (type);
7138
7139   /* Now members are processed in the order of declaration.  */
7140   for (member = CLASSTYPE_DECL_LIST (pattern);
7141        member; member = TREE_CHAIN (member))
7142     {
7143       tree t = TREE_VALUE (member);
7144
7145       if (TREE_PURPOSE (member))
7146         {
7147           if (TYPE_P (t))
7148             {
7149               /* Build new CLASSTYPE_NESTED_UTDS.  */
7150
7151               tree newtag;
7152               bool class_template_p;
7153
7154               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7155                                   && TYPE_LANG_SPECIFIC (t)
7156                                   && CLASSTYPE_IS_TEMPLATE (t));
7157               /* If the member is a class template, then -- even after
7158                  substitution -- there may be dependent types in the
7159                  template argument list for the class.  We increment
7160                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7161                  that function will assume that no types are dependent
7162                  when outside of a template.  */
7163               if (class_template_p)
7164                 ++processing_template_decl;
7165               newtag = tsubst (t, args, tf_error, NULL_TREE);
7166               if (class_template_p)
7167                 --processing_template_decl;
7168               if (newtag == error_mark_node)
7169                 continue;
7170
7171               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7172                 {
7173                   tree name = TYPE_IDENTIFIER (t);
7174
7175                   if (class_template_p)
7176                     /* Unfortunately, lookup_template_class sets
7177                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7178                        instantiation (i.e., for the type of a member
7179                        template class nested within a template class.)
7180                        This behavior is required for
7181                        maybe_process_partial_specialization to work
7182                        correctly, but is not accurate in this case;
7183                        the TAG is not an instantiation of anything.
7184                        (The corresponding TEMPLATE_DECL is an
7185                        instantiation, but the TYPE is not.) */
7186                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7187
7188                   /* Now, we call pushtag to put this NEWTAG into the scope of
7189                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7190                      pushtag calling push_template_decl.  We don't have to do
7191                      this for enums because it will already have been done in
7192                      tsubst_enum.  */
7193                   if (name)
7194                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7195                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7196                 }
7197             }
7198           else if (TREE_CODE (t) == FUNCTION_DECL
7199                    || DECL_FUNCTION_TEMPLATE_P (t))
7200             {
7201               /* Build new TYPE_METHODS.  */
7202               tree r;
7203
7204               if (TREE_CODE (t) == TEMPLATE_DECL)
7205                 ++processing_template_decl;
7206               r = tsubst (t, args, tf_error, NULL_TREE);
7207               if (TREE_CODE (t) == TEMPLATE_DECL)
7208                 --processing_template_decl;
7209               set_current_access_from_decl (r);
7210               finish_member_declaration (r);
7211             }
7212           else
7213             {
7214               /* Build new TYPE_FIELDS.  */
7215               if (TREE_CODE (t) == STATIC_ASSERT)
7216                 {
7217                   tree condition = 
7218                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7219                                  tf_warning_or_error, NULL_TREE,
7220                                  /*integral_constant_expression_p=*/true);
7221                   finish_static_assert (condition,
7222                                         STATIC_ASSERT_MESSAGE (t), 
7223                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7224                                         /*member_p=*/true);
7225                 }
7226               else if (TREE_CODE (t) != CONST_DECL)
7227                 {
7228                   tree r;
7229
7230                   /* The file and line for this declaration, to
7231                      assist in error message reporting.  Since we
7232                      called push_tinst_level above, we don't need to
7233                      restore these.  */
7234                   input_location = DECL_SOURCE_LOCATION (t);
7235
7236                   if (TREE_CODE (t) == TEMPLATE_DECL)
7237                     ++processing_template_decl;
7238                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7239                   if (TREE_CODE (t) == TEMPLATE_DECL)
7240                     --processing_template_decl;
7241                   if (TREE_CODE (r) == VAR_DECL)
7242                     {
7243                       /* In [temp.inst]:
7244
7245                            [t]he initialization (and any associated
7246                            side-effects) of a static data member does
7247                            not occur unless the static data member is
7248                            itself used in a way that requires the
7249                            definition of the static data member to
7250                            exist.
7251
7252                          Therefore, we do not substitute into the
7253                          initialized for the static data member here.  */
7254                       finish_static_data_member_decl
7255                         (r,
7256                          /*init=*/NULL_TREE,
7257                          /*init_const_expr_p=*/false,
7258                          /*asmspec_tree=*/NULL_TREE,
7259                          /*flags=*/0);
7260                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7261                         check_static_variable_definition (r, TREE_TYPE (r));
7262                     }
7263                   else if (TREE_CODE (r) == FIELD_DECL)
7264                     {
7265                       /* Determine whether R has a valid type and can be
7266                          completed later.  If R is invalid, then it is
7267                          replaced by error_mark_node so that it will not be
7268                          added to TYPE_FIELDS.  */
7269                       tree rtype = TREE_TYPE (r);
7270                       if (can_complete_type_without_circularity (rtype))
7271                         complete_type (rtype);
7272
7273                       if (!COMPLETE_TYPE_P (rtype))
7274                         {
7275                           cxx_incomplete_type_error (r, rtype);
7276                           r = error_mark_node;
7277                         }
7278                     }
7279
7280                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7281                      such a thing will already have been added to the field
7282                      list by tsubst_enum in finish_member_declaration in the
7283                      CLASSTYPE_NESTED_UTDS case above.  */
7284                   if (!(TREE_CODE (r) == TYPE_DECL
7285                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7286                         && DECL_ARTIFICIAL (r)))
7287                     {
7288                       set_current_access_from_decl (r);
7289                       finish_member_declaration (r);
7290                     }
7291                 }
7292             }
7293         }
7294       else
7295         {
7296           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7297             {
7298               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7299
7300               tree friend_type = t;
7301               bool adjust_processing_template_decl = false;
7302
7303               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7304                 {
7305                   /* template <class T> friend class C;  */
7306                   friend_type = tsubst_friend_class (friend_type, args);
7307                   adjust_processing_template_decl = true;
7308                 }
7309               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7310                 {
7311                   /* template <class T> friend class C::D;  */
7312                   friend_type = tsubst (friend_type, args,
7313                                         tf_warning_or_error, NULL_TREE);
7314                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7315                     friend_type = TREE_TYPE (friend_type);
7316                   adjust_processing_template_decl = true;
7317                 }
7318               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7319                 {
7320                   /* This could be either
7321
7322                        friend class T::C;
7323
7324                      when dependent_type_p is false or
7325
7326                        template <class U> friend class T::C;
7327
7328                      otherwise.  */
7329                   friend_type = tsubst (friend_type, args,
7330                                         tf_warning_or_error, NULL_TREE);
7331                   /* Bump processing_template_decl for correct
7332                      dependent_type_p calculation.  */
7333                   ++processing_template_decl;
7334                   if (dependent_type_p (friend_type))
7335                     adjust_processing_template_decl = true;
7336                   --processing_template_decl;
7337                 }
7338               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7339                        && hidden_name_p (TYPE_NAME (friend_type)))
7340                 {
7341                   /* friend class C;
7342
7343                      where C hasn't been declared yet.  Let's lookup name
7344                      from namespace scope directly, bypassing any name that
7345                      come from dependent base class.  */
7346                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7347
7348                   /* The call to xref_tag_from_type does injection for friend
7349                      classes.  */
7350                   push_nested_namespace (ns);
7351                   friend_type =
7352                     xref_tag_from_type (friend_type, NULL_TREE,
7353                                         /*tag_scope=*/ts_current);
7354                   pop_nested_namespace (ns);
7355                 }
7356               else if (uses_template_parms (friend_type))
7357                 /* friend class C<T>;  */
7358                 friend_type = tsubst (friend_type, args,
7359                                       tf_warning_or_error, NULL_TREE);
7360               /* Otherwise it's
7361
7362                    friend class C;
7363
7364                  where C is already declared or
7365
7366                    friend class C<int>;
7367
7368                  We don't have to do anything in these cases.  */
7369
7370               if (adjust_processing_template_decl)
7371                 /* Trick make_friend_class into realizing that the friend
7372                    we're adding is a template, not an ordinary class.  It's
7373                    important that we use make_friend_class since it will
7374                    perform some error-checking and output cross-reference
7375                    information.  */
7376                 ++processing_template_decl;
7377
7378               if (friend_type != error_mark_node)
7379                 make_friend_class (type, friend_type, /*complain=*/false);
7380
7381               if (adjust_processing_template_decl)
7382                 --processing_template_decl;
7383             }
7384           else
7385             {
7386               /* Build new DECL_FRIENDLIST.  */
7387               tree r;
7388
7389               /* The file and line for this declaration, to
7390                  assist in error message reporting.  Since we
7391                  called push_tinst_level above, we don't need to
7392                  restore these.  */
7393               input_location = DECL_SOURCE_LOCATION (t);
7394
7395               if (TREE_CODE (t) == TEMPLATE_DECL)
7396                 {
7397                   ++processing_template_decl;
7398                   push_deferring_access_checks (dk_no_check);
7399                 }
7400
7401               r = tsubst_friend_function (t, args);
7402               add_friend (type, r, /*complain=*/false);
7403               if (TREE_CODE (t) == TEMPLATE_DECL)
7404                 {
7405                   pop_deferring_access_checks ();
7406                   --processing_template_decl;
7407                 }
7408             }
7409         }
7410     }
7411
7412   /* Set the file and line number information to whatever is given for
7413      the class itself.  This puts error messages involving generated
7414      implicit functions at a predictable point, and the same point
7415      that would be used for non-template classes.  */
7416   input_location = DECL_SOURCE_LOCATION (typedecl);
7417
7418   unreverse_member_declarations (type);
7419   finish_struct_1 (type);
7420   TYPE_BEING_DEFINED (type) = 0;
7421
7422   /* Now that the class is complete, instantiate default arguments for
7423      any member functions.  We don't do this earlier because the
7424      default arguments may reference members of the class.  */
7425   if (!PRIMARY_TEMPLATE_P (templ))
7426     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7427       if (TREE_CODE (t) == FUNCTION_DECL
7428           /* Implicitly generated member functions will not have template
7429              information; they are not instantiations, but instead are
7430              created "fresh" for each instantiation.  */
7431           && DECL_TEMPLATE_INFO (t))
7432         tsubst_default_arguments (t);
7433
7434   /* Some typedefs referenced from within the template code need to be access
7435      checked at template instantiation time, i.e now. These types were
7436      added to the template at parsing time. Let's get those and perform
7437      the access checks then.  */
7438   perform_typedefs_access_check (pattern, args);
7439   perform_deferred_access_checks ();
7440   pop_nested_class ();
7441   pop_from_top_level ();
7442   pop_deferring_access_checks ();
7443   pop_tinst_level ();
7444
7445   /* The vtable for a template class can be emitted in any translation
7446      unit in which the class is instantiated.  When there is no key
7447      method, however, finish_struct_1 will already have added TYPE to
7448      the keyed_classes list.  */
7449   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7450     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7451
7452   return type;
7453 }
7454
7455 static tree
7456 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7457 {
7458   tree r;
7459
7460   if (!t)
7461     r = t;
7462   else if (TYPE_P (t))
7463     r = tsubst (t, args, complain, in_decl);
7464   else
7465     {
7466       r = tsubst_expr (t, args, complain, in_decl,
7467                        /*integral_constant_expression_p=*/true);
7468       r = fold_non_dependent_expr (r);
7469     }
7470   return r;
7471 }
7472
7473 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7474    NONTYPE_ARGUMENT_PACK.  */
7475
7476 static tree
7477 make_fnparm_pack (tree spec_parm)
7478 {
7479   /* Collect all of the extra "packed" parameters into an
7480      argument pack.  */
7481   tree parmvec;
7482   tree parmtypevec;
7483   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7484   tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
7485   int i, len = list_length (spec_parm);
7486
7487   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7488   parmvec = make_tree_vec (len);
7489   parmtypevec = make_tree_vec (len);
7490   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7491     {
7492       TREE_VEC_ELT (parmvec, i) = spec_parm;
7493       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7494     }
7495
7496   /* Build the argument packs.  */
7497   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7498   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7499   TREE_TYPE (argpack) = argtypepack;
7500
7501   return argpack;
7502 }        
7503
7504 /* Substitute ARGS into T, which is an pack expansion
7505    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7506    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7507    (if only a partial substitution could be performed) or
7508    ERROR_MARK_NODE if there was an error.  */
7509 tree
7510 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7511                        tree in_decl)
7512 {
7513   tree pattern;
7514   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7515   tree first_arg_pack; int i, len = -1;
7516   tree result;
7517   int incomplete = 0;
7518   bool very_local_specializations = false;
7519
7520   gcc_assert (PACK_EXPANSION_P (t));
7521   pattern = PACK_EXPANSION_PATTERN (t);
7522
7523   /* Determine the argument packs that will instantiate the parameter
7524      packs used in the expansion expression. While we're at it,
7525      compute the number of arguments to be expanded and make sure it
7526      is consistent.  */
7527   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7528        pack = TREE_CHAIN (pack))
7529     {
7530       tree parm_pack = TREE_VALUE (pack);
7531       tree arg_pack = NULL_TREE;
7532       tree orig_arg = NULL_TREE;
7533
7534       if (TREE_CODE (parm_pack) == PARM_DECL)
7535         {
7536           arg_pack = retrieve_local_specialization (parm_pack);
7537           if (arg_pack == NULL_TREE)
7538             {
7539               /* This can happen for a parameter name used later in a function
7540                  declaration (such as in a late-specified return type).  Just
7541                  make a dummy decl, since it's only used for its type.  */
7542               gcc_assert (cp_unevaluated_operand != 0);
7543               arg_pack = tsubst_decl (parm_pack, args, complain);
7544               arg_pack = make_fnparm_pack (arg_pack);
7545             }
7546         }
7547       else
7548         {
7549           int level, idx, levels;
7550           template_parm_level_and_index (parm_pack, &level, &idx);
7551
7552           levels = TMPL_ARGS_DEPTH (args);
7553           if (level <= levels)
7554             arg_pack = TMPL_ARG (args, level, idx);
7555         }
7556
7557       orig_arg = arg_pack;
7558       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7559         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7560       
7561       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7562         /* This can only happen if we forget to expand an argument
7563            pack somewhere else. Just return an error, silently.  */
7564         {
7565           result = make_tree_vec (1);
7566           TREE_VEC_ELT (result, 0) = error_mark_node;
7567           return result;
7568         }
7569
7570       if (arg_pack
7571           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7572           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7573         {
7574           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7575           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7576           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7577               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7578             /* The argument pack that the parameter maps to is just an
7579                expansion of the parameter itself, such as one would
7580                find in the implicit typedef of a class inside the
7581                class itself.  Consider this parameter "unsubstituted",
7582                so that we will maintain the outer pack expansion.  */
7583             arg_pack = NULL_TREE;
7584         }
7585           
7586       if (arg_pack)
7587         {
7588           int my_len = 
7589             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7590
7591           /* It's all-or-nothing with incomplete argument packs.  */
7592           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7593             return error_mark_node;
7594           
7595           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7596             incomplete = 1;
7597
7598           if (len < 0)
7599             {
7600               len = my_len;
7601               first_arg_pack = arg_pack;
7602             }
7603           else if (len != my_len)
7604             {
7605               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7606                 error ("mismatched argument pack lengths while expanding "
7607                        "%<%T%>",
7608                        pattern);
7609               else
7610                 error ("mismatched argument pack lengths while expanding "
7611                        "%<%E%>",
7612                        pattern);
7613               return error_mark_node;
7614             }
7615
7616           /* Keep track of the parameter packs and their corresponding
7617              argument packs.  */
7618           packs = tree_cons (parm_pack, arg_pack, packs);
7619           TREE_TYPE (packs) = orig_arg;
7620         }
7621       else
7622         /* We can't substitute for this parameter pack.  */
7623         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7624                                          TREE_VALUE (pack),
7625                                          unsubstituted_packs);
7626     }
7627
7628   /* We cannot expand this expansion expression, because we don't have
7629      all of the argument packs we need. Substitute into the pattern
7630      and return a PACK_EXPANSION_*. The caller will need to deal with
7631      that.  */
7632   if (unsubstituted_packs)
7633     {
7634       tree new_pat;
7635       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7636         new_pat = tsubst_expr (pattern, args, complain, in_decl,
7637                                /*integral_constant_expression_p=*/false);
7638       else
7639         new_pat = tsubst (pattern, args, complain, in_decl);
7640       return make_pack_expansion (new_pat);
7641     }
7642
7643   /* We could not find any argument packs that work.  */
7644   if (len < 0)
7645     return error_mark_node;
7646
7647   if (!local_specializations)
7648     {
7649       /* We're in a late-specified return type, so we don't have a local
7650          specializations table.  Create one for doing this expansion.  */
7651       very_local_specializations = true;
7652       local_specializations = htab_create (37,
7653                                            hash_local_specialization,
7654                                            eq_local_specializations,
7655                                            NULL);
7656     }
7657
7658   /* For each argument in each argument pack, substitute into the
7659      pattern.  */
7660   result = make_tree_vec (len + incomplete);
7661   for (i = 0; i < len + incomplete; ++i)
7662     {
7663       /* For parameter pack, change the substitution of the parameter
7664          pack to the ith argument in its argument pack, then expand
7665          the pattern.  */
7666       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7667         {
7668           tree parm = TREE_PURPOSE (pack);
7669
7670           if (TREE_CODE (parm) == PARM_DECL)
7671             {
7672               /* Select the Ith argument from the pack.  */
7673               tree arg = make_node (ARGUMENT_PACK_SELECT);
7674               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7675               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7676               mark_used (parm);
7677               register_local_specialization (arg, parm);
7678             }
7679           else
7680             {
7681               tree value = parm;
7682               int idx, level;
7683               template_parm_level_and_index (parm, &level, &idx);
7684               
7685               if (i < len) 
7686                 {
7687                   /* Select the Ith argument from the pack. */
7688                   value = make_node (ARGUMENT_PACK_SELECT);
7689                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7690                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7691                 }
7692
7693               /* Update the corresponding argument.  */
7694               TMPL_ARG (args, level, idx) = value;
7695             }
7696         }
7697
7698       /* Substitute into the PATTERN with the altered arguments.  */
7699       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7700         TREE_VEC_ELT (result, i) = 
7701           tsubst_expr (pattern, args, complain, in_decl,
7702                        /*integral_constant_expression_p=*/false);
7703       else
7704         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7705
7706       if (i == len)
7707         /* When we have incomplete argument packs, the last "expanded"
7708            result is itself a pack expansion, which allows us
7709            to deduce more arguments.  */
7710         TREE_VEC_ELT (result, i) = 
7711           make_pack_expansion (TREE_VEC_ELT (result, i));
7712
7713       if (TREE_VEC_ELT (result, i) == error_mark_node)
7714         {
7715           result = error_mark_node;
7716           break;
7717         }
7718     }
7719
7720   /* Update ARGS to restore the substitution from parameter packs to
7721      their argument packs.  */
7722   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7723     {
7724       tree parm = TREE_PURPOSE (pack);
7725
7726       if (TREE_CODE (parm) == PARM_DECL)
7727         register_local_specialization (TREE_TYPE (pack), parm);
7728       else
7729         {
7730           int idx, level;
7731           template_parm_level_and_index (parm, &level, &idx);
7732           
7733           /* Update the corresponding argument.  */
7734           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7735             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7736               TREE_TYPE (pack);
7737           else
7738             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7739         }
7740     }
7741
7742   if (very_local_specializations)
7743     {
7744       htab_delete (local_specializations);
7745       local_specializations = NULL;
7746     }
7747   
7748   return result;
7749 }
7750
7751 /* Substitute ARGS into the vector or list of template arguments T.  */
7752
7753 static tree
7754 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7755 {
7756   tree orig_t = t;
7757   int len = TREE_VEC_LENGTH (t);
7758   int need_new = 0, i, expanded_len_adjust = 0, out;
7759   tree *elts = (tree *) alloca (len * sizeof (tree));
7760
7761   for (i = 0; i < len; i++)
7762     {
7763       tree orig_arg = TREE_VEC_ELT (t, i);
7764       tree new_arg;
7765
7766       if (TREE_CODE (orig_arg) == TREE_VEC)
7767         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7768       else if (PACK_EXPANSION_P (orig_arg))
7769         {
7770           /* Substitute into an expansion expression.  */
7771           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7772
7773           if (TREE_CODE (new_arg) == TREE_VEC)
7774             /* Add to the expanded length adjustment the number of
7775                expanded arguments. We subtract one from this
7776                measurement, because the argument pack expression
7777                itself is already counted as 1 in
7778                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7779                the argument pack is empty.  */
7780             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7781         }
7782       else if (ARGUMENT_PACK_P (orig_arg))
7783         {
7784           /* Substitute into each of the arguments.  */
7785           new_arg = make_node (TREE_CODE (orig_arg));
7786           
7787           SET_ARGUMENT_PACK_ARGS (
7788             new_arg,
7789             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7790                                   args, complain, in_decl));
7791
7792           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7793             new_arg = error_mark_node;
7794
7795           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7796             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7797                                           complain, in_decl);
7798             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7799
7800             if (TREE_TYPE (new_arg) == error_mark_node)
7801               new_arg = error_mark_node;
7802           }
7803         }
7804       else
7805         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7806
7807       if (new_arg == error_mark_node)
7808         return error_mark_node;
7809
7810       elts[i] = new_arg;
7811       if (new_arg != orig_arg)
7812         need_new = 1;
7813     }
7814
7815   if (!need_new)
7816     return t;
7817
7818   /* Make space for the expanded arguments coming from template
7819      argument packs.  */
7820   t = make_tree_vec (len + expanded_len_adjust);
7821   for (i = 0, out = 0; i < len; i++)
7822     {
7823       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7824            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7825           && TREE_CODE (elts[i]) == TREE_VEC)
7826         {
7827           int idx;
7828
7829           /* Now expand the template argument pack "in place".  */
7830           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7831             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7832         }
7833       else
7834         {
7835           TREE_VEC_ELT (t, out) = elts[i];
7836           out++;
7837         }
7838     }
7839
7840   return t;
7841 }
7842
7843 /* Return the result of substituting ARGS into the template parameters
7844    given by PARMS.  If there are m levels of ARGS and m + n levels of
7845    PARMS, then the result will contain n levels of PARMS.  For
7846    example, if PARMS is `template <class T> template <class U>
7847    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7848    result will be `template <int*, double, class V>'.  */
7849
7850 static tree
7851 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7852 {
7853   tree r = NULL_TREE;
7854   tree* new_parms;
7855
7856   /* When substituting into a template, we must set
7857      PROCESSING_TEMPLATE_DECL as the template parameters may be
7858      dependent if they are based on one-another, and the dependency
7859      predicates are short-circuit outside of templates.  */
7860   ++processing_template_decl;
7861
7862   for (new_parms = &r;
7863        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7864        new_parms = &(TREE_CHAIN (*new_parms)),
7865          parms = TREE_CHAIN (parms))
7866     {
7867       tree new_vec =
7868         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7869       int i;
7870
7871       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7872         {
7873           tree tuple;
7874           tree default_value;
7875           tree parm_decl;
7876
7877           if (parms == error_mark_node)
7878             continue;
7879
7880           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7881
7882           if (tuple == error_mark_node)
7883             continue;
7884
7885           default_value = TREE_PURPOSE (tuple);
7886           parm_decl = TREE_VALUE (tuple);
7887
7888           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7889           if (TREE_CODE (parm_decl) == PARM_DECL
7890               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7891             parm_decl = error_mark_node;
7892           default_value = tsubst_template_arg (default_value, args,
7893                                                complain, NULL_TREE);
7894
7895           tuple = build_tree_list (default_value, parm_decl);
7896           TREE_VEC_ELT (new_vec, i) = tuple;
7897         }
7898
7899       *new_parms =
7900         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7901                              - TMPL_ARGS_DEPTH (args)),
7902                    new_vec, NULL_TREE);
7903     }
7904
7905   --processing_template_decl;
7906
7907   return r;
7908 }
7909
7910 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7911    type T.  If T is not an aggregate or enumeration type, it is
7912    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7913    ENTERING_SCOPE is nonzero, T is the context for a template which
7914    we are presently tsubst'ing.  Return the substituted value.  */
7915
7916 static tree
7917 tsubst_aggr_type (tree t,
7918                   tree args,
7919                   tsubst_flags_t complain,
7920                   tree in_decl,
7921                   int entering_scope)
7922 {
7923   if (t == NULL_TREE)
7924     return NULL_TREE;
7925
7926   switch (TREE_CODE (t))
7927     {
7928     case RECORD_TYPE:
7929       if (TYPE_PTRMEMFUNC_P (t))
7930         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7931
7932       /* Else fall through.  */
7933     case ENUMERAL_TYPE:
7934     case UNION_TYPE:
7935       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
7936         {
7937           tree argvec;
7938           tree context;
7939           tree r;
7940           int saved_unevaluated_operand;
7941           int saved_inhibit_evaluation_warnings;
7942
7943           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7944           saved_unevaluated_operand = cp_unevaluated_operand;
7945           cp_unevaluated_operand = 0;
7946           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
7947           c_inhibit_evaluation_warnings = 0;
7948
7949           /* First, determine the context for the type we are looking
7950              up.  */
7951           context = TYPE_CONTEXT (t);
7952           if (context)
7953             {
7954               context = tsubst_aggr_type (context, args, complain,
7955                                           in_decl, /*entering_scope=*/1);
7956               /* If context is a nested class inside a class template,
7957                  it may still need to be instantiated (c++/33959).  */
7958               if (TYPE_P (context))
7959                 context = complete_type (context);
7960             }
7961
7962           /* Then, figure out what arguments are appropriate for the
7963              type we are trying to find.  For example, given:
7964
7965                template <class T> struct S;
7966                template <class T, class U> void f(T, U) { S<U> su; }
7967
7968              and supposing that we are instantiating f<int, double>,
7969              then our ARGS will be {int, double}, but, when looking up
7970              S we only want {double}.  */
7971           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7972                                          complain, in_decl);
7973           if (argvec == error_mark_node)
7974             r = error_mark_node;
7975           else
7976             {
7977               r = lookup_template_class (t, argvec, in_decl, context,
7978                                          entering_scope, complain);
7979               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7980             }
7981
7982           cp_unevaluated_operand = saved_unevaluated_operand;
7983           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
7984
7985           return r;
7986         }
7987       else
7988         /* This is not a template type, so there's nothing to do.  */
7989         return t;
7990
7991     default:
7992       return tsubst (t, args, complain, in_decl);
7993     }
7994 }
7995
7996 /* Substitute into the default argument ARG (a default argument for
7997    FN), which has the indicated TYPE.  */
7998
7999 tree
8000 tsubst_default_argument (tree fn, tree type, tree arg)
8001 {
8002   tree saved_class_ptr = NULL_TREE;
8003   tree saved_class_ref = NULL_TREE;
8004
8005   /* This default argument came from a template.  Instantiate the
8006      default argument here, not in tsubst.  In the case of
8007      something like:
8008
8009        template <class T>
8010        struct S {
8011          static T t();
8012          void f(T = t());
8013        };
8014
8015      we must be careful to do name lookup in the scope of S<T>,
8016      rather than in the current class.  */
8017   push_access_scope (fn);
8018   /* The "this" pointer is not valid in a default argument.  */
8019   if (cfun)
8020     {
8021       saved_class_ptr = current_class_ptr;
8022       cp_function_chain->x_current_class_ptr = NULL_TREE;
8023       saved_class_ref = current_class_ref;
8024       cp_function_chain->x_current_class_ref = NULL_TREE;
8025     }
8026
8027   push_deferring_access_checks(dk_no_deferred);
8028   /* The default argument expression may cause implicitly defined
8029      member functions to be synthesized, which will result in garbage
8030      collection.  We must treat this situation as if we were within
8031      the body of function so as to avoid collecting live data on the
8032      stack.  */
8033   ++function_depth;
8034   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8035                      tf_warning_or_error, NULL_TREE,
8036                      /*integral_constant_expression_p=*/false);
8037   --function_depth;
8038   pop_deferring_access_checks();
8039
8040   /* Restore the "this" pointer.  */
8041   if (cfun)
8042     {
8043       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8044       cp_function_chain->x_current_class_ref = saved_class_ref;
8045     }
8046
8047   pop_access_scope (fn);
8048
8049   /* Make sure the default argument is reasonable.  */
8050   arg = check_default_argument (type, arg);
8051
8052   return arg;
8053 }
8054
8055 /* Substitute into all the default arguments for FN.  */
8056
8057 static void
8058 tsubst_default_arguments (tree fn)
8059 {
8060   tree arg;
8061   tree tmpl_args;
8062
8063   tmpl_args = DECL_TI_ARGS (fn);
8064
8065   /* If this function is not yet instantiated, we certainly don't need
8066      its default arguments.  */
8067   if (uses_template_parms (tmpl_args))
8068     return;
8069
8070   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8071        arg;
8072        arg = TREE_CHAIN (arg))
8073     if (TREE_PURPOSE (arg))
8074       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8075                                                     TREE_VALUE (arg),
8076                                                     TREE_PURPOSE (arg));
8077 }
8078
8079 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8080    result of the substitution.  Issue error and warning messages under
8081    control of COMPLAIN.  */
8082
8083 static tree
8084 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8085 {
8086   location_t saved_loc;
8087   tree r = NULL_TREE;
8088   tree in_decl = t;
8089
8090   /* Set the filename and linenumber to improve error-reporting.  */
8091   saved_loc = input_location;
8092   input_location = DECL_SOURCE_LOCATION (t);
8093
8094   switch (TREE_CODE (t))
8095     {
8096     case TEMPLATE_DECL:
8097       {
8098         /* We can get here when processing a member function template,
8099            member class template, and template template parameter of
8100            a template class.  */
8101         tree decl = DECL_TEMPLATE_RESULT (t);
8102         tree spec;
8103         tree tmpl_args;
8104         tree full_args;
8105
8106         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8107           {
8108             /* Template template parameter is treated here.  */
8109             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8110             if (new_type == error_mark_node)
8111               return error_mark_node;
8112
8113             r = copy_decl (t);
8114             TREE_CHAIN (r) = NULL_TREE;
8115             TREE_TYPE (r) = new_type;
8116             DECL_TEMPLATE_RESULT (r)
8117               = build_decl (DECL_SOURCE_LOCATION (decl),
8118                             TYPE_DECL, DECL_NAME (decl), new_type);
8119             DECL_TEMPLATE_PARMS (r)
8120               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8121                                        complain);
8122             TYPE_NAME (new_type) = r;
8123             break;
8124           }
8125
8126         /* We might already have an instance of this template.
8127            The ARGS are for the surrounding class type, so the
8128            full args contain the tsubst'd args for the context,
8129            plus the innermost args from the template decl.  */
8130         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8131           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8132           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8133         /* Because this is a template, the arguments will still be
8134            dependent, even after substitution.  If
8135            PROCESSING_TEMPLATE_DECL is not set, the dependency
8136            predicates will short-circuit.  */
8137         ++processing_template_decl;
8138         full_args = tsubst_template_args (tmpl_args, args,
8139                                           complain, in_decl);
8140         --processing_template_decl;
8141         if (full_args == error_mark_node)
8142           return error_mark_node;
8143
8144         /* tsubst_template_args doesn't copy the vector if
8145            nothing changed.  But, *something* should have
8146            changed.  */
8147         gcc_assert (full_args != tmpl_args);
8148
8149         spec = retrieve_specialization (t, full_args,
8150                                         /*class_specializations_p=*/true);
8151         if (spec != NULL_TREE)
8152           {
8153             r = spec;
8154             break;
8155           }
8156
8157         /* Make a new template decl.  It will be similar to the
8158            original, but will record the current template arguments.
8159            We also create a new function declaration, which is just
8160            like the old one, but points to this new template, rather
8161            than the old one.  */
8162         r = copy_decl (t);
8163         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8164         TREE_CHAIN (r) = NULL_TREE;
8165
8166         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8167
8168         if (TREE_CODE (decl) == TYPE_DECL)
8169           {
8170             tree new_type;
8171             ++processing_template_decl;
8172             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8173             --processing_template_decl;
8174             if (new_type == error_mark_node)
8175               return error_mark_node;
8176
8177             TREE_TYPE (r) = new_type;
8178             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8179             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8180             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8181             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8182           }
8183         else
8184           {
8185             tree new_decl;
8186             ++processing_template_decl;
8187             new_decl = tsubst (decl, args, complain, in_decl);
8188             --processing_template_decl;
8189             if (new_decl == error_mark_node)
8190               return error_mark_node;
8191
8192             DECL_TEMPLATE_RESULT (r) = new_decl;
8193             DECL_TI_TEMPLATE (new_decl) = r;
8194             TREE_TYPE (r) = TREE_TYPE (new_decl);
8195             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8196             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8197           }
8198
8199         SET_DECL_IMPLICIT_INSTANTIATION (r);
8200         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8201         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8202
8203         /* The template parameters for this new template are all the
8204            template parameters for the old template, except the
8205            outermost level of parameters.  */
8206         DECL_TEMPLATE_PARMS (r)
8207           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8208                                    complain);
8209
8210         if (PRIMARY_TEMPLATE_P (t))
8211           DECL_PRIMARY_TEMPLATE (r) = r;
8212
8213         if (TREE_CODE (decl) != TYPE_DECL)
8214           /* Record this non-type partial instantiation.  */
8215           register_specialization (r, t,
8216                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8217                                    false);
8218       }
8219       break;
8220
8221     case FUNCTION_DECL:
8222       {
8223         tree ctx;
8224         tree argvec = NULL_TREE;
8225         tree *friends;
8226         tree gen_tmpl;
8227         tree type;
8228         int member;
8229         int args_depth;
8230         int parms_depth;
8231
8232         /* Nobody should be tsubst'ing into non-template functions.  */
8233         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8234
8235         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8236           {
8237             tree spec;
8238             bool dependent_p;
8239
8240             /* If T is not dependent, just return it.  We have to
8241                increment PROCESSING_TEMPLATE_DECL because
8242                value_dependent_expression_p assumes that nothing is
8243                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8244             ++processing_template_decl;
8245             dependent_p = value_dependent_expression_p (t);
8246             --processing_template_decl;
8247             if (!dependent_p)
8248               return t;
8249
8250             /* Calculate the most general template of which R is a
8251                specialization, and the complete set of arguments used to
8252                specialize R.  */
8253             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8254             argvec = tsubst_template_args (DECL_TI_ARGS
8255                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8256                                            args, complain, in_decl);
8257
8258             /* Check to see if we already have this specialization.  */
8259             spec = retrieve_specialization (gen_tmpl, argvec,
8260                                             /*class_specializations_p=*/false);
8261
8262             if (spec)
8263               {
8264                 r = spec;
8265                 break;
8266               }
8267
8268             /* We can see more levels of arguments than parameters if
8269                there was a specialization of a member template, like
8270                this:
8271
8272                  template <class T> struct S { template <class U> void f(); }
8273                  template <> template <class U> void S<int>::f(U);
8274
8275                Here, we'll be substituting into the specialization,
8276                because that's where we can find the code we actually
8277                want to generate, but we'll have enough arguments for
8278                the most general template.
8279
8280                We also deal with the peculiar case:
8281
8282                  template <class T> struct S {
8283                    template <class U> friend void f();
8284                  };
8285                  template <class U> void f() {}
8286                  template S<int>;
8287                  template void f<double>();
8288
8289                Here, the ARGS for the instantiation of will be {int,
8290                double}.  But, we only need as many ARGS as there are
8291                levels of template parameters in CODE_PATTERN.  We are
8292                careful not to get fooled into reducing the ARGS in
8293                situations like:
8294
8295                  template <class T> struct S { template <class U> void f(U); }
8296                  template <class T> template <> void S<T>::f(int) {}
8297
8298                which we can spot because the pattern will be a
8299                specialization in this case.  */
8300             args_depth = TMPL_ARGS_DEPTH (args);
8301             parms_depth =
8302               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8303             if (args_depth > parms_depth
8304                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8305               args = get_innermost_template_args (args, parms_depth);
8306           }
8307         else
8308           {
8309             /* This special case arises when we have something like this:
8310
8311                  template <class T> struct S {
8312                    friend void f<int>(int, double);
8313                  };
8314
8315                Here, the DECL_TI_TEMPLATE for the friend declaration
8316                will be an IDENTIFIER_NODE.  We are being called from
8317                tsubst_friend_function, and we want only to create a
8318                new decl (R) with appropriate types so that we can call
8319                determine_specialization.  */
8320             gen_tmpl = NULL_TREE;
8321           }
8322
8323         if (DECL_CLASS_SCOPE_P (t))
8324           {
8325             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8326               member = 2;
8327             else
8328               member = 1;
8329             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8330                                     complain, t, /*entering_scope=*/1);
8331           }
8332         else
8333           {
8334             member = 0;
8335             ctx = DECL_CONTEXT (t);
8336           }
8337         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8338         if (type == error_mark_node)
8339           return error_mark_node;
8340
8341         /* We do NOT check for matching decls pushed separately at this
8342            point, as they may not represent instantiations of this
8343            template, and in any case are considered separate under the
8344            discrete model.  */
8345         r = copy_decl (t);
8346         DECL_USE_TEMPLATE (r) = 0;
8347         TREE_TYPE (r) = type;
8348         /* Clear out the mangled name and RTL for the instantiation.  */
8349         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8350         SET_DECL_RTL (r, NULL_RTX);
8351         /* Leave DECL_INITIAL set on deleted instantiations.  */
8352         if (!DECL_DELETED_FN (r))
8353           DECL_INITIAL (r) = NULL_TREE;
8354         DECL_CONTEXT (r) = ctx;
8355
8356         if (member && DECL_CONV_FN_P (r))
8357           /* Type-conversion operator.  Reconstruct the name, in
8358              case it's the name of one of the template's parameters.  */
8359           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8360
8361         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8362                                      complain, t);
8363         DECL_RESULT (r) = NULL_TREE;
8364
8365         TREE_STATIC (r) = 0;
8366         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8367         DECL_EXTERNAL (r) = 1;
8368         /* If this is an instantiation of a function with internal
8369            linkage, we already know what object file linkage will be
8370            assigned to the instantiation.  */
8371         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8372         DECL_DEFER_OUTPUT (r) = 0;
8373         TREE_CHAIN (r) = NULL_TREE;
8374         DECL_PENDING_INLINE_INFO (r) = 0;
8375         DECL_PENDING_INLINE_P (r) = 0;
8376         DECL_SAVED_TREE (r) = NULL_TREE;
8377         DECL_STRUCT_FUNCTION (r) = NULL;
8378         TREE_USED (r) = 0;
8379         if (DECL_CLONED_FUNCTION (r))
8380           {
8381             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
8382                                                args, complain, t);
8383             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
8384             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
8385           }
8386
8387         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8388            this in the special friend case mentioned above where
8389            GEN_TMPL is NULL.  */
8390         if (gen_tmpl)
8391           {
8392             DECL_TEMPLATE_INFO (r)
8393               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8394             SET_DECL_IMPLICIT_INSTANTIATION (r);
8395             register_specialization (r, gen_tmpl, argvec, false);
8396
8397             /* We're not supposed to instantiate default arguments
8398                until they are called, for a template.  But, for a
8399                declaration like:
8400
8401                  template <class T> void f ()
8402                  { extern void g(int i = T()); }
8403
8404                we should do the substitution when the template is
8405                instantiated.  We handle the member function case in
8406                instantiate_class_template since the default arguments
8407                might refer to other members of the class.  */
8408             if (!member
8409                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8410                 && !uses_template_parms (argvec))
8411               tsubst_default_arguments (r);
8412           }
8413         else
8414           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8415
8416         /* Copy the list of befriending classes.  */
8417         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8418              *friends;
8419              friends = &TREE_CHAIN (*friends))
8420           {
8421             *friends = copy_node (*friends);
8422             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8423                                             args, complain,
8424                                             in_decl);
8425           }
8426
8427         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8428           {
8429             maybe_retrofit_in_chrg (r);
8430             if (DECL_CONSTRUCTOR_P (r))
8431               grok_ctor_properties (ctx, r);
8432             /* If this is an instantiation of a member template, clone it.
8433                If it isn't, that'll be handled by
8434                clone_constructors_and_destructors.  */
8435             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8436               clone_function_decl (r, /*update_method_vec_p=*/0);
8437           }
8438         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8439                  && !grok_op_properties (r, (complain & tf_error) != 0))
8440           return error_mark_node;
8441
8442         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8443           SET_DECL_FRIEND_CONTEXT (r,
8444                                    tsubst (DECL_FRIEND_CONTEXT (t),
8445                                             args, complain, in_decl));
8446
8447         /* Possibly limit visibility based on template args.  */
8448         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8449         if (DECL_VISIBILITY_SPECIFIED (t))
8450           {
8451             DECL_VISIBILITY_SPECIFIED (r) = 0;
8452             DECL_ATTRIBUTES (r)
8453               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8454           }
8455         determine_visibility (r);
8456
8457         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8458                                         args, complain, in_decl);
8459       }
8460       break;
8461
8462     case PARM_DECL:
8463       {
8464         tree type = NULL_TREE;
8465         int i, len = 1;
8466         tree expanded_types = NULL_TREE;
8467         tree prev_r = NULL_TREE;
8468         tree first_r = NULL_TREE;
8469
8470         if (FUNCTION_PARAMETER_PACK_P (t))
8471           {
8472             /* If there is a local specialization that isn't a
8473                parameter pack, it means that we're doing a "simple"
8474                substitution from inside tsubst_pack_expansion. Just
8475                return the local specialization (which will be a single
8476                parm).  */
8477             tree spec = retrieve_local_specialization (t);
8478             if (spec 
8479                 && TREE_CODE (spec) == PARM_DECL
8480                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8481               return spec;
8482
8483             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8484                the parameters in this function parameter pack.  */
8485             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8486                                                     complain, in_decl);
8487             if (TREE_CODE (expanded_types) == TREE_VEC)
8488               {
8489                 len = TREE_VEC_LENGTH (expanded_types);
8490
8491                 /* Zero-length parameter packs are boring. Just substitute
8492                    into the chain.  */
8493                 if (len == 0)
8494                   return tsubst (TREE_CHAIN (t), args, complain, 
8495                                  TREE_CHAIN (t));
8496               }
8497             else
8498               {
8499                 /* All we did was update the type. Make a note of that.  */
8500                 type = expanded_types;
8501                 expanded_types = NULL_TREE;
8502               }
8503           }
8504
8505         /* Loop through all of the parameter's we'll build. When T is
8506            a function parameter pack, LEN is the number of expanded
8507            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8508         r = NULL_TREE;
8509         for (i = 0; i < len; ++i)
8510           {
8511             prev_r = r;
8512             r = copy_node (t);
8513             if (DECL_TEMPLATE_PARM_P (t))
8514               SET_DECL_TEMPLATE_PARM_P (r);
8515
8516             if (expanded_types)
8517               /* We're on the Ith parameter of the function parameter
8518                  pack.  */
8519               {
8520                 /* Get the Ith type.  */
8521                 type = TREE_VEC_ELT (expanded_types, i);
8522
8523                 if (DECL_NAME (r))
8524                   /* Rename the parameter to include the index.  */
8525                   DECL_NAME (r) =
8526                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8527               }
8528             else if (!type)
8529               /* We're dealing with a normal parameter.  */
8530               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8531
8532             type = type_decays_to (type);
8533             TREE_TYPE (r) = type;
8534             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8535
8536             if (DECL_INITIAL (r))
8537               {
8538                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8539                   DECL_INITIAL (r) = TREE_TYPE (r);
8540                 else
8541                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8542                                              complain, in_decl);
8543               }
8544
8545             DECL_CONTEXT (r) = NULL_TREE;
8546
8547             if (!DECL_TEMPLATE_PARM_P (r))
8548               DECL_ARG_TYPE (r) = type_passed_as (type);
8549
8550             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8551                                             args, complain, in_decl);
8552
8553             /* Keep track of the first new parameter we
8554                generate. That's what will be returned to the
8555                caller.  */
8556             if (!first_r)
8557               first_r = r;
8558
8559             /* Build a proper chain of parameters when substituting
8560                into a function parameter pack.  */
8561             if (prev_r)
8562               TREE_CHAIN (prev_r) = r;
8563           }
8564
8565         if (TREE_CHAIN (t))
8566           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8567                                    complain, TREE_CHAIN (t));
8568
8569         /* FIRST_R contains the start of the chain we've built.  */
8570         r = first_r;
8571       }
8572       break;
8573
8574     case FIELD_DECL:
8575       {
8576         tree type;
8577
8578         r = copy_decl (t);
8579         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8580         if (type == error_mark_node)
8581           return error_mark_node;
8582         TREE_TYPE (r) = type;
8583         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8584
8585         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8586         DECL_INITIAL (r)
8587           = tsubst_expr (DECL_INITIAL (t), args,
8588                          complain, in_decl,
8589                          /*integral_constant_expression_p=*/true);
8590         /* We don't have to set DECL_CONTEXT here; it is set by
8591            finish_member_declaration.  */
8592         TREE_CHAIN (r) = NULL_TREE;
8593         if (VOID_TYPE_P (type))
8594           error ("instantiation of %q+D as type %qT", r, type);
8595
8596         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8597                                         args, complain, in_decl);
8598       }
8599       break;
8600
8601     case USING_DECL:
8602       /* We reach here only for member using decls.  */
8603       if (DECL_DEPENDENT_P (t))
8604         {
8605           r = do_class_using_decl
8606             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8607              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8608           if (!r)
8609             r = error_mark_node;
8610           else
8611             {
8612               TREE_PROTECTED (r) = TREE_PROTECTED (t);
8613               TREE_PRIVATE (r) = TREE_PRIVATE (t);
8614             }
8615         }
8616       else
8617         {
8618           r = copy_node (t);
8619           TREE_CHAIN (r) = NULL_TREE;
8620         }
8621       break;
8622
8623     case TYPE_DECL:
8624     case VAR_DECL:
8625       {
8626         tree argvec = NULL_TREE;
8627         tree gen_tmpl = NULL_TREE;
8628         tree spec;
8629         tree tmpl = NULL_TREE;
8630         tree ctx;
8631         tree type = NULL_TREE;
8632         bool local_p;
8633
8634         if (TREE_CODE (t) == TYPE_DECL
8635             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8636           {
8637             /* If this is the canonical decl, we don't have to
8638                mess with instantiations, and often we can't (for
8639                typename, template type parms and such).  Note that
8640                TYPE_NAME is not correct for the above test if
8641                we've copied the type for a typedef.  */
8642             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8643             if (type == error_mark_node)
8644               return error_mark_node;
8645             r = TYPE_NAME (type);
8646             break;
8647           }
8648
8649         /* Check to see if we already have the specialization we
8650            need.  */
8651         spec = NULL_TREE;
8652         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8653           {
8654             /* T is a static data member or namespace-scope entity.
8655                We have to substitute into namespace-scope variables
8656                (even though such entities are never templates) because
8657                of cases like:
8658                
8659                  template <class T> void f() { extern T t; }
8660
8661                where the entity referenced is not known until
8662                instantiation time.  */
8663             local_p = false;
8664             ctx = DECL_CONTEXT (t);
8665             if (DECL_CLASS_SCOPE_P (t))
8666               {
8667                 ctx = tsubst_aggr_type (ctx, args,
8668                                         complain,
8669                                         in_decl, /*entering_scope=*/1);
8670                 /* If CTX is unchanged, then T is in fact the
8671                    specialization we want.  That situation occurs when
8672                    referencing a static data member within in its own
8673                    class.  We can use pointer equality, rather than
8674                    same_type_p, because DECL_CONTEXT is always
8675                    canonical.  */
8676                 if (ctx == DECL_CONTEXT (t))
8677                   spec = t;
8678               }
8679
8680             if (!spec)
8681               {
8682                 tmpl = DECL_TI_TEMPLATE (t);
8683                 gen_tmpl = most_general_template (tmpl);
8684                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8685                 spec = (retrieve_specialization 
8686                         (gen_tmpl, argvec,
8687                          /*class_specializations_p=*/false));
8688               }
8689           }
8690         else
8691           {
8692             /* A local variable.  */
8693             local_p = true;
8694             /* Subsequent calls to pushdecl will fill this in.  */
8695             ctx = NULL_TREE;
8696             spec = retrieve_local_specialization (t);
8697           }
8698         /* If we already have the specialization we need, there is
8699            nothing more to do.  */ 
8700         if (spec)
8701           {
8702             r = spec;
8703             break;
8704           }
8705
8706         /* Create a new node for the specialization we need.  */
8707         r = copy_decl (t);
8708         if (type == NULL_TREE)
8709           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8710         if (TREE_CODE (r) == VAR_DECL)
8711           {
8712             /* Even if the original location is out of scope, the
8713                newly substituted one is not.  */
8714             DECL_DEAD_FOR_LOCAL (r) = 0;
8715             DECL_INITIALIZED_P (r) = 0;
8716             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8717             if (type == error_mark_node)
8718               return error_mark_node;
8719             if (TREE_CODE (type) == FUNCTION_TYPE)
8720               {
8721                 /* It may seem that this case cannot occur, since:
8722
8723                      typedef void f();
8724                      void g() { f x; }
8725
8726                    declares a function, not a variable.  However:
8727       
8728                      typedef void f();
8729                      template <typename T> void g() { T t; }
8730                      template void g<f>();
8731
8732                    is an attempt to declare a variable with function
8733                    type.  */
8734                 error ("variable %qD has function type",
8735                        /* R is not yet sufficiently initialized, so we
8736                           just use its name.  */
8737                        DECL_NAME (r));
8738                 return error_mark_node;
8739               }
8740             type = complete_type (type);
8741             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8742               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8743             type = check_var_type (DECL_NAME (r), type);
8744
8745             if (DECL_HAS_VALUE_EXPR_P (t))
8746               {
8747                 tree ve = DECL_VALUE_EXPR (t);
8748                 ve = tsubst_expr (ve, args, complain, in_decl,
8749                                   /*constant_expression_p=*/false);
8750                 SET_DECL_VALUE_EXPR (r, ve);
8751               }
8752           }
8753         else if (DECL_SELF_REFERENCE_P (t))
8754           SET_DECL_SELF_REFERENCE_P (r);
8755         TREE_TYPE (r) = type;
8756         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8757         DECL_CONTEXT (r) = ctx;
8758         /* Clear out the mangled name and RTL for the instantiation.  */
8759         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8760         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8761           SET_DECL_RTL (r, NULL_RTX);
8762         /* The initializer must not be expanded until it is required;
8763            see [temp.inst].  */
8764         DECL_INITIAL (r) = NULL_TREE;
8765         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8766           SET_DECL_RTL (r, NULL_RTX);
8767         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8768         if (TREE_CODE (r) == VAR_DECL)
8769           {
8770             /* Possibly limit visibility based on template args.  */
8771             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8772             if (DECL_VISIBILITY_SPECIFIED (t))
8773               {
8774                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8775                 DECL_ATTRIBUTES (r)
8776                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8777               }
8778             determine_visibility (r);
8779           }
8780         /* Preserve a typedef that names a type.  */
8781         else if (TREE_CODE (r) == TYPE_DECL
8782                  && DECL_ORIGINAL_TYPE (t)
8783                  && type != error_mark_node)
8784           {
8785             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8786                                              args, complain, in_decl);
8787             TREE_TYPE (r) = type = build_variant_type_copy (type);
8788             TYPE_NAME (type) = r;
8789           }
8790
8791         if (!local_p)
8792           {
8793             /* A static data member declaration is always marked
8794                external when it is declared in-class, even if an
8795                initializer is present.  We mimic the non-template
8796                processing here.  */
8797             DECL_EXTERNAL (r) = 1;
8798
8799             register_specialization (r, gen_tmpl, argvec, false);
8800             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8801             SET_DECL_IMPLICIT_INSTANTIATION (r);
8802           }
8803         else
8804           register_local_specialization (r, t);
8805
8806         TREE_CHAIN (r) = NULL_TREE;
8807
8808         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
8809                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
8810                                         args, complain, in_decl);
8811         layout_decl (r, 0);
8812       }
8813       break;
8814
8815     default:
8816       gcc_unreachable ();
8817     }
8818
8819   /* Restore the file and line information.  */
8820   input_location = saved_loc;
8821
8822   return r;
8823 }
8824
8825 /* Substitute into the ARG_TYPES of a function type.  */
8826
8827 static tree
8828 tsubst_arg_types (tree arg_types,
8829                   tree args,
8830                   tsubst_flags_t complain,
8831                   tree in_decl)
8832 {
8833   tree remaining_arg_types;
8834   tree type = NULL_TREE;
8835   int i = 1;
8836   tree expanded_args = NULL_TREE;
8837   tree default_arg;
8838
8839   if (!arg_types || arg_types == void_list_node)
8840     return arg_types;
8841
8842   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8843                                           args, complain, in_decl);
8844   if (remaining_arg_types == error_mark_node)
8845     return error_mark_node;
8846
8847   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8848     {
8849       /* For a pack expansion, perform substitution on the
8850          entire expression. Later on, we'll handle the arguments
8851          one-by-one.  */
8852       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8853                                             args, complain, in_decl);
8854
8855       if (TREE_CODE (expanded_args) == TREE_VEC)
8856         /* So that we'll spin through the parameters, one by one.  */
8857         i = TREE_VEC_LENGTH (expanded_args);
8858       else
8859         {
8860           /* We only partially substituted into the parameter
8861              pack. Our type is TYPE_PACK_EXPANSION.  */
8862           type = expanded_args;
8863           expanded_args = NULL_TREE;
8864         }
8865     }
8866
8867   while (i > 0) {
8868     --i;
8869     
8870     if (expanded_args)
8871       type = TREE_VEC_ELT (expanded_args, i);
8872     else if (!type)
8873       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8874
8875     if (type == error_mark_node)
8876       return error_mark_node;
8877     if (VOID_TYPE_P (type))
8878       {
8879         if (complain & tf_error)
8880           {
8881             error ("invalid parameter type %qT", type);
8882             if (in_decl)
8883               error ("in declaration %q+D", in_decl);
8884           }
8885         return error_mark_node;
8886     }
8887     
8888     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8889        top-level qualifiers as required.  */
8890     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8891
8892     /* We do not substitute into default arguments here.  The standard
8893        mandates that they be instantiated only when needed, which is
8894        done in build_over_call.  */
8895     default_arg = TREE_PURPOSE (arg_types);
8896
8897     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8898       {
8899         /* We've instantiated a template before its default arguments
8900            have been parsed.  This can happen for a nested template
8901            class, and is not an error unless we require the default
8902            argument in a call of this function.  */
8903         remaining_arg_types = 
8904           tree_cons (default_arg, type, remaining_arg_types);
8905         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8906                        remaining_arg_types);
8907       }
8908     else
8909       remaining_arg_types = 
8910         hash_tree_cons (default_arg, type, remaining_arg_types);
8911   }
8912         
8913   return remaining_arg_types;
8914 }
8915
8916 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8917    *not* handle the exception-specification for FNTYPE, because the
8918    initial substitution of explicitly provided template parameters
8919    during argument deduction forbids substitution into the
8920    exception-specification:
8921
8922      [temp.deduct]
8923
8924      All references in the function type of the function template to  the
8925      corresponding template parameters are replaced by the specified tem-
8926      plate argument values.  If a substitution in a template parameter or
8927      in  the function type of the function template results in an invalid
8928      type, type deduction fails.  [Note: The equivalent  substitution  in
8929      exception specifications is done only when the function is instanti-
8930      ated, at which point a program is  ill-formed  if  the  substitution
8931      results in an invalid type.]  */
8932
8933 static tree
8934 tsubst_function_type (tree t,
8935                       tree args,
8936                       tsubst_flags_t complain,
8937                       tree in_decl)
8938 {
8939   tree return_type;
8940   tree arg_types;
8941   tree fntype;
8942
8943   /* The TYPE_CONTEXT is not used for function/method types.  */
8944   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8945
8946   /* Substitute the return type.  */
8947   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8948   if (return_type == error_mark_node)
8949     return error_mark_node;
8950   /* The standard does not presently indicate that creation of a
8951      function type with an invalid return type is a deduction failure.
8952      However, that is clearly analogous to creating an array of "void"
8953      or a reference to a reference.  This is core issue #486.  */
8954   if (TREE_CODE (return_type) == ARRAY_TYPE
8955       || TREE_CODE (return_type) == FUNCTION_TYPE)
8956     {
8957       if (complain & tf_error)
8958         {
8959           if (TREE_CODE (return_type) == ARRAY_TYPE)
8960             error ("function returning an array");
8961           else
8962             error ("function returning a function");
8963         }
8964       return error_mark_node;
8965     }
8966
8967   /* Substitute the argument types.  */
8968   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8969                                 complain, in_decl);
8970   if (arg_types == error_mark_node)
8971     return error_mark_node;
8972
8973   /* Construct a new type node and return it.  */
8974   if (TREE_CODE (t) == FUNCTION_TYPE)
8975     fntype = build_function_type (return_type, arg_types);
8976   else
8977     {
8978       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8979       if (! MAYBE_CLASS_TYPE_P (r))
8980         {
8981           /* [temp.deduct]
8982
8983              Type deduction may fail for any of the following
8984              reasons:
8985
8986              -- Attempting to create "pointer to member of T" when T
8987              is not a class type.  */
8988           if (complain & tf_error)
8989             error ("creating pointer to member function of non-class type %qT",
8990                       r);
8991           return error_mark_node;
8992         }
8993
8994       fntype = build_method_type_directly (r, return_type,
8995                                            TREE_CHAIN (arg_types));
8996     }
8997   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
8998   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
8999
9000   return fntype;
9001 }
9002
9003 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9004    ARGS into that specification, and return the substituted
9005    specification.  If there is no specification, return NULL_TREE.  */
9006
9007 static tree
9008 tsubst_exception_specification (tree fntype,
9009                                 tree args,
9010                                 tsubst_flags_t complain,
9011                                 tree in_decl)
9012 {
9013   tree specs;
9014   tree new_specs;
9015
9016   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9017   new_specs = NULL_TREE;
9018   if (specs)
9019     {
9020       if (! TREE_VALUE (specs))
9021         new_specs = specs;
9022       else
9023         while (specs)
9024           {
9025             tree spec;
9026             int i, len = 1;
9027             tree expanded_specs = NULL_TREE;
9028
9029             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9030               {
9031                 /* Expand the pack expansion type.  */
9032                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9033                                                        args, complain,
9034                                                        in_decl);
9035
9036                 if (expanded_specs == error_mark_node)
9037                   return error_mark_node;
9038                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9039                   len = TREE_VEC_LENGTH (expanded_specs);
9040                 else
9041                   {
9042                     /* We're substituting into a member template, so
9043                        we got a TYPE_PACK_EXPANSION back.  Add that
9044                        expansion and move on.  */
9045                     gcc_assert (TREE_CODE (expanded_specs) 
9046                                 == TYPE_PACK_EXPANSION);
9047                     new_specs = add_exception_specifier (new_specs,
9048                                                          expanded_specs,
9049                                                          complain);
9050                     specs = TREE_CHAIN (specs);
9051                     continue;
9052                   }
9053               }
9054
9055             for (i = 0; i < len; ++i)
9056               {
9057                 if (expanded_specs)
9058                   spec = TREE_VEC_ELT (expanded_specs, i);
9059                 else
9060                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9061                 if (spec == error_mark_node)
9062                   return spec;
9063                 new_specs = add_exception_specifier (new_specs, spec, 
9064                                                      complain);
9065               }
9066
9067             specs = TREE_CHAIN (specs);
9068           }
9069     }
9070   return new_specs;
9071 }
9072
9073 /* Take the tree structure T and replace template parameters used
9074    therein with the argument vector ARGS.  IN_DECL is an associated
9075    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9076    Issue error and warning messages under control of COMPLAIN.  Note
9077    that we must be relatively non-tolerant of extensions here, in
9078    order to preserve conformance; if we allow substitutions that
9079    should not be allowed, we may allow argument deductions that should
9080    not succeed, and therefore report ambiguous overload situations
9081    where there are none.  In theory, we could allow the substitution,
9082    but indicate that it should have failed, and allow our caller to
9083    make sure that the right thing happens, but we don't try to do this
9084    yet.
9085
9086    This function is used for dealing with types, decls and the like;
9087    for expressions, use tsubst_expr or tsubst_copy.  */
9088
9089 tree
9090 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9091 {
9092   tree type, r;
9093
9094   if (t == NULL_TREE || t == error_mark_node
9095       || t == integer_type_node
9096       || t == void_type_node
9097       || t == char_type_node
9098       || t == unknown_type_node
9099       || TREE_CODE (t) == NAMESPACE_DECL)
9100     return t;
9101
9102   if (DECL_P (t))
9103     return tsubst_decl (t, args, complain);
9104
9105   if (args == NULL_TREE)
9106     return t;
9107
9108   if (TREE_CODE (t) == IDENTIFIER_NODE)
9109     type = IDENTIFIER_TYPE_VALUE (t);
9110   else
9111     type = TREE_TYPE (t);
9112
9113   gcc_assert (type != unknown_type_node);
9114
9115   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9116      such as attribute aligned.  */
9117   if (TYPE_P (t)
9118       && TYPE_NAME (t)
9119       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9120     {
9121       tree decl = TYPE_NAME (t);
9122       
9123       if (DECL_CLASS_SCOPE_P (decl)
9124           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9125           && uses_template_parms (DECL_CONTEXT (decl)))
9126         {
9127           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9128           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9129           r = retrieve_specialization (tmpl, gen_args, false);
9130         }
9131       else if (DECL_FUNCTION_SCOPE_P (decl)
9132                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9133                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9134         r = retrieve_local_specialization (decl);
9135       else
9136         /* The typedef is from a non-template context.  */
9137         return t;
9138
9139       if (r)
9140         {
9141           r = TREE_TYPE (r);
9142           r = cp_build_qualified_type_real
9143             (r, cp_type_quals (t) | cp_type_quals (r),
9144              complain | tf_ignore_bad_quals);
9145           return r;
9146         }
9147       /* Else we must be instantiating the typedef, so fall through.  */
9148     }
9149
9150   if (type
9151       && TREE_CODE (t) != TYPENAME_TYPE
9152       && TREE_CODE (t) != IDENTIFIER_NODE
9153       && TREE_CODE (t) != FUNCTION_TYPE
9154       && TREE_CODE (t) != METHOD_TYPE)
9155     type = tsubst (type, args, complain, in_decl);
9156   if (type == error_mark_node)
9157     return error_mark_node;
9158
9159   switch (TREE_CODE (t))
9160     {
9161     case RECORD_TYPE:
9162     case UNION_TYPE:
9163     case ENUMERAL_TYPE:
9164       return tsubst_aggr_type (t, args, complain, in_decl,
9165                                /*entering_scope=*/0);
9166
9167     case ERROR_MARK:
9168     case IDENTIFIER_NODE:
9169     case VOID_TYPE:
9170     case REAL_TYPE:
9171     case COMPLEX_TYPE:
9172     case VECTOR_TYPE:
9173     case BOOLEAN_TYPE:
9174     case INTEGER_CST:
9175     case REAL_CST:
9176     case STRING_CST:
9177       return t;
9178
9179     case INTEGER_TYPE:
9180       if (t == integer_type_node)
9181         return t;
9182
9183       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9184           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9185         return t;
9186
9187       {
9188         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9189
9190         max = tsubst_expr (omax, args, complain, in_decl,
9191                            /*integral_constant_expression_p=*/false);
9192
9193         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9194            needed.  */
9195         if (TREE_CODE (max) == NOP_EXPR
9196             && TREE_SIDE_EFFECTS (omax)
9197             && !TREE_TYPE (max))
9198           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9199
9200         max = fold_decl_constant_value (max);
9201
9202         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9203            with TREE_SIDE_EFFECTS that indicates this is not an integral
9204            constant expression.  */
9205         if (processing_template_decl
9206             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9207           {
9208             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9209             TREE_SIDE_EFFECTS (max) = 1;
9210           }
9211
9212         if (TREE_CODE (max) != INTEGER_CST
9213             && !at_function_scope_p ()
9214             && !TREE_SIDE_EFFECTS (max)
9215             && !value_dependent_expression_p (max))
9216           {
9217             if (complain & tf_error)
9218               error ("array bound is not an integer constant");
9219             return error_mark_node;
9220           }
9221
9222         /* [temp.deduct]
9223
9224            Type deduction may fail for any of the following
9225            reasons:
9226
9227              Attempting to create an array with a size that is
9228              zero or negative.  */
9229         if (integer_zerop (max) && !(complain & tf_error))
9230           /* We must fail if performing argument deduction (as
9231              indicated by the state of complain), so that
9232              another substitution can be found.  */
9233           return error_mark_node;
9234         else if (TREE_CODE (max) == INTEGER_CST
9235                  && INT_CST_LT (max, integer_zero_node))
9236           {
9237             if (complain & tf_error)
9238               error ("creating array with negative size (%qE)", max);
9239
9240             return error_mark_node;
9241           }
9242
9243         return compute_array_index_type (NULL_TREE, max);
9244       }
9245
9246     case TEMPLATE_TYPE_PARM:
9247     case TEMPLATE_TEMPLATE_PARM:
9248     case BOUND_TEMPLATE_TEMPLATE_PARM:
9249     case TEMPLATE_PARM_INDEX:
9250       {
9251         int idx;
9252         int level;
9253         int levels;
9254         tree arg = NULL_TREE;
9255
9256         r = NULL_TREE;
9257
9258         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9259         template_parm_level_and_index (t, &level, &idx); 
9260
9261         levels = TMPL_ARGS_DEPTH (args);
9262         if (level <= levels)
9263           {
9264             arg = TMPL_ARG (args, level, idx);
9265
9266             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9267               /* See through ARGUMENT_PACK_SELECT arguments. */
9268               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9269           }
9270
9271         if (arg == error_mark_node)
9272           return error_mark_node;
9273         else if (arg != NULL_TREE)
9274           {
9275             if (ARGUMENT_PACK_P (arg))
9276               /* If ARG is an argument pack, we don't actually want to
9277                  perform a substitution here, because substitutions
9278                  for argument packs are only done
9279                  element-by-element. We can get to this point when
9280                  substituting the type of a non-type template
9281                  parameter pack, when that type actually contains
9282                  template parameter packs from an outer template, e.g.,
9283
9284                  template<typename... Types> struct A {
9285                    template<Types... Values> struct B { };
9286                  };  */
9287               return t;
9288
9289             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9290               {
9291                 int quals;
9292                 gcc_assert (TYPE_P (arg));
9293
9294                 /* cv-quals from the template are discarded when
9295                    substituting in a function or reference type.  */
9296                 if (TREE_CODE (arg) == FUNCTION_TYPE
9297                     || TREE_CODE (arg) == METHOD_TYPE
9298                     || TREE_CODE (arg) == REFERENCE_TYPE)
9299                   quals = cp_type_quals (arg);
9300                 else
9301                   quals = cp_type_quals (arg) | cp_type_quals (t);
9302                   
9303                 return cp_build_qualified_type_real
9304                   (arg, quals, complain | tf_ignore_bad_quals);
9305               }
9306             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9307               {
9308                 /* We are processing a type constructed from a
9309                    template template parameter.  */
9310                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9311                                       args, complain, in_decl);
9312                 if (argvec == error_mark_node)
9313                   return error_mark_node;
9314
9315                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9316                    are resolving nested-types in the signature of a
9317                    member function templates.  Otherwise ARG is a
9318                    TEMPLATE_DECL and is the real template to be
9319                    instantiated.  */
9320                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9321                   arg = TYPE_NAME (arg);
9322
9323                 r = lookup_template_class (arg,
9324                                            argvec, in_decl,
9325                                            DECL_CONTEXT (arg),
9326                                             /*entering_scope=*/0,
9327                                            complain);
9328                 return cp_build_qualified_type_real
9329                   (r, TYPE_QUALS (t), complain);
9330               }
9331             else
9332               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9333               return arg;
9334           }
9335
9336         if (level == 1)
9337           /* This can happen during the attempted tsubst'ing in
9338              unify.  This means that we don't yet have any information
9339              about the template parameter in question.  */
9340           return t;
9341
9342         /* If we get here, we must have been looking at a parm for a
9343            more deeply nested template.  Make a new version of this
9344            template parameter, but with a lower level.  */
9345         switch (TREE_CODE (t))
9346           {
9347           case TEMPLATE_TYPE_PARM:
9348           case TEMPLATE_TEMPLATE_PARM:
9349           case BOUND_TEMPLATE_TEMPLATE_PARM:
9350             if (cp_type_quals (t))
9351               {
9352                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9353                 r = cp_build_qualified_type_real
9354                   (r, cp_type_quals (t),
9355                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9356                                ? tf_ignore_bad_quals : 0));
9357               }
9358             else
9359               {
9360                 r = copy_type (t);
9361                 TEMPLATE_TYPE_PARM_INDEX (r)
9362                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9363                                                 r, levels, args, complain);
9364                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9365                 TYPE_MAIN_VARIANT (r) = r;
9366                 TYPE_POINTER_TO (r) = NULL_TREE;
9367                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9368
9369                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9370                   /* We have reduced the level of the template
9371                      template parameter, but not the levels of its
9372                      template parameters, so canonical_type_parameter
9373                      will not be able to find the canonical template
9374                      template parameter for this level. Thus, we
9375                      require structural equality checking to compare
9376                      TEMPLATE_TEMPLATE_PARMs. */
9377                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9378                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9379                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9380                 else
9381                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9382
9383                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9384                   {
9385                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9386                                           complain, in_decl);
9387                     if (argvec == error_mark_node)
9388                       return error_mark_node;
9389
9390                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9391                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9392                   }
9393               }
9394             break;
9395
9396           case TEMPLATE_PARM_INDEX:
9397             r = reduce_template_parm_level (t, type, levels, args, complain);
9398             break;
9399
9400           default:
9401             gcc_unreachable ();
9402           }
9403
9404         return r;
9405       }
9406
9407     case TREE_LIST:
9408       {
9409         tree purpose, value, chain;
9410
9411         if (t == void_list_node)
9412           return t;
9413
9414         purpose = TREE_PURPOSE (t);
9415         if (purpose)
9416           {
9417             purpose = tsubst (purpose, args, complain, in_decl);
9418             if (purpose == error_mark_node)
9419               return error_mark_node;
9420           }
9421         value = TREE_VALUE (t);
9422         if (value)
9423           {
9424             value = tsubst (value, args, complain, in_decl);
9425             if (value == error_mark_node)
9426               return error_mark_node;
9427           }
9428         chain = TREE_CHAIN (t);
9429         if (chain && chain != void_type_node)
9430           {
9431             chain = tsubst (chain, args, complain, in_decl);
9432             if (chain == error_mark_node)
9433               return error_mark_node;
9434           }
9435         if (purpose == TREE_PURPOSE (t)
9436             && value == TREE_VALUE (t)
9437             && chain == TREE_CHAIN (t))
9438           return t;
9439         return hash_tree_cons (purpose, value, chain);
9440       }
9441
9442     case TREE_BINFO:
9443       /* We should never be tsubsting a binfo.  */
9444       gcc_unreachable ();
9445
9446     case TREE_VEC:
9447       /* A vector of template arguments.  */
9448       gcc_assert (!type);
9449       return tsubst_template_args (t, args, complain, in_decl);
9450
9451     case POINTER_TYPE:
9452     case REFERENCE_TYPE:
9453       {
9454         enum tree_code code;
9455
9456         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9457           return t;
9458
9459         code = TREE_CODE (t);
9460
9461
9462         /* [temp.deduct]
9463
9464            Type deduction may fail for any of the following
9465            reasons:
9466
9467            -- Attempting to create a pointer to reference type.
9468            -- Attempting to create a reference to a reference type or
9469               a reference to void.
9470
9471           Core issue 106 says that creating a reference to a reference
9472           during instantiation is no longer a cause for failure. We
9473           only enforce this check in strict C++98 mode.  */
9474         if ((TREE_CODE (type) == REFERENCE_TYPE
9475              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9476             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9477           {
9478             static location_t last_loc;
9479
9480             /* We keep track of the last time we issued this error
9481                message to avoid spewing a ton of messages during a
9482                single bad template instantiation.  */
9483             if (complain & tf_error
9484                 && last_loc != input_location)
9485               {
9486                 if (TREE_CODE (type) == VOID_TYPE)
9487                   error ("forming reference to void");
9488                 else
9489                   error ("forming %s to reference type %qT",
9490                          (code == POINTER_TYPE) ? "pointer" : "reference",
9491                          type);
9492                 last_loc = input_location;
9493               }
9494
9495             return error_mark_node;
9496           }
9497         else if (code == POINTER_TYPE)
9498           {
9499             r = build_pointer_type (type);
9500             if (TREE_CODE (type) == METHOD_TYPE)
9501               r = build_ptrmemfunc_type (r);
9502           }
9503         else if (TREE_CODE (type) == REFERENCE_TYPE)
9504           /* In C++0x, during template argument substitution, when there is an
9505              attempt to create a reference to a reference type, reference
9506              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9507
9508              "If a template-argument for a template-parameter T names a type
9509              that is a reference to a type A, an attempt to create the type
9510              'lvalue reference to cv T' creates the type 'lvalue reference to
9511              A,' while an attempt to create the type type rvalue reference to
9512              cv T' creates the type T"
9513           */
9514           r = cp_build_reference_type
9515               (TREE_TYPE (type),
9516                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9517         else
9518           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9519         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9520
9521         if (r != error_mark_node)
9522           /* Will this ever be needed for TYPE_..._TO values?  */
9523           layout_type (r);
9524
9525         return r;
9526       }
9527     case OFFSET_TYPE:
9528       {
9529         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9530         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9531           {
9532             /* [temp.deduct]
9533
9534                Type deduction may fail for any of the following
9535                reasons:
9536
9537                -- Attempting to create "pointer to member of T" when T
9538                   is not a class type.  */
9539             if (complain & tf_error)
9540               error ("creating pointer to member of non-class type %qT", r);
9541             return error_mark_node;
9542           }
9543         if (TREE_CODE (type) == REFERENCE_TYPE)
9544           {
9545             if (complain & tf_error)
9546               error ("creating pointer to member reference type %qT", type);
9547             return error_mark_node;
9548           }
9549         if (TREE_CODE (type) == VOID_TYPE)
9550           {
9551             if (complain & tf_error)
9552               error ("creating pointer to member of type void");
9553             return error_mark_node;
9554           }
9555         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9556         if (TREE_CODE (type) == FUNCTION_TYPE)
9557           {
9558             /* The type of the implicit object parameter gets its
9559                cv-qualifiers from the FUNCTION_TYPE. */
9560             tree method_type;
9561             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9562                                                       cp_type_quals (type));
9563             tree memptr;
9564             method_type = build_method_type_directly (this_type,
9565                                                       TREE_TYPE (type),
9566                                                       TYPE_ARG_TYPES (type));
9567             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9568             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9569                                                  complain);
9570           }
9571         else
9572           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9573                                                TYPE_QUALS (t),
9574                                                complain);
9575       }
9576     case FUNCTION_TYPE:
9577     case METHOD_TYPE:
9578       {
9579         tree fntype;
9580         tree specs;
9581         fntype = tsubst_function_type (t, args, complain, in_decl);
9582         if (fntype == error_mark_node)
9583           return error_mark_node;
9584
9585         /* Substitute the exception specification.  */
9586         specs = tsubst_exception_specification (t, args, complain,
9587                                                 in_decl);
9588         if (specs == error_mark_node)
9589           return error_mark_node;
9590         if (specs)
9591           fntype = build_exception_variant (fntype, specs);
9592         return fntype;
9593       }
9594     case ARRAY_TYPE:
9595       {
9596         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9597         if (domain == error_mark_node)
9598           return error_mark_node;
9599
9600         /* As an optimization, we avoid regenerating the array type if
9601            it will obviously be the same as T.  */
9602         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9603           return t;
9604
9605         /* These checks should match the ones in grokdeclarator.
9606
9607            [temp.deduct]
9608
9609            The deduction may fail for any of the following reasons:
9610
9611            -- Attempting to create an array with an element type that
9612               is void, a function type, or a reference type, or [DR337]
9613               an abstract class type.  */
9614         if (TREE_CODE (type) == VOID_TYPE
9615             || TREE_CODE (type) == FUNCTION_TYPE
9616             || TREE_CODE (type) == REFERENCE_TYPE)
9617           {
9618             if (complain & tf_error)
9619               error ("creating array of %qT", type);
9620             return error_mark_node;
9621           }
9622         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9623           {
9624             if (complain & tf_error)
9625               error ("creating array of %qT, which is an abstract class type",
9626                      type);
9627             return error_mark_node;
9628           }
9629
9630         r = build_cplus_array_type (type, domain);
9631
9632         if (TYPE_USER_ALIGN (t))
9633           {
9634             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9635             TYPE_USER_ALIGN (r) = 1;
9636           }
9637
9638         return r;
9639       }
9640
9641     case PLUS_EXPR:
9642     case MINUS_EXPR:
9643       {
9644         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9645         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9646
9647         if (e1 == error_mark_node || e2 == error_mark_node)
9648           return error_mark_node;
9649
9650         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9651       }
9652
9653     case NEGATE_EXPR:
9654     case NOP_EXPR:
9655       {
9656         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9657         if (e == error_mark_node)
9658           return error_mark_node;
9659
9660         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9661       }
9662
9663     case TYPENAME_TYPE:
9664       {
9665         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9666                                      in_decl, /*entering_scope=*/1);
9667         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9668                               complain, in_decl);
9669
9670         if (ctx == error_mark_node || f == error_mark_node)
9671           return error_mark_node;
9672
9673         if (!MAYBE_CLASS_TYPE_P (ctx))
9674           {
9675             if (complain & tf_error)
9676               error ("%qT is not a class, struct, or union type", ctx);
9677             return error_mark_node;
9678           }
9679         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9680           {
9681             /* Normally, make_typename_type does not require that the CTX
9682                have complete type in order to allow things like:
9683
9684                  template <class T> struct S { typename S<T>::X Y; };
9685
9686                But, such constructs have already been resolved by this
9687                point, so here CTX really should have complete type, unless
9688                it's a partial instantiation.  */
9689             ctx = complete_type (ctx);
9690             if (!COMPLETE_TYPE_P (ctx))
9691               {
9692                 if (complain & tf_error)
9693                   cxx_incomplete_type_error (NULL_TREE, ctx);
9694                 return error_mark_node;
9695               }
9696           }
9697
9698         f = make_typename_type (ctx, f, typename_type,
9699                                 (complain & tf_error) | tf_keep_type_decl);
9700         if (f == error_mark_node)
9701           return f;
9702         if (TREE_CODE (f) == TYPE_DECL)
9703           {
9704             complain |= tf_ignore_bad_quals;
9705             f = TREE_TYPE (f);
9706           }
9707
9708         if (TREE_CODE (f) != TYPENAME_TYPE)
9709           {
9710             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9711               error ("%qT resolves to %qT, which is not an enumeration type",
9712                      t, f);
9713             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9714               error ("%qT resolves to %qT, which is is not a class type",
9715                      t, f);
9716           }
9717
9718         return cp_build_qualified_type_real
9719           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9720       }
9721
9722     case UNBOUND_CLASS_TEMPLATE:
9723       {
9724         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9725                                      in_decl, /*entering_scope=*/1);
9726         tree name = TYPE_IDENTIFIER (t);
9727         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9728
9729         if (ctx == error_mark_node || name == error_mark_node)
9730           return error_mark_node;
9731
9732         if (parm_list)
9733           parm_list = tsubst_template_parms (parm_list, args, complain);
9734         return make_unbound_class_template (ctx, name, parm_list, complain);
9735       }
9736
9737     case INDIRECT_REF:
9738     case ADDR_EXPR:
9739     case CALL_EXPR:
9740       gcc_unreachable ();
9741
9742     case ARRAY_REF:
9743       {
9744         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9745         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9746                                /*integral_constant_expression_p=*/false);
9747         if (e1 == error_mark_node || e2 == error_mark_node)
9748           return error_mark_node;
9749
9750         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9751       }
9752
9753     case SCOPE_REF:
9754       {
9755         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9756         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9757         if (e1 == error_mark_node || e2 == error_mark_node)
9758           return error_mark_node;
9759
9760         return build_qualified_name (/*type=*/NULL_TREE,
9761                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9762       }
9763
9764     case TYPEOF_TYPE:
9765       {
9766         tree type;
9767
9768         type = finish_typeof (tsubst_expr 
9769                               (TYPEOF_TYPE_EXPR (t), args,
9770                                complain, in_decl,
9771                                /*integral_constant_expression_p=*/false));
9772         return cp_build_qualified_type_real (type,
9773                                              cp_type_quals (t)
9774                                              | cp_type_quals (type),
9775                                              complain);
9776       }
9777
9778     case DECLTYPE_TYPE:
9779       {
9780         tree type;
9781
9782         ++cp_unevaluated_operand;
9783         ++c_inhibit_evaluation_warnings;
9784
9785         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
9786                             complain, in_decl,
9787                             /*integral_constant_expression_p=*/false);
9788
9789         --cp_unevaluated_operand;
9790         --c_inhibit_evaluation_warnings;
9791
9792         type =
9793           finish_decltype_type (type,
9794                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9795         return cp_build_qualified_type_real (type,
9796                                              cp_type_quals (t)
9797                                              | cp_type_quals (type),
9798                                              complain);
9799       }
9800
9801     case TYPE_ARGUMENT_PACK:
9802     case NONTYPE_ARGUMENT_PACK:
9803       {
9804         tree r = make_node (TREE_CODE (t));
9805         tree packed_out = 
9806           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9807                                 args,
9808                                 complain,
9809                                 in_decl);
9810         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9811
9812         /* For template nontype argument packs, also substitute into
9813            the type.  */
9814         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9815           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9816
9817         return r;
9818       }
9819       break;
9820
9821     default:
9822       sorry ("use of %qs in template",
9823              tree_code_name [(int) TREE_CODE (t)]);
9824       return error_mark_node;
9825     }
9826 }
9827
9828 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9829    type of the expression on the left-hand side of the "." or "->"
9830    operator.  */
9831
9832 static tree
9833 tsubst_baselink (tree baselink, tree object_type,
9834                  tree args, tsubst_flags_t complain, tree in_decl)
9835 {
9836     tree name;
9837     tree qualifying_scope;
9838     tree fns;
9839     tree optype;
9840     tree template_args = 0;
9841     bool template_id_p = false;
9842
9843     /* A baselink indicates a function from a base class.  Both the
9844        BASELINK_ACCESS_BINFO and the base class referenced may
9845        indicate bases of the template class, rather than the
9846        instantiated class.  In addition, lookups that were not
9847        ambiguous before may be ambiguous now.  Therefore, we perform
9848        the lookup again.  */
9849     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9850     qualifying_scope = tsubst (qualifying_scope, args,
9851                                complain, in_decl);
9852     fns = BASELINK_FUNCTIONS (baselink);
9853     optype = BASELINK_OPTYPE (baselink);
9854     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9855       {
9856         template_id_p = true;
9857         template_args = TREE_OPERAND (fns, 1);
9858         fns = TREE_OPERAND (fns, 0);
9859         if (template_args)
9860           template_args = tsubst_template_args (template_args, args,
9861                                                 complain, in_decl);
9862       }
9863     name = DECL_NAME (get_first_fn (fns));
9864     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9865
9866     /* If lookup found a single function, mark it as used at this
9867        point.  (If it lookup found multiple functions the one selected
9868        later by overload resolution will be marked as used at that
9869        point.)  */
9870     if (BASELINK_P (baselink))
9871       fns = BASELINK_FUNCTIONS (baselink);
9872     if (!template_id_p && !really_overloaded_fn (fns))
9873       mark_used (OVL_CURRENT (fns));
9874
9875     /* Add back the template arguments, if present.  */
9876     if (BASELINK_P (baselink) && template_id_p)
9877       BASELINK_FUNCTIONS (baselink)
9878         = build_nt (TEMPLATE_ID_EXPR,
9879                     BASELINK_FUNCTIONS (baselink),
9880                     template_args);
9881     /* Update the conversion operator type.  */
9882     BASELINK_OPTYPE (baselink) 
9883       = tsubst (optype, args, complain, in_decl);
9884
9885     if (!object_type)
9886       object_type = current_class_type;
9887     return adjust_result_of_qualified_name_lookup (baselink,
9888                                                    qualifying_scope,
9889                                                    object_type);
9890 }
9891
9892 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9893    true if the qualified-id will be a postfix-expression in-and-of
9894    itself; false if more of the postfix-expression follows the
9895    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9896    of "&".  */
9897
9898 static tree
9899 tsubst_qualified_id (tree qualified_id, tree args,
9900                      tsubst_flags_t complain, tree in_decl,
9901                      bool done, bool address_p)
9902 {
9903   tree expr;
9904   tree scope;
9905   tree name;
9906   bool is_template;
9907   tree template_args;
9908
9909   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9910
9911   /* Figure out what name to look up.  */
9912   name = TREE_OPERAND (qualified_id, 1);
9913   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9914     {
9915       is_template = true;
9916       template_args = TREE_OPERAND (name, 1);
9917       if (template_args)
9918         template_args = tsubst_template_args (template_args, args,
9919                                               complain, in_decl);
9920       name = TREE_OPERAND (name, 0);
9921     }
9922   else
9923     {
9924       is_template = false;
9925       template_args = NULL_TREE;
9926     }
9927
9928   /* Substitute into the qualifying scope.  When there are no ARGS, we
9929      are just trying to simplify a non-dependent expression.  In that
9930      case the qualifying scope may be dependent, and, in any case,
9931      substituting will not help.  */
9932   scope = TREE_OPERAND (qualified_id, 0);
9933   if (args)
9934     {
9935       scope = tsubst (scope, args, complain, in_decl);
9936       expr = tsubst_copy (name, args, complain, in_decl);
9937     }
9938   else
9939     expr = name;
9940
9941   if (dependent_type_p (scope))
9942     {
9943       tree type = NULL_TREE;
9944       if (DECL_P (expr) && !dependent_scope_p (scope))
9945         type = TREE_TYPE (expr);
9946       return build_qualified_name (type, scope, expr,
9947                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9948     }
9949
9950   if (!BASELINK_P (name) && !DECL_P (expr))
9951     {
9952       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9953         {
9954           /* A BIT_NOT_EXPR is used to represent a destructor.  */
9955           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
9956             {
9957               error ("qualifying type %qT does not match destructor name ~%qT",
9958                      scope, TREE_OPERAND (expr, 0));
9959               expr = error_mark_node;
9960             }
9961           else
9962             expr = lookup_qualified_name (scope, complete_dtor_identifier,
9963                                           /*is_type_p=*/0, false);
9964         }
9965       else
9966         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9967       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9968                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9969         {
9970           if (complain & tf_error)
9971             {
9972               error ("dependent-name %qE is parsed as a non-type, but "
9973                      "instantiation yields a type", qualified_id);
9974               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
9975             }
9976           return error_mark_node;
9977         }
9978     }
9979
9980   if (DECL_P (expr))
9981     {
9982       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9983                                            scope);
9984       /* Remember that there was a reference to this entity.  */
9985       mark_used (expr);
9986     }
9987
9988   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9989     {
9990       if (complain & tf_error)
9991         qualified_name_lookup_error (scope,
9992                                      TREE_OPERAND (qualified_id, 1),
9993                                      expr, input_location);
9994       return error_mark_node;
9995     }
9996
9997   if (is_template)
9998     expr = lookup_template_function (expr, template_args);
9999
10000   if (expr == error_mark_node && complain & tf_error)
10001     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10002                                  expr, input_location);
10003   else if (TYPE_P (scope))
10004     {
10005       expr = (adjust_result_of_qualified_name_lookup
10006               (expr, scope, current_class_type));
10007       expr = (finish_qualified_id_expr
10008               (scope, expr, done, address_p,
10009                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10010                /*template_arg_p=*/false));
10011     }
10012
10013   /* Expressions do not generally have reference type.  */
10014   if (TREE_CODE (expr) != SCOPE_REF
10015       /* However, if we're about to form a pointer-to-member, we just
10016          want the referenced member referenced.  */
10017       && TREE_CODE (expr) != OFFSET_REF)
10018     expr = convert_from_reference (expr);
10019
10020   return expr;
10021 }
10022
10023 /* Like tsubst, but deals with expressions.  This function just replaces
10024    template parms; to finish processing the resultant expression, use
10025    tsubst_expr.  */
10026
10027 static tree
10028 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10029 {
10030   enum tree_code code;
10031   tree r;
10032
10033   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10034     return t;
10035
10036   code = TREE_CODE (t);
10037
10038   switch (code)
10039     {
10040     case PARM_DECL:
10041       r = retrieve_local_specialization (t);
10042
10043       if (r == NULL)
10044         {
10045           tree c;
10046           /* This can happen for a parameter name used later in a function
10047              declaration (such as in a late-specified return type).  Just
10048              make a dummy decl, since it's only used for its type.  */
10049           gcc_assert (cp_unevaluated_operand != 0);
10050           /* We copy T because want to tsubst the PARM_DECL only,
10051              not the following PARM_DECLs that are chained to T.  */
10052           c = copy_node (t);
10053           r = tsubst_decl (c, args, complain);
10054           /* Give it the template pattern as its context; its true context
10055              hasn't been instantiated yet and this is good enough for
10056              mangling.  */
10057           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10058         }
10059       
10060       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10061         r = ARGUMENT_PACK_SELECT_ARG (r);
10062       mark_used (r);
10063       return r;
10064
10065     case CONST_DECL:
10066       {
10067         tree enum_type;
10068         tree v;
10069
10070         if (DECL_TEMPLATE_PARM_P (t))
10071           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10072         /* There is no need to substitute into namespace-scope
10073            enumerators.  */
10074         if (DECL_NAMESPACE_SCOPE_P (t))
10075           return t;
10076         /* If ARGS is NULL, then T is known to be non-dependent.  */
10077         if (args == NULL_TREE)
10078           return integral_constant_value (t);
10079
10080         /* Unfortunately, we cannot just call lookup_name here.
10081            Consider:
10082
10083              template <int I> int f() {
10084              enum E { a = I };
10085              struct S { void g() { E e = a; } };
10086              };
10087
10088            When we instantiate f<7>::S::g(), say, lookup_name is not
10089            clever enough to find f<7>::a.  */
10090         enum_type
10091           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10092                               /*entering_scope=*/0);
10093
10094         for (v = TYPE_VALUES (enum_type);
10095              v != NULL_TREE;
10096              v = TREE_CHAIN (v))
10097           if (TREE_PURPOSE (v) == DECL_NAME (t))
10098             return TREE_VALUE (v);
10099
10100           /* We didn't find the name.  That should never happen; if
10101              name-lookup found it during preliminary parsing, we
10102              should find it again here during instantiation.  */
10103         gcc_unreachable ();
10104       }
10105       return t;
10106
10107     case FIELD_DECL:
10108       if (DECL_CONTEXT (t))
10109         {
10110           tree ctx;
10111
10112           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10113                                   /*entering_scope=*/1);
10114           if (ctx != DECL_CONTEXT (t))
10115             {
10116               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10117               if (!r)
10118                 {
10119                   if (complain & tf_error)
10120                     error ("using invalid field %qD", t);
10121                   return error_mark_node;
10122                 }
10123               return r;
10124             }
10125         }
10126
10127       return t;
10128
10129     case VAR_DECL:
10130     case FUNCTION_DECL:
10131       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10132           || local_variable_p (t))
10133         t = tsubst (t, args, complain, in_decl);
10134       mark_used (t);
10135       return t;
10136
10137     case BASELINK:
10138       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10139
10140     case TEMPLATE_DECL:
10141       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10142         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10143                        args, complain, in_decl);
10144       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10145         return tsubst (t, args, complain, in_decl);
10146       else if (DECL_CLASS_SCOPE_P (t)
10147                && uses_template_parms (DECL_CONTEXT (t)))
10148         {
10149           /* Template template argument like the following example need
10150              special treatment:
10151
10152                template <template <class> class TT> struct C {};
10153                template <class T> struct D {
10154                  template <class U> struct E {};
10155                  C<E> c;                                // #1
10156                };
10157                D<int> d;                                // #2
10158
10159              We are processing the template argument `E' in #1 for
10160              the template instantiation #2.  Originally, `E' is a
10161              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10162              have to substitute this with one having context `D<int>'.  */
10163
10164           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10165           return lookup_field (context, DECL_NAME(t), 0, false);
10166         }
10167       else
10168         /* Ordinary template template argument.  */
10169         return t;
10170
10171     case CAST_EXPR:
10172     case REINTERPRET_CAST_EXPR:
10173     case CONST_CAST_EXPR:
10174     case STATIC_CAST_EXPR:
10175     case DYNAMIC_CAST_EXPR:
10176     case NOP_EXPR:
10177       return build1
10178         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10179          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10180
10181     case SIZEOF_EXPR:
10182       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10183         {
10184           /* We only want to compute the number of arguments.  */
10185           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10186                                                 complain, in_decl);
10187           int len = 0;
10188
10189           if (TREE_CODE (expanded) == TREE_VEC)
10190             len = TREE_VEC_LENGTH (expanded);
10191
10192           if (expanded == error_mark_node)
10193             return error_mark_node;
10194           else if (PACK_EXPANSION_P (expanded)
10195                    || (TREE_CODE (expanded) == TREE_VEC
10196                        && len > 0
10197                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10198             {
10199               if (TREE_CODE (expanded) == TREE_VEC)
10200                 expanded = TREE_VEC_ELT (expanded, len - 1);
10201
10202               if (TYPE_P (expanded))
10203                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10204                                                    complain & tf_error);
10205               else
10206                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10207                                                    complain & tf_error);
10208             }
10209           else
10210             return build_int_cst (size_type_node, len);
10211         }
10212       /* Fall through */
10213
10214     case INDIRECT_REF:
10215     case NEGATE_EXPR:
10216     case TRUTH_NOT_EXPR:
10217     case BIT_NOT_EXPR:
10218     case ADDR_EXPR:
10219     case UNARY_PLUS_EXPR:      /* Unary + */
10220     case ALIGNOF_EXPR:
10221     case ARROW_EXPR:
10222     case THROW_EXPR:
10223     case TYPEID_EXPR:
10224     case REALPART_EXPR:
10225     case IMAGPART_EXPR:
10226       return build1
10227         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10228          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10229
10230     case COMPONENT_REF:
10231       {
10232         tree object;
10233         tree name;
10234
10235         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10236         name = TREE_OPERAND (t, 1);
10237         if (TREE_CODE (name) == BIT_NOT_EXPR)
10238           {
10239             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10240                                 complain, in_decl);
10241             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10242           }
10243         else if (TREE_CODE (name) == SCOPE_REF
10244                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10245           {
10246             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10247                                      complain, in_decl);
10248             name = TREE_OPERAND (name, 1);
10249             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10250                                 complain, in_decl);
10251             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10252             name = build_qualified_name (/*type=*/NULL_TREE,
10253                                          base, name,
10254                                          /*template_p=*/false);
10255           }
10256         else if (TREE_CODE (name) == BASELINK)
10257           name = tsubst_baselink (name,
10258                                   non_reference (TREE_TYPE (object)),
10259                                   args, complain,
10260                                   in_decl);
10261         else
10262           name = tsubst_copy (name, args, complain, in_decl);
10263         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10264       }
10265
10266     case PLUS_EXPR:
10267     case MINUS_EXPR:
10268     case MULT_EXPR:
10269     case TRUNC_DIV_EXPR:
10270     case CEIL_DIV_EXPR:
10271     case FLOOR_DIV_EXPR:
10272     case ROUND_DIV_EXPR:
10273     case EXACT_DIV_EXPR:
10274     case BIT_AND_EXPR:
10275     case BIT_IOR_EXPR:
10276     case BIT_XOR_EXPR:
10277     case TRUNC_MOD_EXPR:
10278     case FLOOR_MOD_EXPR:
10279     case TRUTH_ANDIF_EXPR:
10280     case TRUTH_ORIF_EXPR:
10281     case TRUTH_AND_EXPR:
10282     case TRUTH_OR_EXPR:
10283     case RSHIFT_EXPR:
10284     case LSHIFT_EXPR:
10285     case RROTATE_EXPR:
10286     case LROTATE_EXPR:
10287     case EQ_EXPR:
10288     case NE_EXPR:
10289     case MAX_EXPR:
10290     case MIN_EXPR:
10291     case LE_EXPR:
10292     case GE_EXPR:
10293     case LT_EXPR:
10294     case GT_EXPR:
10295     case COMPOUND_EXPR:
10296     case DOTSTAR_EXPR:
10297     case MEMBER_REF:
10298     case PREDECREMENT_EXPR:
10299     case PREINCREMENT_EXPR:
10300     case POSTDECREMENT_EXPR:
10301     case POSTINCREMENT_EXPR:
10302       return build_nt
10303         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10304          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10305
10306     case SCOPE_REF:
10307       return build_qualified_name (/*type=*/NULL_TREE,
10308                                    tsubst_copy (TREE_OPERAND (t, 0),
10309                                                 args, complain, in_decl),
10310                                    tsubst_copy (TREE_OPERAND (t, 1),
10311                                                 args, complain, in_decl),
10312                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10313
10314     case ARRAY_REF:
10315       return build_nt
10316         (ARRAY_REF,
10317          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10318          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10319          NULL_TREE, NULL_TREE);
10320
10321     case CALL_EXPR:
10322       {
10323         int n = VL_EXP_OPERAND_LENGTH (t);
10324         tree result = build_vl_exp (CALL_EXPR, n);
10325         int i;
10326         for (i = 0; i < n; i++)
10327           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10328                                              complain, in_decl);
10329         return result;
10330       }
10331
10332     case COND_EXPR:
10333     case MODOP_EXPR:
10334     case PSEUDO_DTOR_EXPR:
10335       {
10336         r = build_nt
10337           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10338            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10339            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10340         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10341         return r;
10342       }
10343
10344     case NEW_EXPR:
10345       {
10346         r = build_nt
10347         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10348          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10349          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10350         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10351         return r;
10352       }
10353
10354     case DELETE_EXPR:
10355       {
10356         r = build_nt
10357         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10358          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10359         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10360         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10361         return r;
10362       }
10363
10364     case TEMPLATE_ID_EXPR:
10365       {
10366         /* Substituted template arguments */
10367         tree fn = TREE_OPERAND (t, 0);
10368         tree targs = TREE_OPERAND (t, 1);
10369
10370         fn = tsubst_copy (fn, args, complain, in_decl);
10371         if (targs)
10372           targs = tsubst_template_args (targs, args, complain, in_decl);
10373
10374         return lookup_template_function (fn, targs);
10375       }
10376
10377     case TREE_LIST:
10378       {
10379         tree purpose, value, chain;
10380
10381         if (t == void_list_node)
10382           return t;
10383
10384         purpose = TREE_PURPOSE (t);
10385         if (purpose)
10386           purpose = tsubst_copy (purpose, args, complain, in_decl);
10387         value = TREE_VALUE (t);
10388         if (value)
10389           value = tsubst_copy (value, args, complain, in_decl);
10390         chain = TREE_CHAIN (t);
10391         if (chain && chain != void_type_node)
10392           chain = tsubst_copy (chain, args, complain, in_decl);
10393         if (purpose == TREE_PURPOSE (t)
10394             && value == TREE_VALUE (t)
10395             && chain == TREE_CHAIN (t))
10396           return t;
10397         return tree_cons (purpose, value, chain);
10398       }
10399
10400     case RECORD_TYPE:
10401     case UNION_TYPE:
10402     case ENUMERAL_TYPE:
10403     case INTEGER_TYPE:
10404     case TEMPLATE_TYPE_PARM:
10405     case TEMPLATE_TEMPLATE_PARM:
10406     case BOUND_TEMPLATE_TEMPLATE_PARM:
10407     case TEMPLATE_PARM_INDEX:
10408     case POINTER_TYPE:
10409     case REFERENCE_TYPE:
10410     case OFFSET_TYPE:
10411     case FUNCTION_TYPE:
10412     case METHOD_TYPE:
10413     case ARRAY_TYPE:
10414     case TYPENAME_TYPE:
10415     case UNBOUND_CLASS_TEMPLATE:
10416     case TYPEOF_TYPE:
10417     case DECLTYPE_TYPE:
10418     case TYPE_DECL:
10419       return tsubst (t, args, complain, in_decl);
10420
10421     case IDENTIFIER_NODE:
10422       if (IDENTIFIER_TYPENAME_P (t))
10423         {
10424           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10425           return mangle_conv_op_name_for_type (new_type);
10426         }
10427       else
10428         return t;
10429
10430     case CONSTRUCTOR:
10431       /* This is handled by tsubst_copy_and_build.  */
10432       gcc_unreachable ();
10433
10434     case VA_ARG_EXPR:
10435       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10436                                           in_decl),
10437                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10438
10439     case CLEANUP_POINT_EXPR:
10440       /* We shouldn't have built any of these during initial template
10441          generation.  Instead, they should be built during instantiation
10442          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10443       gcc_unreachable ();
10444
10445     case OFFSET_REF:
10446       mark_used (TREE_OPERAND (t, 1));
10447       return t;
10448
10449     case EXPR_PACK_EXPANSION:
10450       error ("invalid use of pack expansion expression");
10451       return error_mark_node;
10452
10453     case NONTYPE_ARGUMENT_PACK:
10454       error ("use %<...%> to expand argument pack");
10455       return error_mark_node;
10456
10457     default:
10458       return t;
10459     }
10460 }
10461
10462 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10463
10464 static tree
10465 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10466                     tree in_decl)
10467 {
10468   tree new_clauses = NULL, nc, oc;
10469
10470   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10471     {
10472       nc = copy_node (oc);
10473       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10474       new_clauses = nc;
10475
10476       switch (OMP_CLAUSE_CODE (nc))
10477         {
10478         case OMP_CLAUSE_LASTPRIVATE:
10479           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10480             {
10481               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10482               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10483                            in_decl, /*integral_constant_expression_p=*/false);
10484               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10485                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10486             }
10487           /* FALLTHRU */
10488         case OMP_CLAUSE_PRIVATE:
10489         case OMP_CLAUSE_SHARED:
10490         case OMP_CLAUSE_FIRSTPRIVATE:
10491         case OMP_CLAUSE_REDUCTION:
10492         case OMP_CLAUSE_COPYIN:
10493         case OMP_CLAUSE_COPYPRIVATE:
10494         case OMP_CLAUSE_IF:
10495         case OMP_CLAUSE_NUM_THREADS:
10496         case OMP_CLAUSE_SCHEDULE:
10497         case OMP_CLAUSE_COLLAPSE:
10498           OMP_CLAUSE_OPERAND (nc, 0)
10499             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10500                            in_decl, /*integral_constant_expression_p=*/false);
10501           break;
10502         case OMP_CLAUSE_NOWAIT:
10503         case OMP_CLAUSE_ORDERED:
10504         case OMP_CLAUSE_DEFAULT:
10505         case OMP_CLAUSE_UNTIED:
10506           break;
10507         default:
10508           gcc_unreachable ();
10509         }
10510     }
10511
10512   return finish_omp_clauses (nreverse (new_clauses));
10513 }
10514
10515 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10516
10517 static tree
10518 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10519                           tree in_decl)
10520 {
10521 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10522
10523   tree purpose, value, chain;
10524
10525   if (t == NULL)
10526     return t;
10527
10528   if (TREE_CODE (t) != TREE_LIST)
10529     return tsubst_copy_and_build (t, args, complain, in_decl,
10530                                   /*function_p=*/false,
10531                                   /*integral_constant_expression_p=*/false);
10532
10533   if (t == void_list_node)
10534     return t;
10535
10536   purpose = TREE_PURPOSE (t);
10537   if (purpose)
10538     purpose = RECUR (purpose);
10539   value = TREE_VALUE (t);
10540   if (value)
10541     value = RECUR (value);
10542   chain = TREE_CHAIN (t);
10543   if (chain && chain != void_type_node)
10544     chain = RECUR (chain);
10545   return tree_cons (purpose, value, chain);
10546 #undef RECUR
10547 }
10548
10549 /* Substitute one OMP_FOR iterator.  */
10550
10551 static void
10552 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
10553                          tree condv, tree incrv, tree *clauses,
10554                          tree args, tsubst_flags_t complain, tree in_decl,
10555                          bool integral_constant_expression_p)
10556 {
10557 #define RECUR(NODE)                             \
10558   tsubst_expr ((NODE), args, complain, in_decl, \
10559                integral_constant_expression_p)
10560   tree decl, init, cond, incr, auto_node;
10561
10562   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
10563   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10564   decl = RECUR (TREE_OPERAND (init, 0));
10565   init = TREE_OPERAND (init, 1);
10566   auto_node = type_uses_auto (TREE_TYPE (decl));
10567   if (auto_node && init)
10568     {
10569       tree init_expr = init;
10570       if (TREE_CODE (init_expr) == DECL_EXPR)
10571         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
10572       init_expr = RECUR (init_expr);
10573       TREE_TYPE (decl)
10574         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
10575     }
10576   gcc_assert (!type_dependent_expression_p (decl));
10577
10578   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
10579     {
10580       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
10581       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10582       if (TREE_CODE (incr) == MODIFY_EXPR)
10583         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
10584                                     RECUR (TREE_OPERAND (incr, 1)),
10585                                     complain);
10586       else
10587         incr = RECUR (incr);
10588       TREE_VEC_ELT (declv, i) = decl;
10589       TREE_VEC_ELT (initv, i) = init;
10590       TREE_VEC_ELT (condv, i) = cond;
10591       TREE_VEC_ELT (incrv, i) = incr;
10592       return;
10593     }
10594
10595   if (init && TREE_CODE (init) != DECL_EXPR)
10596     {
10597       tree c;
10598       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
10599         {
10600           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
10601                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
10602               && OMP_CLAUSE_DECL (c) == decl)
10603             break;
10604           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
10605                    && OMP_CLAUSE_DECL (c) == decl)
10606             error ("iteration variable %qD should not be firstprivate", decl);
10607           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
10608                    && OMP_CLAUSE_DECL (c) == decl)
10609             error ("iteration variable %qD should not be reduction", decl);
10610         }
10611       if (c == NULL)
10612         {
10613           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
10614           OMP_CLAUSE_DECL (c) = decl;
10615           c = finish_omp_clauses (c);
10616           if (c)
10617             {
10618               OMP_CLAUSE_CHAIN (c) = *clauses;
10619               *clauses = c;
10620             }
10621         }
10622     }
10623   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
10624   if (COMPARISON_CLASS_P (cond))
10625     cond = build2 (TREE_CODE (cond), boolean_type_node,
10626                    RECUR (TREE_OPERAND (cond, 0)),
10627                    RECUR (TREE_OPERAND (cond, 1)));
10628   else
10629     cond = RECUR (cond);
10630   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10631   switch (TREE_CODE (incr))
10632     {
10633     case PREINCREMENT_EXPR:
10634     case PREDECREMENT_EXPR:
10635     case POSTINCREMENT_EXPR:
10636     case POSTDECREMENT_EXPR:
10637       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
10638                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
10639       break;
10640     case MODIFY_EXPR:
10641       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10642           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10643         {
10644           tree rhs = TREE_OPERAND (incr, 1);
10645           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10646                          RECUR (TREE_OPERAND (incr, 0)),
10647                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10648                                  RECUR (TREE_OPERAND (rhs, 0)),
10649                                  RECUR (TREE_OPERAND (rhs, 1))));
10650         }
10651       else
10652         incr = RECUR (incr);
10653       break;
10654     case MODOP_EXPR:
10655       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10656           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10657         {
10658           tree lhs = RECUR (TREE_OPERAND (incr, 0));
10659           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
10660                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
10661                                  TREE_TYPE (decl), lhs,
10662                                  RECUR (TREE_OPERAND (incr, 2))));
10663         }
10664       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
10665                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
10666                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
10667         {
10668           tree rhs = TREE_OPERAND (incr, 2);
10669           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10670                          RECUR (TREE_OPERAND (incr, 0)),
10671                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10672                                  RECUR (TREE_OPERAND (rhs, 0)),
10673                                  RECUR (TREE_OPERAND (rhs, 1))));
10674         }
10675       else
10676         incr = RECUR (incr);
10677       break;
10678     default:
10679       incr = RECUR (incr);
10680       break;
10681     }
10682
10683   TREE_VEC_ELT (declv, i) = decl;
10684   TREE_VEC_ELT (initv, i) = init;
10685   TREE_VEC_ELT (condv, i) = cond;
10686   TREE_VEC_ELT (incrv, i) = incr;
10687 #undef RECUR
10688 }
10689
10690 /* Like tsubst_copy for expressions, etc. but also does semantic
10691    processing.  */
10692
10693 static tree
10694 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10695              bool integral_constant_expression_p)
10696 {
10697 #define RECUR(NODE)                             \
10698   tsubst_expr ((NODE), args, complain, in_decl, \
10699                integral_constant_expression_p)
10700
10701   tree stmt, tmp;
10702
10703   if (t == NULL_TREE || t == error_mark_node)
10704     return t;
10705
10706   if (EXPR_HAS_LOCATION (t))
10707     input_location = EXPR_LOCATION (t);
10708   if (STATEMENT_CODE_P (TREE_CODE (t)))
10709     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10710
10711   switch (TREE_CODE (t))
10712     {
10713     case STATEMENT_LIST:
10714       {
10715         tree_stmt_iterator i;
10716         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10717           RECUR (tsi_stmt (i));
10718         break;
10719       }
10720
10721     case CTOR_INITIALIZER:
10722       finish_mem_initializers (tsubst_initializer_list
10723                                (TREE_OPERAND (t, 0), args));
10724       break;
10725
10726     case RETURN_EXPR:
10727       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10728       break;
10729
10730     case EXPR_STMT:
10731       tmp = RECUR (EXPR_STMT_EXPR (t));
10732       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10733         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10734       else
10735         finish_expr_stmt (tmp);
10736       break;
10737
10738     case USING_STMT:
10739       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10740       break;
10741
10742     case DECL_EXPR:
10743       {
10744         tree decl;
10745         tree init;
10746
10747         decl = DECL_EXPR_DECL (t);
10748         if (TREE_CODE (decl) == LABEL_DECL)
10749           finish_label_decl (DECL_NAME (decl));
10750         else if (TREE_CODE (decl) == USING_DECL)
10751           {
10752             tree scope = USING_DECL_SCOPE (decl);
10753             tree name = DECL_NAME (decl);
10754             tree decl;
10755
10756             scope = RECUR (scope);
10757             decl = lookup_qualified_name (scope, name,
10758                                           /*is_type_p=*/false,
10759                                           /*complain=*/false);
10760             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10761               qualified_name_lookup_error (scope, name, decl, input_location);
10762             else
10763               do_local_using_decl (decl, scope, name);
10764           }
10765         else
10766           {
10767             init = DECL_INITIAL (decl);
10768             decl = tsubst (decl, args, complain, in_decl);
10769             if (decl != error_mark_node)
10770               {
10771                 /* By marking the declaration as instantiated, we avoid
10772                    trying to instantiate it.  Since instantiate_decl can't
10773                    handle local variables, and since we've already done
10774                    all that needs to be done, that's the right thing to
10775                    do.  */
10776                 if (TREE_CODE (decl) == VAR_DECL)
10777                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10778                 if (TREE_CODE (decl) == VAR_DECL
10779                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10780                   /* Anonymous aggregates are a special case.  */
10781                   finish_anon_union (decl);
10782                 else
10783                   {
10784                     maybe_push_decl (decl);
10785                     if (TREE_CODE (decl) == VAR_DECL
10786                         && DECL_PRETTY_FUNCTION_P (decl))
10787                       {
10788                         /* For __PRETTY_FUNCTION__ we have to adjust the
10789                            initializer.  */
10790                         const char *const name
10791                           = cxx_printable_name (current_function_decl, 2);
10792                         init = cp_fname_init (name, &TREE_TYPE (decl));
10793                       }
10794                     else
10795                       {
10796                         tree t = RECUR (init);
10797
10798                         if (init && !t)
10799                           /* If we had an initializer but it
10800                              instantiated to nothing,
10801                              value-initialize the object.  This will
10802                              only occur when the initializer was a
10803                              pack expansion where the parameter packs
10804                              used in that expansion were of length
10805                              zero.  */
10806                           init = build_value_init (TREE_TYPE (decl));
10807                         else
10808                           init = t;
10809                       }
10810
10811                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
10812                   }
10813               }
10814           }
10815
10816         /* A DECL_EXPR can also be used as an expression, in the condition
10817            clause of an if/for/while construct.  */
10818         return decl;
10819       }
10820
10821     case FOR_STMT:
10822       stmt = begin_for_stmt ();
10823                           RECUR (FOR_INIT_STMT (t));
10824       finish_for_init_stmt (stmt);
10825       tmp = RECUR (FOR_COND (t));
10826       finish_for_cond (tmp, stmt);
10827       tmp = RECUR (FOR_EXPR (t));
10828       finish_for_expr (tmp, stmt);
10829       RECUR (FOR_BODY (t));
10830       finish_for_stmt (stmt);
10831       break;
10832
10833     case WHILE_STMT:
10834       stmt = begin_while_stmt ();
10835       tmp = RECUR (WHILE_COND (t));
10836       finish_while_stmt_cond (tmp, stmt);
10837       RECUR (WHILE_BODY (t));
10838       finish_while_stmt (stmt);
10839       break;
10840
10841     case DO_STMT:
10842       stmt = begin_do_stmt ();
10843       RECUR (DO_BODY (t));
10844       finish_do_body (stmt);
10845       tmp = RECUR (DO_COND (t));
10846       finish_do_stmt (tmp, stmt);
10847       break;
10848
10849     case IF_STMT:
10850       stmt = begin_if_stmt ();
10851       tmp = RECUR (IF_COND (t));
10852       finish_if_stmt_cond (tmp, stmt);
10853       RECUR (THEN_CLAUSE (t));
10854       finish_then_clause (stmt);
10855
10856       if (ELSE_CLAUSE (t))
10857         {
10858           begin_else_clause (stmt);
10859           RECUR (ELSE_CLAUSE (t));
10860           finish_else_clause (stmt);
10861         }
10862
10863       finish_if_stmt (stmt);
10864       break;
10865
10866     case BIND_EXPR:
10867       if (BIND_EXPR_BODY_BLOCK (t))
10868         stmt = begin_function_body ();
10869       else
10870         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10871                                     ? BCS_TRY_BLOCK : 0);
10872
10873       RECUR (BIND_EXPR_BODY (t));
10874
10875       if (BIND_EXPR_BODY_BLOCK (t))
10876         finish_function_body (stmt);
10877       else
10878         finish_compound_stmt (stmt);
10879       break;
10880
10881     case BREAK_STMT:
10882       finish_break_stmt ();
10883       break;
10884
10885     case CONTINUE_STMT:
10886       finish_continue_stmt ();
10887       break;
10888
10889     case SWITCH_STMT:
10890       stmt = begin_switch_stmt ();
10891       tmp = RECUR (SWITCH_STMT_COND (t));
10892       finish_switch_cond (tmp, stmt);
10893       RECUR (SWITCH_STMT_BODY (t));
10894       finish_switch_stmt (stmt);
10895       break;
10896
10897     case CASE_LABEL_EXPR:
10898       finish_case_label (EXPR_LOCATION (t),
10899                          RECUR (CASE_LOW (t)),
10900                          RECUR (CASE_HIGH (t)));
10901       break;
10902
10903     case LABEL_EXPR:
10904       {
10905         tree decl = LABEL_EXPR_LABEL (t);
10906         tree label;
10907
10908         label = finish_label_stmt (DECL_NAME (decl));
10909         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
10910           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
10911       }
10912       break;
10913
10914     case GOTO_EXPR:
10915       tmp = GOTO_DESTINATION (t);
10916       if (TREE_CODE (tmp) != LABEL_DECL)
10917         /* Computed goto's must be tsubst'd into.  On the other hand,
10918            non-computed gotos must not be; the identifier in question
10919            will have no binding.  */
10920         tmp = RECUR (tmp);
10921       else
10922         tmp = DECL_NAME (tmp);
10923       finish_goto_stmt (tmp);
10924       break;
10925
10926     case ASM_EXPR:
10927       tmp = finish_asm_stmt
10928         (ASM_VOLATILE_P (t),
10929          RECUR (ASM_STRING (t)),
10930          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10931          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10932          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10933       {
10934         tree asm_expr = tmp;
10935         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10936           asm_expr = TREE_OPERAND (asm_expr, 0);
10937         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10938       }
10939       break;
10940
10941     case TRY_BLOCK:
10942       if (CLEANUP_P (t))
10943         {
10944           stmt = begin_try_block ();
10945           RECUR (TRY_STMTS (t));
10946           finish_cleanup_try_block (stmt);
10947           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10948         }
10949       else
10950         {
10951           tree compound_stmt = NULL_TREE;
10952
10953           if (FN_TRY_BLOCK_P (t))
10954             stmt = begin_function_try_block (&compound_stmt);
10955           else
10956             stmt = begin_try_block ();
10957
10958           RECUR (TRY_STMTS (t));
10959
10960           if (FN_TRY_BLOCK_P (t))
10961             finish_function_try_block (stmt);
10962           else
10963             finish_try_block (stmt);
10964
10965           RECUR (TRY_HANDLERS (t));
10966           if (FN_TRY_BLOCK_P (t))
10967             finish_function_handler_sequence (stmt, compound_stmt);
10968           else
10969             finish_handler_sequence (stmt);
10970         }
10971       break;
10972
10973     case HANDLER:
10974       {
10975         tree decl = HANDLER_PARMS (t);
10976
10977         if (decl)
10978           {
10979             decl = tsubst (decl, args, complain, in_decl);
10980             /* Prevent instantiate_decl from trying to instantiate
10981                this variable.  We've already done all that needs to be
10982                done.  */
10983             if (decl != error_mark_node)
10984               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10985           }
10986         stmt = begin_handler ();
10987         finish_handler_parms (decl, stmt);
10988         RECUR (HANDLER_BODY (t));
10989         finish_handler (stmt);
10990       }
10991       break;
10992
10993     case TAG_DEFN:
10994       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10995       break;
10996
10997     case STATIC_ASSERT:
10998       {
10999         tree condition = 
11000           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11001                        args,
11002                        complain, in_decl,
11003                        /*integral_constant_expression_p=*/true);
11004         finish_static_assert (condition,
11005                               STATIC_ASSERT_MESSAGE (t),
11006                               STATIC_ASSERT_SOURCE_LOCATION (t),
11007                               /*member_p=*/false);
11008       }
11009       break;
11010
11011     case OMP_PARALLEL:
11012       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11013                                 args, complain, in_decl);
11014       stmt = begin_omp_parallel ();
11015       RECUR (OMP_PARALLEL_BODY (t));
11016       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11017         = OMP_PARALLEL_COMBINED (t);
11018       break;
11019
11020     case OMP_TASK:
11021       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11022                                 args, complain, in_decl);
11023       stmt = begin_omp_task ();
11024       RECUR (OMP_TASK_BODY (t));
11025       finish_omp_task (tmp, stmt);
11026       break;
11027
11028     case OMP_FOR:
11029       {
11030         tree clauses, body, pre_body;
11031         tree declv, initv, condv, incrv;
11032         int i;
11033
11034         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11035                                       args, complain, in_decl);
11036         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11037         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11038         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11039         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11040
11041         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11042           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11043                                    &clauses, args, complain, in_decl,
11044                                    integral_constant_expression_p);
11045
11046         stmt = begin_omp_structured_block ();
11047
11048         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11049           if (TREE_VEC_ELT (initv, i) == NULL
11050               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11051             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11052           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11053             {
11054               tree init = RECUR (TREE_VEC_ELT (initv, i));
11055               gcc_assert (init == TREE_VEC_ELT (declv, i));
11056               TREE_VEC_ELT (initv, i) = NULL_TREE;
11057             }
11058           else
11059             {
11060               tree decl_expr = TREE_VEC_ELT (initv, i);
11061               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11062               gcc_assert (init != NULL);
11063               TREE_VEC_ELT (initv, i) = RECUR (init);
11064               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11065               RECUR (decl_expr);
11066               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11067             }
11068
11069         pre_body = push_stmt_list ();
11070         RECUR (OMP_FOR_PRE_BODY (t));
11071         pre_body = pop_stmt_list (pre_body);
11072
11073         body = push_stmt_list ();
11074         RECUR (OMP_FOR_BODY (t));
11075         body = pop_stmt_list (body);
11076
11077         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11078                             body, pre_body, clauses);
11079
11080         add_stmt (finish_omp_structured_block (stmt));
11081       }
11082       break;
11083
11084     case OMP_SECTIONS:
11085     case OMP_SINGLE:
11086       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11087       stmt = push_stmt_list ();
11088       RECUR (OMP_BODY (t));
11089       stmt = pop_stmt_list (stmt);
11090
11091       t = copy_node (t);
11092       OMP_BODY (t) = stmt;
11093       OMP_CLAUSES (t) = tmp;
11094       add_stmt (t);
11095       break;
11096
11097     case OMP_SECTION:
11098     case OMP_CRITICAL:
11099     case OMP_MASTER:
11100     case OMP_ORDERED:
11101       stmt = push_stmt_list ();
11102       RECUR (OMP_BODY (t));
11103       stmt = pop_stmt_list (stmt);
11104
11105       t = copy_node (t);
11106       OMP_BODY (t) = stmt;
11107       add_stmt (t);
11108       break;
11109
11110     case OMP_ATOMIC:
11111       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11112       {
11113         tree op1 = TREE_OPERAND (t, 1);
11114         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11115         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11116         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11117       }
11118       break;
11119
11120     case EXPR_PACK_EXPANSION:
11121       error ("invalid use of pack expansion expression");
11122       return error_mark_node;
11123
11124     case NONTYPE_ARGUMENT_PACK:
11125       error ("use %<...%> to expand argument pack");
11126       return error_mark_node;
11127
11128     default:
11129       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11130
11131       return tsubst_copy_and_build (t, args, complain, in_decl,
11132                                     /*function_p=*/false,
11133                                     integral_constant_expression_p);
11134     }
11135
11136   return NULL_TREE;
11137 #undef RECUR
11138 }
11139
11140 /* T is a postfix-expression that is not being used in a function
11141    call.  Return the substituted version of T.  */
11142
11143 static tree
11144 tsubst_non_call_postfix_expression (tree t, tree args,
11145                                     tsubst_flags_t complain,
11146                                     tree in_decl)
11147 {
11148   if (TREE_CODE (t) == SCOPE_REF)
11149     t = tsubst_qualified_id (t, args, complain, in_decl,
11150                              /*done=*/false, /*address_p=*/false);
11151   else
11152     t = tsubst_copy_and_build (t, args, complain, in_decl,
11153                                /*function_p=*/false,
11154                                /*integral_constant_expression_p=*/false);
11155
11156   return t;
11157 }
11158
11159 /* Like tsubst but deals with expressions and performs semantic
11160    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11161
11162 tree
11163 tsubst_copy_and_build (tree t,
11164                        tree args,
11165                        tsubst_flags_t complain,
11166                        tree in_decl,
11167                        bool function_p,
11168                        bool integral_constant_expression_p)
11169 {
11170 #define RECUR(NODE)                                             \
11171   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11172                          /*function_p=*/false,                  \
11173                          integral_constant_expression_p)
11174
11175   tree op1;
11176
11177   if (t == NULL_TREE || t == error_mark_node)
11178     return t;
11179
11180   switch (TREE_CODE (t))
11181     {
11182     case USING_DECL:
11183       t = DECL_NAME (t);
11184       /* Fall through.  */
11185     case IDENTIFIER_NODE:
11186       {
11187         tree decl;
11188         cp_id_kind idk;
11189         bool non_integral_constant_expression_p;
11190         const char *error_msg;
11191
11192         if (IDENTIFIER_TYPENAME_P (t))
11193           {
11194             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11195             t = mangle_conv_op_name_for_type (new_type);
11196           }
11197
11198         /* Look up the name.  */
11199         decl = lookup_name (t);
11200
11201         /* By convention, expressions use ERROR_MARK_NODE to indicate
11202            failure, not NULL_TREE.  */
11203         if (decl == NULL_TREE)
11204           decl = error_mark_node;
11205
11206         decl = finish_id_expression (t, decl, NULL_TREE,
11207                                      &idk,
11208                                      integral_constant_expression_p,
11209                                      /*allow_non_integral_constant_expression_p=*/false,
11210                                      &non_integral_constant_expression_p,
11211                                      /*template_p=*/false,
11212                                      /*done=*/true,
11213                                      /*address_p=*/false,
11214                                      /*template_arg_p=*/false,
11215                                      &error_msg,
11216                                      input_location);
11217         if (error_msg)
11218           error (error_msg);
11219         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11220           decl = unqualified_name_lookup_error (decl);
11221         return decl;
11222       }
11223
11224     case TEMPLATE_ID_EXPR:
11225       {
11226         tree object;
11227         tree templ = RECUR (TREE_OPERAND (t, 0));
11228         tree targs = TREE_OPERAND (t, 1);
11229
11230         if (targs)
11231           targs = tsubst_template_args (targs, args, complain, in_decl);
11232
11233         if (TREE_CODE (templ) == COMPONENT_REF)
11234           {
11235             object = TREE_OPERAND (templ, 0);
11236             templ = TREE_OPERAND (templ, 1);
11237           }
11238         else
11239           object = NULL_TREE;
11240         templ = lookup_template_function (templ, targs);
11241
11242         if (object)
11243           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11244                          object, templ, NULL_TREE);
11245         else
11246           return baselink_for_fns (templ);
11247       }
11248
11249     case INDIRECT_REF:
11250       {
11251         tree r = RECUR (TREE_OPERAND (t, 0));
11252
11253         if (REFERENCE_REF_P (t))
11254           {
11255             /* A type conversion to reference type will be enclosed in
11256                such an indirect ref, but the substitution of the cast
11257                will have also added such an indirect ref.  */
11258             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11259               r = convert_from_reference (r);
11260           }
11261         else
11262           r = build_x_indirect_ref (r, "unary *", complain);
11263         return r;
11264       }
11265
11266     case NOP_EXPR:
11267       return build_nop
11268         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11269          RECUR (TREE_OPERAND (t, 0)));
11270
11271     case CAST_EXPR:
11272     case REINTERPRET_CAST_EXPR:
11273     case CONST_CAST_EXPR:
11274     case DYNAMIC_CAST_EXPR:
11275     case STATIC_CAST_EXPR:
11276       {
11277         tree type;
11278         tree op;
11279
11280         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11281         if (integral_constant_expression_p
11282             && !cast_valid_in_integral_constant_expression_p (type))
11283           {
11284             if (complain & tf_error)
11285               error ("a cast to a type other than an integral or "
11286                      "enumeration type cannot appear in a constant-expression");
11287             return error_mark_node; 
11288           }
11289
11290         op = RECUR (TREE_OPERAND (t, 0));
11291
11292         switch (TREE_CODE (t))
11293           {
11294           case CAST_EXPR:
11295             return build_functional_cast (type, op, complain);
11296           case REINTERPRET_CAST_EXPR:
11297             return build_reinterpret_cast (type, op, complain);
11298           case CONST_CAST_EXPR:
11299             return build_const_cast (type, op, complain);
11300           case DYNAMIC_CAST_EXPR:
11301             return build_dynamic_cast (type, op, complain);
11302           case STATIC_CAST_EXPR:
11303             return build_static_cast (type, op, complain);
11304           default:
11305             gcc_unreachable ();
11306           }
11307       }
11308
11309     case POSTDECREMENT_EXPR:
11310     case POSTINCREMENT_EXPR:
11311       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11312                                                 args, complain, in_decl);
11313       return build_x_unary_op (TREE_CODE (t), op1, complain);
11314
11315     case PREDECREMENT_EXPR:
11316     case PREINCREMENT_EXPR:
11317     case NEGATE_EXPR:
11318     case BIT_NOT_EXPR:
11319     case ABS_EXPR:
11320     case TRUTH_NOT_EXPR:
11321     case UNARY_PLUS_EXPR:  /* Unary + */
11322     case REALPART_EXPR:
11323     case IMAGPART_EXPR:
11324       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11325                                complain);
11326
11327     case ADDR_EXPR:
11328       op1 = TREE_OPERAND (t, 0);
11329       if (TREE_CODE (op1) == SCOPE_REF)
11330         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11331                                    /*done=*/true, /*address_p=*/true);
11332       else
11333         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11334                                                   in_decl);
11335       if (TREE_CODE (op1) == LABEL_DECL)
11336         return finish_label_address_expr (DECL_NAME (op1),
11337                                           EXPR_LOCATION (op1));
11338       return build_x_unary_op (ADDR_EXPR, op1, complain);
11339
11340     case PLUS_EXPR:
11341     case MINUS_EXPR:
11342     case MULT_EXPR:
11343     case TRUNC_DIV_EXPR:
11344     case CEIL_DIV_EXPR:
11345     case FLOOR_DIV_EXPR:
11346     case ROUND_DIV_EXPR:
11347     case EXACT_DIV_EXPR:
11348     case BIT_AND_EXPR:
11349     case BIT_IOR_EXPR:
11350     case BIT_XOR_EXPR:
11351     case TRUNC_MOD_EXPR:
11352     case FLOOR_MOD_EXPR:
11353     case TRUTH_ANDIF_EXPR:
11354     case TRUTH_ORIF_EXPR:
11355     case TRUTH_AND_EXPR:
11356     case TRUTH_OR_EXPR:
11357     case RSHIFT_EXPR:
11358     case LSHIFT_EXPR:
11359     case RROTATE_EXPR:
11360     case LROTATE_EXPR:
11361     case EQ_EXPR:
11362     case NE_EXPR:
11363     case MAX_EXPR:
11364     case MIN_EXPR:
11365     case LE_EXPR:
11366     case GE_EXPR:
11367     case LT_EXPR:
11368     case GT_EXPR:
11369     case MEMBER_REF:
11370     case DOTSTAR_EXPR:
11371       return build_x_binary_op
11372         (TREE_CODE (t),
11373          RECUR (TREE_OPERAND (t, 0)),
11374          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11375           ? ERROR_MARK
11376           : TREE_CODE (TREE_OPERAND (t, 0))),
11377          RECUR (TREE_OPERAND (t, 1)),
11378          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11379           ? ERROR_MARK
11380           : TREE_CODE (TREE_OPERAND (t, 1))),
11381          /*overloaded_p=*/NULL,
11382          complain);
11383
11384     case SCOPE_REF:
11385       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11386                                   /*address_p=*/false);
11387     case ARRAY_REF:
11388       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11389                                                 args, complain, in_decl);
11390       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11391
11392     case SIZEOF_EXPR:
11393       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11394         return tsubst_copy (t, args, complain, in_decl);
11395       /* Fall through */
11396       
11397     case ALIGNOF_EXPR:
11398       op1 = TREE_OPERAND (t, 0);
11399       if (!args)
11400         {
11401           /* When there are no ARGS, we are trying to evaluate a
11402              non-dependent expression from the parser.  Trying to do
11403              the substitutions may not work.  */
11404           if (!TYPE_P (op1))
11405             op1 = TREE_TYPE (op1);
11406         }
11407       else
11408         {
11409           ++cp_unevaluated_operand;
11410           ++c_inhibit_evaluation_warnings;
11411           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11412                                        /*function_p=*/false,
11413                                        /*integral_constant_expression_p=*/false);
11414           --cp_unevaluated_operand;
11415           --c_inhibit_evaluation_warnings;
11416         }
11417       if (TYPE_P (op1))
11418         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11419                                            complain & tf_error);
11420       else
11421         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11422                                            complain & tf_error);
11423
11424     case MODOP_EXPR:
11425       {
11426         tree r = build_x_modify_expr
11427           (RECUR (TREE_OPERAND (t, 0)),
11428            TREE_CODE (TREE_OPERAND (t, 1)),
11429            RECUR (TREE_OPERAND (t, 2)),
11430            complain);
11431         /* TREE_NO_WARNING must be set if either the expression was
11432            parenthesized or it uses an operator such as >>= rather
11433            than plain assignment.  In the former case, it was already
11434            set and must be copied.  In the latter case,
11435            build_x_modify_expr sets it and it must not be reset
11436            here.  */
11437         if (TREE_NO_WARNING (t))
11438           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11439         return r;
11440       }
11441
11442     case ARROW_EXPR:
11443       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11444                                                 args, complain, in_decl);
11445       /* Remember that there was a reference to this entity.  */
11446       if (DECL_P (op1))
11447         mark_used (op1);
11448       return build_x_arrow (op1);
11449
11450     case NEW_EXPR:
11451       {
11452         tree placement = RECUR (TREE_OPERAND (t, 0));
11453         tree init = RECUR (TREE_OPERAND (t, 3));
11454         VEC(tree,gc) *placement_vec;
11455         VEC(tree,gc) *init_vec;
11456         tree ret;
11457
11458         if (placement == NULL_TREE)
11459           placement_vec = NULL;
11460         else
11461           {
11462             placement_vec = make_tree_vector ();
11463             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
11464               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
11465           }
11466
11467         /* If there was an initializer in the original tree, but it
11468            instantiated to an empty list, then we should pass a
11469            non-NULL empty vector to tell build_new that it was an
11470            empty initializer() rather than no initializer.  This can
11471            only happen when the initializer is a pack expansion whose
11472            parameter packs are of length zero.  */
11473         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
11474           init_vec = NULL;
11475         else
11476           {
11477             init_vec = make_tree_vector ();
11478             if (init == void_zero_node)
11479               gcc_assert (init_vec != NULL);
11480             else
11481               {
11482                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
11483                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
11484               }
11485           }
11486
11487         ret = build_new (&placement_vec,
11488                          RECUR (TREE_OPERAND (t, 1)),
11489                          RECUR (TREE_OPERAND (t, 2)),
11490                          &init_vec,
11491                          NEW_EXPR_USE_GLOBAL (t),
11492                          complain);
11493
11494         if (placement_vec != NULL)
11495           release_tree_vector (placement_vec);
11496         if (init_vec != NULL)
11497           release_tree_vector (init_vec);
11498
11499         return ret;
11500       }
11501
11502     case DELETE_EXPR:
11503      return delete_sanity
11504        (RECUR (TREE_OPERAND (t, 0)),
11505         RECUR (TREE_OPERAND (t, 1)),
11506         DELETE_EXPR_USE_VEC (t),
11507         DELETE_EXPR_USE_GLOBAL (t));
11508
11509     case COMPOUND_EXPR:
11510       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11511                                     RECUR (TREE_OPERAND (t, 1)),
11512                                     complain);
11513
11514     case CALL_EXPR:
11515       {
11516         tree function;
11517         VEC(tree,gc) *call_args;
11518         unsigned int nargs, i;
11519         bool qualified_p;
11520         bool koenig_p;
11521         tree ret;
11522
11523         function = CALL_EXPR_FN (t);
11524         /* When we parsed the expression,  we determined whether or
11525            not Koenig lookup should be performed.  */
11526         koenig_p = KOENIG_LOOKUP_P (t);
11527         if (TREE_CODE (function) == SCOPE_REF)
11528           {
11529             qualified_p = true;
11530             function = tsubst_qualified_id (function, args, complain, in_decl,
11531                                             /*done=*/false,
11532                                             /*address_p=*/false);
11533           }
11534         else
11535           {
11536             if (TREE_CODE (function) == COMPONENT_REF)
11537               {
11538                 tree op = TREE_OPERAND (function, 1);
11539
11540                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11541                                || (BASELINK_P (op)
11542                                    && BASELINK_QUALIFIED_P (op)));
11543               }
11544             else
11545               qualified_p = false;
11546
11547             function = tsubst_copy_and_build (function, args, complain,
11548                                               in_decl,
11549                                               !qualified_p,
11550                                               integral_constant_expression_p);
11551
11552             if (BASELINK_P (function))
11553               qualified_p = true;
11554           }
11555
11556         nargs = call_expr_nargs (t);
11557         call_args = make_tree_vector ();
11558         for (i = 0; i < nargs; ++i)
11559           {
11560             tree arg = CALL_EXPR_ARG (t, i);
11561
11562             if (!PACK_EXPANSION_P (arg))
11563               VEC_safe_push (tree, gc, call_args,
11564                              RECUR (CALL_EXPR_ARG (t, i)));
11565             else
11566               {
11567                 /* Expand the pack expansion and push each entry onto
11568                    CALL_ARGS.  */
11569                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
11570                 if (TREE_CODE (arg) == TREE_VEC)
11571                   {
11572                     unsigned int len, j;
11573
11574                     len = TREE_VEC_LENGTH (arg);
11575                     for (j = 0; j < len; ++j)
11576                       {
11577                         tree value = TREE_VEC_ELT (arg, j);
11578                         if (value != NULL_TREE)
11579                           value = convert_from_reference (value);
11580                         VEC_safe_push (tree, gc, call_args, value);
11581                       }
11582                   }
11583                 else
11584                   {
11585                     /* A partial substitution.  Add one entry.  */
11586                     VEC_safe_push (tree, gc, call_args, arg);
11587                   }
11588               }
11589           }
11590
11591         /* We do not perform argument-dependent lookup if normal
11592            lookup finds a non-function, in accordance with the
11593            expected resolution of DR 218.  */
11594         if (koenig_p
11595             && ((is_overloaded_fn (function)
11596                  /* If lookup found a member function, the Koenig lookup is
11597                     not appropriate, even if an unqualified-name was used
11598                     to denote the function.  */
11599                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11600                 || TREE_CODE (function) == IDENTIFIER_NODE)
11601             /* Only do this when substitution turns a dependent call
11602                into a non-dependent call.  */
11603             && type_dependent_expression_p_push (t)
11604             && !any_type_dependent_arguments_p (call_args))
11605           function = perform_koenig_lookup (function, call_args);
11606
11607         if (TREE_CODE (function) == IDENTIFIER_NODE)
11608           {
11609             unqualified_name_lookup_error (function);
11610             release_tree_vector (call_args);
11611             return error_mark_node;
11612           }
11613
11614         /* Remember that there was a reference to this entity.  */
11615         if (DECL_P (function))
11616           mark_used (function);
11617
11618         if (TREE_CODE (function) == OFFSET_REF)
11619           ret = build_offset_ref_call_from_tree (function, &call_args);
11620         else if (TREE_CODE (function) == COMPONENT_REF)
11621           {
11622             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11623               ret = finish_call_expr (function, &call_args,
11624                                        /*disallow_virtual=*/false,
11625                                        /*koenig_p=*/false,
11626                                        complain);
11627             else
11628               ret = (build_new_method_call
11629                       (TREE_OPERAND (function, 0),
11630                        TREE_OPERAND (function, 1),
11631                        &call_args, NULL_TREE,
11632                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11633                        /*fn_p=*/NULL,
11634                        complain));
11635           }
11636         else
11637           ret = finish_call_expr (function, &call_args,
11638                                   /*disallow_virtual=*/qualified_p,
11639                                   koenig_p,
11640                                   complain);
11641
11642         release_tree_vector (call_args);
11643
11644         return ret;
11645       }
11646
11647     case COND_EXPR:
11648       return build_x_conditional_expr
11649         (RECUR (TREE_OPERAND (t, 0)),
11650          RECUR (TREE_OPERAND (t, 1)),
11651          RECUR (TREE_OPERAND (t, 2)),
11652          complain);
11653
11654     case PSEUDO_DTOR_EXPR:
11655       return finish_pseudo_destructor_expr
11656         (RECUR (TREE_OPERAND (t, 0)),
11657          RECUR (TREE_OPERAND (t, 1)),
11658          RECUR (TREE_OPERAND (t, 2)));
11659
11660     case TREE_LIST:
11661       {
11662         tree purpose, value, chain;
11663
11664         if (t == void_list_node)
11665           return t;
11666
11667         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11668             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11669           {
11670             /* We have pack expansions, so expand those and
11671                create a new list out of it.  */
11672             tree purposevec = NULL_TREE;
11673             tree valuevec = NULL_TREE;
11674             tree chain;
11675             int i, len = -1;
11676
11677             /* Expand the argument expressions.  */
11678             if (TREE_PURPOSE (t))
11679               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11680                                                  complain, in_decl);
11681             if (TREE_VALUE (t))
11682               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11683                                                complain, in_decl);
11684
11685             /* Build the rest of the list.  */
11686             chain = TREE_CHAIN (t);
11687             if (chain && chain != void_type_node)
11688               chain = RECUR (chain);
11689
11690             /* Determine the number of arguments.  */
11691             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11692               {
11693                 len = TREE_VEC_LENGTH (purposevec);
11694                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11695               }
11696             else if (TREE_CODE (valuevec) == TREE_VEC)
11697               len = TREE_VEC_LENGTH (valuevec);
11698             else
11699               {
11700                 /* Since we only performed a partial substitution into
11701                    the argument pack, we only return a single list
11702                    node.  */
11703                 if (purposevec == TREE_PURPOSE (t)
11704                     && valuevec == TREE_VALUE (t)
11705                     && chain == TREE_CHAIN (t))
11706                   return t;
11707
11708                 return tree_cons (purposevec, valuevec, chain);
11709               }
11710             
11711             /* Convert the argument vectors into a TREE_LIST */
11712             i = len;
11713             while (i > 0)
11714               {
11715                 /* Grab the Ith values.  */
11716                 i--;
11717                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11718                                      : NULL_TREE;
11719                 value 
11720                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11721                              : NULL_TREE;
11722
11723                 /* Build the list (backwards).  */
11724                 chain = tree_cons (purpose, value, chain);
11725               }
11726
11727             return chain;
11728           }
11729
11730         purpose = TREE_PURPOSE (t);
11731         if (purpose)
11732           purpose = RECUR (purpose);
11733         value = TREE_VALUE (t);
11734         if (value)
11735           value = RECUR (value);
11736         chain = TREE_CHAIN (t);
11737         if (chain && chain != void_type_node)
11738           chain = RECUR (chain);
11739         if (purpose == TREE_PURPOSE (t)
11740             && value == TREE_VALUE (t)
11741             && chain == TREE_CHAIN (t))
11742           return t;
11743         return tree_cons (purpose, value, chain);
11744       }
11745
11746     case COMPONENT_REF:
11747       {
11748         tree object;
11749         tree object_type;
11750         tree member;
11751
11752         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11753                                                      args, complain, in_decl);
11754         /* Remember that there was a reference to this entity.  */
11755         if (DECL_P (object))
11756           mark_used (object);
11757         object_type = TREE_TYPE (object);
11758
11759         member = TREE_OPERAND (t, 1);
11760         if (BASELINK_P (member))
11761           member = tsubst_baselink (member,
11762                                     non_reference (TREE_TYPE (object)),
11763                                     args, complain, in_decl);
11764         else
11765           member = tsubst_copy (member, args, complain, in_decl);
11766         if (member == error_mark_node)
11767           return error_mark_node;
11768
11769         if (object_type && !CLASS_TYPE_P (object_type))
11770           {
11771             if (SCALAR_TYPE_P (object_type))
11772               {
11773                 tree s = NULL_TREE;
11774                 tree dtor = member;
11775
11776                 if (TREE_CODE (dtor) == SCOPE_REF)
11777                   {
11778                     s = TREE_OPERAND (dtor, 0);
11779                     dtor = TREE_OPERAND (dtor, 1);
11780                   }
11781                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11782                   {
11783                     dtor = TREE_OPERAND (dtor, 0);
11784                     if (TYPE_P (dtor))
11785                       return finish_pseudo_destructor_expr (object, s, dtor);
11786                   }
11787               }
11788           }
11789         else if (TREE_CODE (member) == SCOPE_REF
11790                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11791           {
11792             tree tmpl;
11793             tree args;
11794
11795             /* Lookup the template functions now that we know what the
11796                scope is.  */
11797             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11798             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11799             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11800                                             /*is_type_p=*/false,
11801                                             /*complain=*/false);
11802             if (BASELINK_P (member))
11803               {
11804                 BASELINK_FUNCTIONS (member)
11805                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11806                               args);
11807                 member = (adjust_result_of_qualified_name_lookup
11808                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11809                            object_type));
11810               }
11811             else
11812               {
11813                 qualified_name_lookup_error (object_type, tmpl, member,
11814                                              input_location);
11815                 return error_mark_node;
11816               }
11817           }
11818         else if (TREE_CODE (member) == SCOPE_REF
11819                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11820                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11821           {
11822             if (complain & tf_error)
11823               {
11824                 if (TYPE_P (TREE_OPERAND (member, 0)))
11825                   error ("%qT is not a class or namespace",
11826                          TREE_OPERAND (member, 0));
11827                 else
11828                   error ("%qD is not a class or namespace",
11829                          TREE_OPERAND (member, 0));
11830               }
11831             return error_mark_node;
11832           }
11833         else if (TREE_CODE (member) == FIELD_DECL)
11834           return finish_non_static_data_member (member, object, NULL_TREE);
11835
11836         return finish_class_member_access_expr (object, member,
11837                                                 /*template_p=*/false,
11838                                                 complain);
11839       }
11840
11841     case THROW_EXPR:
11842       return build_throw
11843         (RECUR (TREE_OPERAND (t, 0)));
11844
11845     case CONSTRUCTOR:
11846       {
11847         VEC(constructor_elt,gc) *n;
11848         constructor_elt *ce;
11849         unsigned HOST_WIDE_INT idx;
11850         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11851         bool process_index_p;
11852         int newlen;
11853         bool need_copy_p = false;
11854         tree r;
11855
11856         if (type == error_mark_node)
11857           return error_mark_node;
11858
11859         /* digest_init will do the wrong thing if we let it.  */
11860         if (type && TYPE_PTRMEMFUNC_P (type))
11861           return t;
11862
11863         /* We do not want to process the index of aggregate
11864            initializers as they are identifier nodes which will be
11865            looked up by digest_init.  */
11866         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
11867
11868         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11869         newlen = VEC_length (constructor_elt, n);
11870         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11871           {
11872             if (ce->index && process_index_p)
11873               ce->index = RECUR (ce->index);
11874
11875             if (PACK_EXPANSION_P (ce->value))
11876               {
11877                 /* Substitute into the pack expansion.  */
11878                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11879                                                   in_decl);
11880
11881                 if (ce->value == error_mark_node)
11882                   ;
11883                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11884                   /* Just move the argument into place.  */
11885                   ce->value = TREE_VEC_ELT (ce->value, 0);
11886                 else
11887                   {
11888                     /* Update the length of the final CONSTRUCTOR
11889                        arguments vector, and note that we will need to
11890                        copy.*/
11891                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11892                     need_copy_p = true;
11893                   }
11894               }
11895             else
11896               ce->value = RECUR (ce->value);
11897           }
11898
11899         if (need_copy_p)
11900           {
11901             VEC(constructor_elt,gc) *old_n = n;
11902
11903             n = VEC_alloc (constructor_elt, gc, newlen);
11904             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11905                  idx++)
11906               {
11907                 if (TREE_CODE (ce->value) == TREE_VEC)
11908                   {
11909                     int i, len = TREE_VEC_LENGTH (ce->value);
11910                     for (i = 0; i < len; ++i)
11911                       CONSTRUCTOR_APPEND_ELT (n, 0,
11912                                               TREE_VEC_ELT (ce->value, i));
11913                   }
11914                 else
11915                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11916               }
11917           }
11918
11919         r = build_constructor (init_list_type_node, n);
11920         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
11921
11922         if (TREE_HAS_CONSTRUCTOR (t))
11923           return finish_compound_literal (type, r);
11924
11925         return r;
11926       }
11927
11928     case TYPEID_EXPR:
11929       {
11930         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11931         if (TYPE_P (operand_0))
11932           return get_typeid (operand_0);
11933         return build_typeid (operand_0);
11934       }
11935
11936     case VAR_DECL:
11937       if (!args)
11938         return t;
11939       /* Fall through */
11940
11941     case PARM_DECL:
11942       {
11943         tree r = tsubst_copy (t, args, complain, in_decl);
11944
11945         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11946           /* If the original type was a reference, we'll be wrapped in
11947              the appropriate INDIRECT_REF.  */
11948           r = convert_from_reference (r);
11949         return r;
11950       }
11951
11952     case VA_ARG_EXPR:
11953       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11954                              tsubst_copy (TREE_TYPE (t), args, complain,
11955                                           in_decl));
11956
11957     case OFFSETOF_EXPR:
11958       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11959
11960     case TRAIT_EXPR:
11961       {
11962         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11963                                   complain, in_decl);
11964
11965         tree type2 = TRAIT_EXPR_TYPE2 (t);
11966         if (type2)
11967           type2 = tsubst_copy (type2, args, complain, in_decl);
11968         
11969         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11970       }
11971
11972     case STMT_EXPR:
11973       {
11974         tree old_stmt_expr = cur_stmt_expr;
11975         tree stmt_expr = begin_stmt_expr ();
11976
11977         cur_stmt_expr = stmt_expr;
11978         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11979                      integral_constant_expression_p);
11980         stmt_expr = finish_stmt_expr (stmt_expr, false);
11981         cur_stmt_expr = old_stmt_expr;
11982
11983         return stmt_expr;
11984       }
11985
11986     case CONST_DECL:
11987       t = tsubst_copy (t, args, complain, in_decl);
11988       /* As in finish_id_expression, we resolve enumeration constants
11989          to their underlying values.  */
11990       if (TREE_CODE (t) == CONST_DECL)
11991         {
11992           used_types_insert (TREE_TYPE (t));
11993           return DECL_INITIAL (t);
11994         }
11995       return t;
11996
11997     default:
11998       /* Handle Objective-C++ constructs, if appropriate.  */
11999       {
12000         tree subst
12001           = objcp_tsubst_copy_and_build (t, args, complain,
12002                                          in_decl, /*function_p=*/false);
12003         if (subst)
12004           return subst;
12005       }
12006       return tsubst_copy (t, args, complain, in_decl);
12007     }
12008
12009 #undef RECUR
12010 }
12011
12012 /* Verify that the instantiated ARGS are valid. For type arguments,
12013    make sure that the type's linkage is ok. For non-type arguments,
12014    make sure they are constants if they are integral or enumerations.
12015    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12016
12017 static bool
12018 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12019 {
12020   if (ARGUMENT_PACK_P (t))
12021     {
12022       tree vec = ARGUMENT_PACK_ARGS (t);
12023       int len = TREE_VEC_LENGTH (vec);
12024       bool result = false;
12025       int i;
12026
12027       for (i = 0; i < len; ++i)
12028         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12029           result = true;
12030       return result;
12031     }
12032   else if (TYPE_P (t))
12033     {
12034       /* [basic.link]: A name with no linkage (notably, the name
12035          of a class or enumeration declared in a local scope)
12036          shall not be used to declare an entity with linkage.
12037          This implies that names with no linkage cannot be used as
12038          template arguments.  */
12039       tree nt = no_linkage_check (t, /*relaxed_p=*/false);
12040
12041       if (nt)
12042         {
12043           /* DR 488 makes use of a type with no linkage cause
12044              type deduction to fail.  */
12045           if (complain & tf_error)
12046             {
12047               if (TYPE_ANONYMOUS_P (nt))
12048                 error ("%qT is/uses anonymous type", t);
12049               else
12050                 error ("template argument for %qD uses local type %qT",
12051                        tmpl, t);
12052             }
12053           return true;
12054         }
12055       /* In order to avoid all sorts of complications, we do not
12056          allow variably-modified types as template arguments.  */
12057       else if (variably_modified_type_p (t, NULL_TREE))
12058         {
12059           if (complain & tf_error)
12060             error ("%qT is a variably modified type", t);
12061           return true;
12062         }
12063     }
12064   /* A non-type argument of integral or enumerated type must be a
12065      constant.  */
12066   else if (TREE_TYPE (t)
12067            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12068            && !TREE_CONSTANT (t))
12069     {
12070       if (complain & tf_error)
12071         error ("integral expression %qE is not constant", t);
12072       return true;
12073     }
12074   return false;
12075 }
12076
12077 static bool
12078 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12079 {
12080   int ix, len = DECL_NTPARMS (tmpl);
12081   bool result = false;
12082
12083   for (ix = 0; ix != len; ix++)
12084     {
12085       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12086         result = true;
12087     }
12088   if (result && (complain & tf_error))
12089     error ("  trying to instantiate %qD", tmpl);
12090   return result;
12091 }
12092
12093 /* Instantiate the indicated variable or function template TMPL with
12094    the template arguments in TARG_PTR.  */
12095
12096 tree
12097 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
12098 {
12099   tree fndecl;
12100   tree gen_tmpl;
12101   tree spec;
12102   HOST_WIDE_INT saved_processing_template_decl;
12103
12104   if (tmpl == error_mark_node)
12105     return error_mark_node;
12106
12107   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12108
12109   /* If this function is a clone, handle it specially.  */
12110   if (DECL_CLONED_FUNCTION_P (tmpl))
12111     {
12112       tree spec;
12113       tree clone;
12114
12115       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
12116                                    complain);
12117       if (spec == error_mark_node)
12118         return error_mark_node;
12119
12120       /* Look for the clone.  */
12121       FOR_EACH_CLONE (clone, spec)
12122         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12123           return clone;
12124       /* We should always have found the clone by now.  */
12125       gcc_unreachable ();
12126       return NULL_TREE;
12127     }
12128
12129   /* Check to see if we already have this specialization.  */
12130   spec = retrieve_specialization (tmpl, targ_ptr,
12131                                   /*class_specializations_p=*/false);
12132   if (spec != NULL_TREE)
12133     return spec;
12134
12135   gen_tmpl = most_general_template (tmpl);
12136   if (tmpl != gen_tmpl)
12137     {
12138       /* The TMPL is a partial instantiation.  To get a full set of
12139          arguments we must add the arguments used to perform the
12140          partial instantiation.  */
12141       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12142                                               targ_ptr);
12143
12144       /* Check to see if we already have this specialization.  */
12145       spec = retrieve_specialization (gen_tmpl, targ_ptr,
12146                                       /*class_specializations_p=*/false);
12147       if (spec != NULL_TREE)
12148         return spec;
12149     }
12150
12151   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12152                                complain))
12153     return error_mark_node;
12154
12155   /* We are building a FUNCTION_DECL, during which the access of its
12156      parameters and return types have to be checked.  However this
12157      FUNCTION_DECL which is the desired context for access checking
12158      is not built yet.  We solve this chicken-and-egg problem by
12159      deferring all checks until we have the FUNCTION_DECL.  */
12160   push_deferring_access_checks (dk_deferred);
12161
12162   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12163      (because, for example, we have encountered a non-dependent
12164      function call in the body of a template function and must now
12165      determine which of several overloaded functions will be called),
12166      within the instantiation itself we are not processing a
12167      template.  */  
12168   saved_processing_template_decl = processing_template_decl;
12169   processing_template_decl = 0;
12170   /* Substitute template parameters to obtain the specialization.  */
12171   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12172                    targ_ptr, complain, gen_tmpl);
12173   processing_template_decl = saved_processing_template_decl;
12174   if (fndecl == error_mark_node)
12175     return error_mark_node;
12176
12177   /* Now we know the specialization, compute access previously
12178      deferred.  */
12179   push_access_scope (fndecl);
12180
12181   /* Some typedefs referenced from within the template code need to be access
12182      checked at template instantiation time, i.e now. These types were
12183      added to the template at parsing time. Let's get those and perfom
12184      the acces checks then.  */
12185   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
12186   perform_deferred_access_checks ();
12187   pop_access_scope (fndecl);
12188   pop_deferring_access_checks ();
12189
12190   /* The DECL_TI_TEMPLATE should always be the immediate parent
12191      template, not the most general template.  */
12192   DECL_TI_TEMPLATE (fndecl) = tmpl;
12193
12194   /* If we've just instantiated the main entry point for a function,
12195      instantiate all the alternate entry points as well.  We do this
12196      by cloning the instantiation of the main entry point, not by
12197      instantiating the template clones.  */
12198   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12199     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12200
12201   return fndecl;
12202 }
12203
12204 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
12205    NARGS elements of the arguments that are being used when calling
12206    it.  TARGS is a vector into which the deduced template arguments
12207    are placed.
12208
12209    Return zero for success, 2 for an incomplete match that doesn't resolve
12210    all the types, and 1 for complete failure.  An error message will be
12211    printed only for an incomplete match.
12212
12213    If FN is a conversion operator, or we are trying to produce a specific
12214    specialization, RETURN_TYPE is the return type desired.
12215
12216    The EXPLICIT_TARGS are explicit template arguments provided via a
12217    template-id.
12218
12219    The parameter STRICT is one of:
12220
12221    DEDUCE_CALL:
12222      We are deducing arguments for a function call, as in
12223      [temp.deduct.call].
12224
12225    DEDUCE_CONV:
12226      We are deducing arguments for a conversion function, as in
12227      [temp.deduct.conv].
12228
12229    DEDUCE_EXACT:
12230      We are deducing arguments when doing an explicit instantiation
12231      as in [temp.explicit], when determining an explicit specialization
12232      as in [temp.expl.spec], or when taking the address of a function
12233      template, as in [temp.deduct.funcaddr].  */
12234
12235 int
12236 fn_type_unification (tree fn,
12237                      tree explicit_targs,
12238                      tree targs,
12239                      const tree *args,
12240                      unsigned int nargs,
12241                      tree return_type,
12242                      unification_kind_t strict,
12243                      int flags)
12244 {
12245   tree parms;
12246   tree fntype;
12247   int result;
12248   bool incomplete_argument_packs_p = false;
12249
12250   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12251
12252   fntype = TREE_TYPE (fn);
12253   if (explicit_targs)
12254     {
12255       /* [temp.deduct]
12256
12257          The specified template arguments must match the template
12258          parameters in kind (i.e., type, nontype, template), and there
12259          must not be more arguments than there are parameters;
12260          otherwise type deduction fails.
12261
12262          Nontype arguments must match the types of the corresponding
12263          nontype template parameters, or must be convertible to the
12264          types of the corresponding nontype parameters as specified in
12265          _temp.arg.nontype_, otherwise type deduction fails.
12266
12267          All references in the function type of the function template
12268          to the corresponding template parameters are replaced by the
12269          specified template argument values.  If a substitution in a
12270          template parameter or in the function type of the function
12271          template results in an invalid type, type deduction fails.  */
12272       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12273       int i, len = TREE_VEC_LENGTH (tparms);
12274       tree converted_args;
12275       bool incomplete = false;
12276
12277       if (explicit_targs == error_mark_node)
12278         return 1;
12279
12280       converted_args
12281         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12282                                   /*require_all_args=*/false,
12283                                   /*use_default_args=*/false));
12284       if (converted_args == error_mark_node)
12285         return 1;
12286
12287       /* Substitute the explicit args into the function type.  This is
12288          necessary so that, for instance, explicitly declared function
12289          arguments can match null pointed constants.  If we were given
12290          an incomplete set of explicit args, we must not do semantic
12291          processing during substitution as we could create partial
12292          instantiations.  */
12293       for (i = 0; i < len; i++)
12294         {
12295           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12296           bool parameter_pack = false;
12297
12298           /* Dig out the actual parm.  */
12299           if (TREE_CODE (parm) == TYPE_DECL
12300               || TREE_CODE (parm) == TEMPLATE_DECL)
12301             {
12302               parm = TREE_TYPE (parm);
12303               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12304             }
12305           else if (TREE_CODE (parm) == PARM_DECL)
12306             {
12307               parm = DECL_INITIAL (parm);
12308               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12309             }
12310
12311           if (parameter_pack)
12312             {
12313               int level, idx;
12314               tree targ;
12315               template_parm_level_and_index (parm, &level, &idx);
12316
12317               /* Mark the argument pack as "incomplete". We could
12318                  still deduce more arguments during unification.  */
12319               targ = TMPL_ARG (converted_args, level, idx);
12320               if (targ)
12321                 {
12322                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12323                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12324                     = ARGUMENT_PACK_ARGS (targ);
12325                 }
12326
12327               /* We have some incomplete argument packs.  */
12328               incomplete_argument_packs_p = true;
12329             }
12330         }
12331
12332       if (incomplete_argument_packs_p)
12333         /* Any substitution is guaranteed to be incomplete if there
12334            are incomplete argument packs, because we can still deduce
12335            more arguments.  */
12336         incomplete = 1;
12337       else
12338         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12339
12340       processing_template_decl += incomplete;
12341       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12342       processing_template_decl -= incomplete;
12343
12344       if (fntype == error_mark_node)
12345         return 1;
12346
12347       /* Place the explicitly specified arguments in TARGS.  */
12348       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12349         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12350     }
12351
12352   /* Never do unification on the 'this' parameter.  */
12353   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12354
12355   if (return_type)
12356     {
12357       tree *new_args;
12358
12359       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12360       new_args = XALLOCAVEC (tree, nargs + 1);
12361       new_args[0] = return_type;
12362       memcpy (new_args + 1, args, nargs * sizeof (tree));
12363       args = new_args;
12364       ++nargs;
12365     }
12366
12367   /* We allow incomplete unification without an error message here
12368      because the standard doesn't seem to explicitly prohibit it.  Our
12369      callers must be ready to deal with unification failures in any
12370      event.  */
12371   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12372                                   targs, parms, args, nargs, /*subr=*/0,
12373                                   strict, flags);
12374
12375   if (result == 0 && incomplete_argument_packs_p)
12376     {
12377       int i, len = NUM_TMPL_ARGS (targs);
12378
12379       /* Clear the "incomplete" flags on all argument packs.  */
12380       for (i = 0; i < len; i++)
12381         {
12382           tree arg = TREE_VEC_ELT (targs, i);
12383           if (ARGUMENT_PACK_P (arg))
12384             {
12385               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12386               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12387             }
12388         }
12389     }
12390
12391   /* Now that we have bindings for all of the template arguments,
12392      ensure that the arguments deduced for the template template
12393      parameters have compatible template parameter lists.  We cannot
12394      check this property before we have deduced all template
12395      arguments, because the template parameter types of a template
12396      template parameter might depend on prior template parameters
12397      deduced after the template template parameter.  The following
12398      ill-formed example illustrates this issue:
12399
12400        template<typename T, template<T> class C> void f(C<5>, T);
12401
12402        template<int N> struct X {};
12403
12404        void g() {
12405          f(X<5>(), 5l); // error: template argument deduction fails
12406        }
12407
12408      The template parameter list of 'C' depends on the template type
12409      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12410      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12411      time that we deduce 'C'.  */
12412   if (result == 0
12413       && !template_template_parm_bindings_ok_p 
12414            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12415     return 1;
12416
12417   if (result == 0)
12418     /* All is well so far.  Now, check:
12419
12420        [temp.deduct]
12421
12422        When all template arguments have been deduced, all uses of
12423        template parameters in nondeduced contexts are replaced with
12424        the corresponding deduced argument values.  If the
12425        substitution results in an invalid type, as described above,
12426        type deduction fails.  */
12427     {
12428       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
12429       if (substed == error_mark_node)
12430         return 1;
12431
12432       /* If we're looking for an exact match, check that what we got
12433          is indeed an exact match.  It might not be if some template
12434          parameters are used in non-deduced contexts.  */
12435       if (strict == DEDUCE_EXACT)
12436         {
12437           unsigned int i;
12438
12439           tree sarg
12440             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
12441           if (return_type)
12442             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
12443           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
12444             if (!same_type_p (args[i], TREE_VALUE (sarg)))
12445               return 1;
12446         }
12447     }
12448
12449   return result;
12450 }
12451
12452 /* Adjust types before performing type deduction, as described in
12453    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12454    sections are symmetric.  PARM is the type of a function parameter
12455    or the return type of the conversion function.  ARG is the type of
12456    the argument passed to the call, or the type of the value
12457    initialized with the result of the conversion function.
12458    ARG_EXPR is the original argument expression, which may be null.  */
12459
12460 static int
12461 maybe_adjust_types_for_deduction (unification_kind_t strict,
12462                                   tree* parm,
12463                                   tree* arg,
12464                                   tree arg_expr)
12465 {
12466   int result = 0;
12467
12468   switch (strict)
12469     {
12470     case DEDUCE_CALL:
12471       break;
12472
12473     case DEDUCE_CONV:
12474       {
12475         /* Swap PARM and ARG throughout the remainder of this
12476            function; the handling is precisely symmetric since PARM
12477            will initialize ARG rather than vice versa.  */
12478         tree* temp = parm;
12479         parm = arg;
12480         arg = temp;
12481         break;
12482       }
12483
12484     case DEDUCE_EXACT:
12485       /* There is nothing to do in this case.  */
12486       return 0;
12487
12488     default:
12489       gcc_unreachable ();
12490     }
12491
12492   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12493     {
12494       /* [temp.deduct.call]
12495
12496          If P is not a reference type:
12497
12498          --If A is an array type, the pointer type produced by the
12499          array-to-pointer standard conversion (_conv.array_) is
12500          used in place of A for type deduction; otherwise,
12501
12502          --If A is a function type, the pointer type produced by
12503          the function-to-pointer standard conversion
12504          (_conv.func_) is used in place of A for type deduction;
12505          otherwise,
12506
12507          --If A is a cv-qualified type, the top level
12508          cv-qualifiers of A's type are ignored for type
12509          deduction.  */
12510       if (TREE_CODE (*arg) == ARRAY_TYPE)
12511         *arg = build_pointer_type (TREE_TYPE (*arg));
12512       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12513         *arg = build_pointer_type (*arg);
12514       else
12515         *arg = TYPE_MAIN_VARIANT (*arg);
12516     }
12517
12518   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12519      of the form T&&, where T is a template parameter, and the argument
12520      is an lvalue, T is deduced as A& */
12521   if (TREE_CODE (*parm) == REFERENCE_TYPE
12522       && TYPE_REF_IS_RVALUE (*parm)
12523       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12524       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12525       && arg_expr && real_lvalue_p (arg_expr))
12526     *arg = build_reference_type (*arg);
12527
12528   /* [temp.deduct.call]
12529
12530      If P is a cv-qualified type, the top level cv-qualifiers
12531      of P's type are ignored for type deduction.  If P is a
12532      reference type, the type referred to by P is used for
12533      type deduction.  */
12534   *parm = TYPE_MAIN_VARIANT (*parm);
12535   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12536     {
12537       *parm = TREE_TYPE (*parm);
12538       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12539     }
12540
12541   /* DR 322. For conversion deduction, remove a reference type on parm
12542      too (which has been swapped into ARG).  */
12543   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12544     *arg = TREE_TYPE (*arg);
12545
12546   return result;
12547 }
12548
12549 /* Most parms like fn_type_unification.
12550
12551    If SUBR is 1, we're being called recursively (to unify the
12552    arguments of a function or method parameter of a function
12553    template). */
12554
12555 static int
12556 type_unification_real (tree tparms,
12557                        tree targs,
12558                        tree xparms,
12559                        const tree *xargs,
12560                        unsigned int xnargs,
12561                        int subr,
12562                        unification_kind_t strict,
12563                        int flags)
12564 {
12565   tree parm, arg, arg_expr;
12566   int i;
12567   int ntparms = TREE_VEC_LENGTH (tparms);
12568   int sub_strict;
12569   int saw_undeduced = 0;
12570   tree parms;
12571   const tree *args;
12572   unsigned int nargs;
12573   unsigned int ia;
12574
12575   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
12576   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
12577   gcc_assert (ntparms > 0);
12578
12579   switch (strict)
12580     {
12581     case DEDUCE_CALL:
12582       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12583                     | UNIFY_ALLOW_DERIVED);
12584       break;
12585
12586     case DEDUCE_CONV:
12587       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12588       break;
12589
12590     case DEDUCE_EXACT:
12591       sub_strict = UNIFY_ALLOW_NONE;
12592       break;
12593
12594     default:
12595       gcc_unreachable ();
12596     }
12597
12598  again:
12599   parms = xparms;
12600   args = xargs;
12601   nargs = xnargs;
12602
12603   ia = 0;
12604   while (parms && parms != void_list_node
12605          && ia < nargs)
12606     {
12607       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12608         break;
12609
12610       parm = TREE_VALUE (parms);
12611       parms = TREE_CHAIN (parms);
12612       arg = args[ia];
12613       ++ia;
12614       arg_expr = NULL;
12615
12616       if (arg == error_mark_node)
12617         return 1;
12618       if (arg == unknown_type_node)
12619         /* We can't deduce anything from this, but we might get all the
12620            template args from other function args.  */
12621         continue;
12622
12623       /* Conversions will be performed on a function argument that
12624          corresponds with a function parameter that contains only
12625          non-deducible template parameters and explicitly specified
12626          template parameters.  */
12627       if (!uses_template_parms (parm))
12628         {
12629           tree type;
12630
12631           if (!TYPE_P (arg))
12632             type = TREE_TYPE (arg);
12633           else
12634             type = arg;
12635
12636           if (same_type_p (parm, type))
12637             continue;
12638           if (strict != DEDUCE_EXACT
12639               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12640                                   flags))
12641             continue;
12642
12643           return 1;
12644         }
12645
12646       if (!TYPE_P (arg))
12647         {
12648           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12649           if (type_unknown_p (arg))
12650             {
12651               /* [temp.deduct.type] 
12652
12653                  A template-argument can be deduced from a pointer to
12654                  function or pointer to member function argument if
12655                  the set of overloaded functions does not contain
12656                  function templates and at most one of a set of
12657                  overloaded functions provides a unique match.  */
12658               if (resolve_overloaded_unification
12659                   (tparms, targs, parm, arg, strict, sub_strict))
12660                 continue;
12661
12662               return 1;
12663             }
12664           arg_expr = arg;
12665           arg = unlowered_expr_type (arg);
12666           if (arg == error_mark_node)
12667             return 1;
12668         }
12669
12670       {
12671         int arg_strict = sub_strict;
12672
12673         if (!subr)
12674           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12675                                                           arg_expr);
12676
12677         if (arg == init_list_type_node && arg_expr)
12678           arg = arg_expr;
12679         if (unify (tparms, targs, parm, arg, arg_strict))
12680           return 1;
12681       }
12682     }
12683
12684
12685   if (parms 
12686       && parms != void_list_node
12687       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12688     {
12689       /* Unify the remaining arguments with the pack expansion type.  */
12690       tree argvec;
12691       tree parmvec = make_tree_vec (1);
12692
12693       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12694       argvec = make_tree_vec (nargs - ia);
12695       for (i = 0; ia < nargs; ++ia, ++i)
12696         TREE_VEC_ELT (argvec, i) = args[ia];
12697
12698       /* Copy the parameter into parmvec.  */
12699       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12700       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12701                                 /*call_args_p=*/true, /*subr=*/subr))
12702         return 1;
12703
12704       /* Advance to the end of the list of parameters.  */
12705       parms = TREE_CHAIN (parms);
12706     }
12707
12708   /* Fail if we've reached the end of the parm list, and more args
12709      are present, and the parm list isn't variadic.  */
12710   if (ia < nargs && parms == void_list_node)
12711     return 1;
12712   /* Fail if parms are left and they don't have default values.  */
12713   if (parms && parms != void_list_node
12714       && TREE_PURPOSE (parms) == NULL_TREE)
12715     return 1;
12716
12717   if (!subr)
12718     for (i = 0; i < ntparms; i++)
12719       if (!TREE_VEC_ELT (targs, i))
12720         {
12721           tree tparm;
12722
12723           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12724             continue;
12725
12726           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12727
12728           /* If this is an undeduced nontype parameter that depends on
12729              a type parameter, try another pass; its type may have been
12730              deduced from a later argument than the one from which
12731              this parameter can be deduced.  */
12732           if (TREE_CODE (tparm) == PARM_DECL
12733               && uses_template_parms (TREE_TYPE (tparm))
12734               && !saw_undeduced++)
12735             goto again;
12736
12737           /* Core issue #226 (C++0x) [temp.deduct]:
12738
12739                If a template argument has not been deduced, its
12740                default template argument, if any, is used. 
12741
12742              When we are in C++98 mode, TREE_PURPOSE will either
12743              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12744              to explicitly check cxx_dialect here.  */
12745           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12746             {
12747               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
12748                                  targs, tf_none, NULL_TREE);
12749               if (arg == error_mark_node)
12750                 return 1;
12751               else
12752                 {
12753                   TREE_VEC_ELT (targs, i) = arg;
12754                   continue;
12755                 }
12756             }
12757
12758           /* If the type parameter is a parameter pack, then it will
12759              be deduced to an empty parameter pack.  */
12760           if (template_parameter_pack_p (tparm))
12761             {
12762               tree arg;
12763
12764               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12765                 {
12766                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12767                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12768                   TREE_CONSTANT (arg) = 1;
12769                 }
12770               else
12771                 arg = make_node (TYPE_ARGUMENT_PACK);
12772
12773               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12774
12775               TREE_VEC_ELT (targs, i) = arg;
12776               continue;
12777             }
12778
12779           return 2;
12780         }
12781
12782   return 0;
12783 }
12784
12785 /* Subroutine of type_unification_real.  Args are like the variables
12786    at the call site.  ARG is an overloaded function (or template-id);
12787    we try deducing template args from each of the overloads, and if
12788    only one succeeds, we go with that.  Modifies TARGS and returns
12789    true on success.  */
12790
12791 static bool
12792 resolve_overloaded_unification (tree tparms,
12793                                 tree targs,
12794                                 tree parm,
12795                                 tree arg,
12796                                 unification_kind_t strict,
12797                                 int sub_strict)
12798 {
12799   tree tempargs = copy_node (targs);
12800   int good = 0;
12801   tree goodfn = NULL_TREE;
12802   bool addr_p;
12803
12804   if (TREE_CODE (arg) == ADDR_EXPR)
12805     {
12806       arg = TREE_OPERAND (arg, 0);
12807       addr_p = true;
12808     }
12809   else
12810     addr_p = false;
12811
12812   if (TREE_CODE (arg) == COMPONENT_REF)
12813     /* Handle `&x' where `x' is some static or non-static member
12814        function name.  */
12815     arg = TREE_OPERAND (arg, 1);
12816
12817   if (TREE_CODE (arg) == OFFSET_REF)
12818     arg = TREE_OPERAND (arg, 1);
12819
12820   /* Strip baselink information.  */
12821   if (BASELINK_P (arg))
12822     arg = BASELINK_FUNCTIONS (arg);
12823
12824   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12825     {
12826       /* If we got some explicit template args, we need to plug them into
12827          the affected templates before we try to unify, in case the
12828          explicit args will completely resolve the templates in question.  */
12829
12830       tree expl_subargs = TREE_OPERAND (arg, 1);
12831       arg = TREE_OPERAND (arg, 0);
12832
12833       for (; arg; arg = OVL_NEXT (arg))
12834         {
12835           tree fn = OVL_CURRENT (arg);
12836           tree subargs, elem;
12837
12838           if (TREE_CODE (fn) != TEMPLATE_DECL)
12839             continue;
12840
12841           ++processing_template_decl;
12842           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12843                                   expl_subargs, /*check_ret=*/false);
12844           if (subargs)
12845             {
12846               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12847               if (try_one_overload (tparms, targs, tempargs, parm,
12848                                     elem, strict, sub_strict, addr_p)
12849                   && (!goodfn || !decls_match (goodfn, elem)))
12850                 {
12851                   goodfn = elem;
12852                   ++good;
12853                 }
12854             }
12855           --processing_template_decl;
12856         }
12857     }
12858   else if (TREE_CODE (arg) != OVERLOAD
12859            && TREE_CODE (arg) != FUNCTION_DECL)
12860     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12861        -- but the deduction does not succeed because the expression is
12862        not just the function on its own.  */
12863     return false;
12864   else
12865     for (; arg; arg = OVL_NEXT (arg))
12866       if (try_one_overload (tparms, targs, tempargs, parm,
12867                             TREE_TYPE (OVL_CURRENT (arg)),
12868                             strict, sub_strict, addr_p)
12869           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
12870         {
12871           goodfn = OVL_CURRENT (arg);
12872           ++good;
12873         }
12874
12875   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12876      to function or pointer to member function argument if the set of
12877      overloaded functions does not contain function templates and at most
12878      one of a set of overloaded functions provides a unique match.
12879
12880      So if we found multiple possibilities, we return success but don't
12881      deduce anything.  */
12882
12883   if (good == 1)
12884     {
12885       int i = TREE_VEC_LENGTH (targs);
12886       for (; i--; )
12887         if (TREE_VEC_ELT (tempargs, i))
12888           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12889     }
12890   if (good)
12891     return true;
12892
12893   return false;
12894 }
12895
12896 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12897    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12898    different overloads deduce different arguments for a given parm.
12899    ADDR_P is true if the expression for which deduction is being
12900    performed was of the form "& fn" rather than simply "fn".
12901
12902    Returns 1 on success.  */
12903
12904 static int
12905 try_one_overload (tree tparms,
12906                   tree orig_targs,
12907                   tree targs,
12908                   tree parm,
12909                   tree arg,
12910                   unification_kind_t strict,
12911                   int sub_strict,
12912                   bool addr_p)
12913 {
12914   int nargs;
12915   tree tempargs;
12916   int i;
12917
12918   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12919      to function or pointer to member function argument if the set of
12920      overloaded functions does not contain function templates and at most
12921      one of a set of overloaded functions provides a unique match.
12922
12923      So if this is a template, just return success.  */
12924
12925   if (uses_template_parms (arg))
12926     return 1;
12927
12928   if (TREE_CODE (arg) == METHOD_TYPE)
12929     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12930   else if (addr_p)
12931     arg = build_pointer_type (arg);
12932
12933   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12934
12935   /* We don't copy orig_targs for this because if we have already deduced
12936      some template args from previous args, unify would complain when we
12937      try to deduce a template parameter for the same argument, even though
12938      there isn't really a conflict.  */
12939   nargs = TREE_VEC_LENGTH (targs);
12940   tempargs = make_tree_vec (nargs);
12941
12942   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12943     return 0;
12944
12945   /* First make sure we didn't deduce anything that conflicts with
12946      explicitly specified args.  */
12947   for (i = nargs; i--; )
12948     {
12949       tree elt = TREE_VEC_ELT (tempargs, i);
12950       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12951
12952       if (!elt)
12953         /*NOP*/;
12954       else if (uses_template_parms (elt))
12955         /* Since we're unifying against ourselves, we will fill in
12956            template args used in the function parm list with our own
12957            template parms.  Discard them.  */
12958         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12959       else if (oldelt && !template_args_equal (oldelt, elt))
12960         return 0;
12961     }
12962
12963   for (i = nargs; i--; )
12964     {
12965       tree elt = TREE_VEC_ELT (tempargs, i);
12966
12967       if (elt)
12968         TREE_VEC_ELT (targs, i) = elt;
12969     }
12970
12971   return 1;
12972 }
12973
12974 /* PARM is a template class (perhaps with unbound template
12975    parameters).  ARG is a fully instantiated type.  If ARG can be
12976    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12977    TARGS are as for unify.  */
12978
12979 static tree
12980 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12981 {
12982   tree copy_of_targs;
12983
12984   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12985       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12986           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12987     return NULL_TREE;
12988
12989   /* We need to make a new template argument vector for the call to
12990      unify.  If we used TARGS, we'd clutter it up with the result of
12991      the attempted unification, even if this class didn't work out.
12992      We also don't want to commit ourselves to all the unifications
12993      we've already done, since unification is supposed to be done on
12994      an argument-by-argument basis.  In other words, consider the
12995      following pathological case:
12996
12997        template <int I, int J, int K>
12998        struct S {};
12999
13000        template <int I, int J>
13001        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13002
13003        template <int I, int J, int K>
13004        void f(S<I, J, K>, S<I, I, I>);
13005
13006        void g() {
13007          S<0, 0, 0> s0;
13008          S<0, 1, 2> s2;
13009
13010          f(s0, s2);
13011        }
13012
13013      Now, by the time we consider the unification involving `s2', we
13014      already know that we must have `f<0, 0, 0>'.  But, even though
13015      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13016      because there are two ways to unify base classes of S<0, 1, 2>
13017      with S<I, I, I>.  If we kept the already deduced knowledge, we
13018      would reject the possibility I=1.  */
13019   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13020
13021   /* If unification failed, we're done.  */
13022   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13023              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13024     return NULL_TREE;
13025
13026   return arg;
13027 }
13028
13029 /* Given a template type PARM and a class type ARG, find the unique
13030    base type in ARG that is an instance of PARM.  We do not examine
13031    ARG itself; only its base-classes.  If there is not exactly one
13032    appropriate base class, return NULL_TREE.  PARM may be the type of
13033    a partial specialization, as well as a plain template type.  Used
13034    by unify.  */
13035
13036 static tree
13037 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13038 {
13039   tree rval = NULL_TREE;
13040   tree binfo;
13041
13042   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13043
13044   binfo = TYPE_BINFO (complete_type (arg));
13045   if (!binfo)
13046     /* The type could not be completed.  */
13047     return NULL_TREE;
13048
13049   /* Walk in inheritance graph order.  The search order is not
13050      important, and this avoids multiple walks of virtual bases.  */
13051   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13052     {
13053       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13054
13055       if (r)
13056         {
13057           /* If there is more than one satisfactory baseclass, then:
13058
13059                [temp.deduct.call]
13060
13061               If they yield more than one possible deduced A, the type
13062               deduction fails.
13063
13064              applies.  */
13065           if (rval && !same_type_p (r, rval))
13066             return NULL_TREE;
13067
13068           rval = r;
13069         }
13070     }
13071
13072   return rval;
13073 }
13074
13075 /* Returns the level of DECL, which declares a template parameter.  */
13076
13077 static int
13078 template_decl_level (tree decl)
13079 {
13080   switch (TREE_CODE (decl))
13081     {
13082     case TYPE_DECL:
13083     case TEMPLATE_DECL:
13084       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13085
13086     case PARM_DECL:
13087       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13088
13089     default:
13090       gcc_unreachable ();
13091     }
13092   return 0;
13093 }
13094
13095 /* Decide whether ARG can be unified with PARM, considering only the
13096    cv-qualifiers of each type, given STRICT as documented for unify.
13097    Returns nonzero iff the unification is OK on that basis.  */
13098
13099 static int
13100 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13101 {
13102   int arg_quals = cp_type_quals (arg);
13103   int parm_quals = cp_type_quals (parm);
13104
13105   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13106       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13107     {
13108       /*  Although a CVR qualifier is ignored when being applied to a
13109           substituted template parameter ([8.3.2]/1 for example), that
13110           does not apply during deduction [14.8.2.4]/1, (even though
13111           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13112           this).  Except when we're allowing additional CV qualifiers
13113           at the outer level [14.8.2.1]/3,1st bullet.  */
13114       if ((TREE_CODE (arg) == REFERENCE_TYPE
13115            || TREE_CODE (arg) == FUNCTION_TYPE
13116            || TREE_CODE (arg) == METHOD_TYPE)
13117           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13118         return 0;
13119
13120       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13121           && (parm_quals & TYPE_QUAL_RESTRICT))
13122         return 0;
13123     }
13124
13125   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13126       && (arg_quals & parm_quals) != parm_quals)
13127     return 0;
13128
13129   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13130       && (parm_quals & arg_quals) != arg_quals)
13131     return 0;
13132
13133   return 1;
13134 }
13135
13136 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13137 void 
13138 template_parm_level_and_index (tree parm, int* level, int* index)
13139 {
13140   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13141       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13142       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13143     {
13144       *index = TEMPLATE_TYPE_IDX (parm);
13145       *level = TEMPLATE_TYPE_LEVEL (parm);
13146     }
13147   else
13148     {
13149       *index = TEMPLATE_PARM_IDX (parm);
13150       *level = TEMPLATE_PARM_LEVEL (parm);
13151     }
13152 }
13153
13154 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13155    expansion at the end of PACKED_PARMS. Returns 0 if the type
13156    deduction succeeds, 1 otherwise. STRICT is the same as in
13157    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13158    call argument list. We'll need to adjust the arguments to make them
13159    types. SUBR tells us if this is from a recursive call to
13160    type_unification_real.  */
13161 int
13162 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13163                       tree packed_args, int strict, bool call_args_p,
13164                       bool subr)
13165 {
13166   tree parm 
13167     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13168   tree pattern = PACK_EXPANSION_PATTERN (parm);
13169   tree pack, packs = NULL_TREE;
13170   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13171   int len = TREE_VEC_LENGTH (packed_args);
13172
13173   /* Determine the parameter packs we will be deducing from the
13174      pattern, and record their current deductions.  */
13175   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13176        pack; pack = TREE_CHAIN (pack))
13177     {
13178       tree parm_pack = TREE_VALUE (pack);
13179       int idx, level;
13180
13181       /* Determine the index and level of this parameter pack.  */
13182       template_parm_level_and_index (parm_pack, &level, &idx);
13183
13184       /* Keep track of the parameter packs and their corresponding
13185          argument packs.  */
13186       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13187       TREE_TYPE (packs) = make_tree_vec (len - start);
13188     }
13189   
13190   /* Loop through all of the arguments that have not yet been
13191      unified and unify each with the pattern.  */
13192   for (i = start; i < len; i++)
13193     {
13194       tree parm = pattern;
13195
13196       /* For each parameter pack, clear out the deduced value so that
13197          we can deduce it again.  */
13198       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13199         {
13200           int idx, level;
13201           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13202
13203           TMPL_ARG (targs, level, idx) = NULL_TREE;
13204         }
13205
13206       /* Unify the pattern with the current argument.  */
13207       {
13208         tree arg = TREE_VEC_ELT (packed_args, i);
13209         tree arg_expr = NULL_TREE;
13210         int arg_strict = strict;
13211         bool skip_arg_p = false;
13212
13213         if (call_args_p)
13214           {
13215             int sub_strict;
13216
13217             /* This mirrors what we do in type_unification_real.  */
13218             switch (strict)
13219               {
13220               case DEDUCE_CALL:
13221                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13222                               | UNIFY_ALLOW_MORE_CV_QUAL
13223                               | UNIFY_ALLOW_DERIVED);
13224                 break;
13225                 
13226               case DEDUCE_CONV:
13227                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13228                 break;
13229                 
13230               case DEDUCE_EXACT:
13231                 sub_strict = UNIFY_ALLOW_NONE;
13232                 break;
13233                 
13234               default:
13235                 gcc_unreachable ();
13236               }
13237
13238             if (!TYPE_P (arg))
13239               {
13240                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13241                 if (type_unknown_p (arg))
13242                   {
13243                     /* [temp.deduct.type] A template-argument can be
13244                        deduced from a pointer to function or pointer
13245                        to member function argument if the set of
13246                        overloaded functions does not contain function
13247                        templates and at most one of a set of
13248                        overloaded functions provides a unique
13249                        match.  */
13250
13251                     if (resolve_overloaded_unification
13252                         (tparms, targs, parm, arg,
13253                          (unification_kind_t) strict,
13254                          sub_strict)
13255                         != 0)
13256                       return 1;
13257                     skip_arg_p = true;
13258                   }
13259
13260                 if (!skip_arg_p)
13261                   {
13262                     arg_expr = arg;
13263                     arg = unlowered_expr_type (arg);
13264                     if (arg == error_mark_node)
13265                       return 1;
13266                   }
13267               }
13268       
13269             arg_strict = sub_strict;
13270
13271             if (!subr)
13272               arg_strict |= 
13273                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
13274                                                   &parm, &arg, arg_expr);
13275           }
13276
13277         if (!skip_arg_p)
13278           {
13279             if (unify (tparms, targs, parm, arg, arg_strict))
13280               return 1;
13281           }
13282       }
13283
13284       /* For each parameter pack, collect the deduced value.  */
13285       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13286         {
13287           int idx, level;
13288           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13289
13290           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13291             TMPL_ARG (targs, level, idx);
13292         }
13293     }
13294
13295   /* Verify that the results of unification with the parameter packs
13296      produce results consistent with what we've seen before, and make
13297      the deduced argument packs available.  */
13298   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13299     {
13300       tree old_pack = TREE_VALUE (pack);
13301       tree new_args = TREE_TYPE (pack);
13302       int i, len = TREE_VEC_LENGTH (new_args);
13303       bool nondeduced_p = false;
13304
13305       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13306          actually deduce anything.  */
13307       for (i = 0; i < len && !nondeduced_p; ++i)
13308         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13309           nondeduced_p = true;
13310       if (nondeduced_p)
13311         continue;
13312
13313       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13314         {
13315           /* Prepend the explicit arguments onto NEW_ARGS.  */
13316           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13317           tree old_args = new_args;
13318           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13319           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13320
13321           /* Copy the explicit arguments.  */
13322           new_args = make_tree_vec (len);
13323           for (i = 0; i < explicit_len; i++)
13324             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13325
13326           /* Copy the deduced arguments.  */
13327           for (; i < len; i++)
13328             TREE_VEC_ELT (new_args, i) =
13329               TREE_VEC_ELT (old_args, i - explicit_len);
13330         }
13331
13332       if (!old_pack)
13333         {
13334           tree result;
13335           int idx, level;
13336           
13337           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13338
13339           /* Build the deduced *_ARGUMENT_PACK.  */
13340           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13341             {
13342               result = make_node (NONTYPE_ARGUMENT_PACK);
13343               TREE_TYPE (result) = 
13344                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13345               TREE_CONSTANT (result) = 1;
13346             }
13347           else
13348             result = make_node (TYPE_ARGUMENT_PACK);
13349
13350           SET_ARGUMENT_PACK_ARGS (result, new_args);
13351
13352           /* Note the deduced argument packs for this parameter
13353              pack.  */
13354           TMPL_ARG (targs, level, idx) = result;
13355         }
13356       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13357                && (ARGUMENT_PACK_ARGS (old_pack) 
13358                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13359         {
13360           /* We only had the explicitly-provided arguments before, but
13361              now we have a complete set of arguments.  */
13362           int idx, level;
13363           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13364           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13365
13366           /* Keep the original deduced argument pack.  */
13367           TMPL_ARG (targs, level, idx) = old_pack;
13368
13369           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13370           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13371           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13372         }
13373       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13374                                     new_args))
13375         /* Inconsistent unification of this parameter pack.  */
13376         return 1;
13377       else
13378         {
13379           int idx, level;
13380           
13381           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13382
13383           /* Keep the original deduced argument pack.  */
13384           TMPL_ARG (targs, level, idx) = old_pack;
13385         }
13386     }
13387
13388   return 0;
13389 }
13390
13391 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13392    set of template parameters to a template.  TARGS is the bindings
13393    for those template parameters, as determined thus far; TARGS may
13394    include template arguments for outer levels of template parameters
13395    as well.  PARM is a parameter to a template function, or a
13396    subcomponent of that parameter; ARG is the corresponding argument.
13397    This function attempts to match PARM with ARG in a manner
13398    consistent with the existing assignments in TARGS.  If more values
13399    are deduced, then TARGS is updated.
13400
13401    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13402    parameter STRICT is a bitwise or of the following flags:
13403
13404      UNIFY_ALLOW_NONE:
13405        Require an exact match between PARM and ARG.
13406      UNIFY_ALLOW_MORE_CV_QUAL:
13407        Allow the deduced ARG to be more cv-qualified (by qualification
13408        conversion) than ARG.
13409      UNIFY_ALLOW_LESS_CV_QUAL:
13410        Allow the deduced ARG to be less cv-qualified than ARG.
13411      UNIFY_ALLOW_DERIVED:
13412        Allow the deduced ARG to be a template base class of ARG,
13413        or a pointer to a template base class of the type pointed to by
13414        ARG.
13415      UNIFY_ALLOW_INTEGER:
13416        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13417        case for more information.
13418      UNIFY_ALLOW_OUTER_LEVEL:
13419        This is the outermost level of a deduction. Used to determine validity
13420        of qualification conversions. A valid qualification conversion must
13421        have const qualified pointers leading up to the inner type which
13422        requires additional CV quals, except at the outer level, where const
13423        is not required [conv.qual]. It would be normal to set this flag in
13424        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13425      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13426        This is the outermost level of a deduction, and PARM can be more CV
13427        qualified at this point.
13428      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13429        This is the outermost level of a deduction, and PARM can be less CV
13430        qualified at this point.  */
13431
13432 static int
13433 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13434 {
13435   int idx;
13436   tree targ;
13437   tree tparm;
13438   int strict_in = strict;
13439
13440   /* I don't think this will do the right thing with respect to types.
13441      But the only case I've seen it in so far has been array bounds, where
13442      signedness is the only information lost, and I think that will be
13443      okay.  */
13444   while (TREE_CODE (parm) == NOP_EXPR)
13445     parm = TREE_OPERAND (parm, 0);
13446
13447   if (arg == error_mark_node)
13448     return 1;
13449   if (arg == unknown_type_node
13450       || arg == init_list_type_node)
13451     /* We can't deduce anything from this, but we might get all the
13452        template args from other function args.  */
13453     return 0;
13454
13455   /* If PARM uses template parameters, then we can't bail out here,
13456      even if ARG == PARM, since we won't record unifications for the
13457      template parameters.  We might need them if we're trying to
13458      figure out which of two things is more specialized.  */
13459   if (arg == parm && !uses_template_parms (parm))
13460     return 0;
13461
13462   /* Handle init lists early, so the rest of the function can assume
13463      we're dealing with a type. */
13464   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
13465     {
13466       tree elt, elttype;
13467       unsigned i;
13468
13469       if (!is_std_init_list (parm))
13470         /* We can only deduce from an initializer list argument if the
13471            parameter is std::initializer_list; otherwise this is a
13472            non-deduced context. */
13473         return 0;
13474
13475       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
13476
13477       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
13478         {
13479           int elt_strict = strict;
13480           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
13481             {
13482               tree type = TREE_TYPE (elt);
13483               /* It should only be possible to get here for a call.  */
13484               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
13485               elt_strict |= maybe_adjust_types_for_deduction
13486                 (DEDUCE_CALL, &elttype, &type, elt);
13487               elt = type;
13488             }
13489
13490           if (unify (tparms, targs, elttype, elt, elt_strict))
13491             return 1;
13492         }
13493       return 0;
13494     }
13495
13496   /* Immediately reject some pairs that won't unify because of
13497      cv-qualification mismatches.  */
13498   if (TREE_CODE (arg) == TREE_CODE (parm)
13499       && TYPE_P (arg)
13500       /* It is the elements of the array which hold the cv quals of an array
13501          type, and the elements might be template type parms. We'll check
13502          when we recurse.  */
13503       && TREE_CODE (arg) != ARRAY_TYPE
13504       /* We check the cv-qualifiers when unifying with template type
13505          parameters below.  We want to allow ARG `const T' to unify with
13506          PARM `T' for example, when computing which of two templates
13507          is more specialized, for example.  */
13508       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
13509       && !check_cv_quals_for_unify (strict_in, arg, parm))
13510     return 1;
13511
13512   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
13513       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
13514     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
13515   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
13516   strict &= ~UNIFY_ALLOW_DERIVED;
13517   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13518   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
13519
13520   switch (TREE_CODE (parm))
13521     {
13522     case TYPENAME_TYPE:
13523     case SCOPE_REF:
13524     case UNBOUND_CLASS_TEMPLATE:
13525       /* In a type which contains a nested-name-specifier, template
13526          argument values cannot be deduced for template parameters used
13527          within the nested-name-specifier.  */
13528       return 0;
13529
13530     case TEMPLATE_TYPE_PARM:
13531     case TEMPLATE_TEMPLATE_PARM:
13532     case BOUND_TEMPLATE_TEMPLATE_PARM:
13533       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13534       if (tparm == error_mark_node)
13535         return 1;
13536
13537       if (TEMPLATE_TYPE_LEVEL (parm)
13538           != template_decl_level (tparm))
13539         /* The PARM is not one we're trying to unify.  Just check
13540            to see if it matches ARG.  */
13541         return (TREE_CODE (arg) == TREE_CODE (parm)
13542                 && same_type_p (parm, arg)) ? 0 : 1;
13543       idx = TEMPLATE_TYPE_IDX (parm);
13544       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13545       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
13546
13547       /* Check for mixed types and values.  */
13548       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13549            && TREE_CODE (tparm) != TYPE_DECL)
13550           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13551               && TREE_CODE (tparm) != TEMPLATE_DECL))
13552         return 1;
13553
13554       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13555         {
13556           /* ARG must be constructed from a template class or a template
13557              template parameter.  */
13558           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
13559               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
13560             return 1;
13561
13562           {
13563             tree parmvec = TYPE_TI_ARGS (parm);
13564             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
13565             tree parm_parms 
13566               = DECL_INNERMOST_TEMPLATE_PARMS
13567                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
13568             int i, len;
13569             int parm_variadic_p = 0;
13570
13571             /* The resolution to DR150 makes clear that default
13572                arguments for an N-argument may not be used to bind T
13573                to a template template parameter with fewer than N
13574                parameters.  It is not safe to permit the binding of
13575                default arguments as an extension, as that may change
13576                the meaning of a conforming program.  Consider:
13577
13578                   struct Dense { static const unsigned int dim = 1; };
13579
13580                   template <template <typename> class View,
13581                             typename Block>
13582                   void operator+(float, View<Block> const&);
13583
13584                   template <typename Block,
13585                             unsigned int Dim = Block::dim>
13586                   struct Lvalue_proxy { operator float() const; };
13587
13588                   void
13589                   test_1d (void) {
13590                     Lvalue_proxy<Dense> p;
13591                     float b;
13592                     b + p;
13593                   }
13594
13595               Here, if Lvalue_proxy is permitted to bind to View, then
13596               the global operator+ will be used; if they are not, the
13597               Lvalue_proxy will be converted to float.  */
13598             if (coerce_template_parms (parm_parms,
13599                                        argvec,
13600                                        TYPE_TI_TEMPLATE (parm),
13601                                        tf_none,
13602                                        /*require_all_args=*/true,
13603                                        /*use_default_args=*/false)
13604                 == error_mark_node)
13605               return 1;
13606
13607             /* Deduce arguments T, i from TT<T> or TT<i>.
13608                We check each element of PARMVEC and ARGVEC individually
13609                rather than the whole TREE_VEC since they can have
13610                different number of elements.  */
13611
13612             parmvec = expand_template_argument_pack (parmvec);
13613             argvec = expand_template_argument_pack (argvec);
13614
13615             len = TREE_VEC_LENGTH (parmvec);
13616
13617             /* Check if the parameters end in a pack, making them
13618                variadic.  */
13619             if (len > 0
13620                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
13621               parm_variadic_p = 1;
13622             
13623             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
13624               return 1;
13625
13626              for (i = 0; i < len - parm_variadic_p; ++i)
13627               {
13628                 if (unify (tparms, targs,
13629                            TREE_VEC_ELT (parmvec, i),
13630                            TREE_VEC_ELT (argvec, i),
13631                            UNIFY_ALLOW_NONE))
13632                   return 1;
13633               }
13634
13635             if (parm_variadic_p
13636                 && unify_pack_expansion (tparms, targs,
13637                                          parmvec, argvec,
13638                                          UNIFY_ALLOW_NONE,
13639                                          /*call_args_p=*/false,
13640                                          /*subr=*/false))
13641               return 1;
13642           }
13643           arg = TYPE_TI_TEMPLATE (arg);
13644
13645           /* Fall through to deduce template name.  */
13646         }
13647
13648       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13649           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13650         {
13651           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13652
13653           /* Simple cases: Value already set, does match or doesn't.  */
13654           if (targ != NULL_TREE && template_args_equal (targ, arg))
13655             return 0;
13656           else if (targ)
13657             return 1;
13658         }
13659       else
13660         {
13661           /* If PARM is `const T' and ARG is only `int', we don't have
13662              a match unless we are allowing additional qualification.
13663              If ARG is `const int' and PARM is just `T' that's OK;
13664              that binds `const int' to `T'.  */
13665           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13666                                          arg, parm))
13667             return 1;
13668
13669           /* Consider the case where ARG is `const volatile int' and
13670              PARM is `const T'.  Then, T should be `volatile int'.  */
13671           arg = cp_build_qualified_type_real
13672             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13673           if (arg == error_mark_node)
13674             return 1;
13675
13676           /* Simple cases: Value already set, does match or doesn't.  */
13677           if (targ != NULL_TREE && same_type_p (targ, arg))
13678             return 0;
13679           else if (targ)
13680             return 1;
13681
13682           /* Make sure that ARG is not a variable-sized array.  (Note
13683              that were talking about variable-sized arrays (like
13684              `int[n]'), rather than arrays of unknown size (like
13685              `int[]').)  We'll get very confused by such a type since
13686              the bound of the array will not be computable in an
13687              instantiation.  Besides, such types are not allowed in
13688              ISO C++, so we can do as we please here.  */
13689           if (variably_modified_type_p (arg, NULL_TREE))
13690             return 1;
13691
13692           /* Strip typedefs as in convert_template_argument.  */
13693           arg = strip_typedefs (arg);
13694         }
13695
13696       /* If ARG is a parameter pack or an expansion, we cannot unify
13697          against it unless PARM is also a parameter pack.  */
13698       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13699           && !template_parameter_pack_p (parm))
13700         return 1;
13701
13702       /* If the argument deduction results is a METHOD_TYPE,
13703          then there is a problem.
13704          METHOD_TYPE doesn't map to any real C++ type the result of
13705          the deduction can not be of that type.  */
13706       if (TREE_CODE (arg) == METHOD_TYPE)
13707         return 1;
13708
13709       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13710       return 0;
13711
13712     case TEMPLATE_PARM_INDEX:
13713       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13714       if (tparm == error_mark_node)
13715         return 1;
13716
13717       if (TEMPLATE_PARM_LEVEL (parm)
13718           != template_decl_level (tparm))
13719         /* The PARM is not one we're trying to unify.  Just check
13720            to see if it matches ARG.  */
13721         return !(TREE_CODE (arg) == TREE_CODE (parm)
13722                  && cp_tree_equal (parm, arg));
13723
13724       idx = TEMPLATE_PARM_IDX (parm);
13725       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13726
13727       if (targ)
13728         return !cp_tree_equal (targ, arg);
13729
13730       /* [temp.deduct.type] If, in the declaration of a function template
13731          with a non-type template-parameter, the non-type
13732          template-parameter is used in an expression in the function
13733          parameter-list and, if the corresponding template-argument is
13734          deduced, the template-argument type shall match the type of the
13735          template-parameter exactly, except that a template-argument
13736          deduced from an array bound may be of any integral type.
13737          The non-type parameter might use already deduced type parameters.  */
13738       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13739       if (!TREE_TYPE (arg))
13740         /* Template-parameter dependent expression.  Just accept it for now.
13741            It will later be processed in convert_template_argument.  */
13742         ;
13743       else if (same_type_p (TREE_TYPE (arg), tparm))
13744         /* OK */;
13745       else if ((strict & UNIFY_ALLOW_INTEGER)
13746                && (TREE_CODE (tparm) == INTEGER_TYPE
13747                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13748         /* Convert the ARG to the type of PARM; the deduced non-type
13749            template argument must exactly match the types of the
13750            corresponding parameter.  */
13751         arg = fold (build_nop (tparm, arg));
13752       else if (uses_template_parms (tparm))
13753         /* We haven't deduced the type of this parameter yet.  Try again
13754            later.  */
13755         return 0;
13756       else
13757         return 1;
13758
13759       /* If ARG is a parameter pack or an expansion, we cannot unify
13760          against it unless PARM is also a parameter pack.  */
13761       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13762           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13763         return 1;
13764
13765       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13766       return 0;
13767
13768     case PTRMEM_CST:
13769      {
13770         /* A pointer-to-member constant can be unified only with
13771          another constant.  */
13772       if (TREE_CODE (arg) != PTRMEM_CST)
13773         return 1;
13774
13775       /* Just unify the class member. It would be useless (and possibly
13776          wrong, depending on the strict flags) to unify also
13777          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13778          arg refer to the same variable, even if through different
13779          classes. For instance:
13780
13781          struct A { int x; };
13782          struct B : A { };
13783
13784          Unification of &A::x and &B::x must succeed.  */
13785       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13786                     PTRMEM_CST_MEMBER (arg), strict);
13787      }
13788
13789     case POINTER_TYPE:
13790       {
13791         if (TREE_CODE (arg) != POINTER_TYPE)
13792           return 1;
13793
13794         /* [temp.deduct.call]
13795
13796            A can be another pointer or pointer to member type that can
13797            be converted to the deduced A via a qualification
13798            conversion (_conv.qual_).
13799
13800            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13801            This will allow for additional cv-qualification of the
13802            pointed-to types if appropriate.  */
13803
13804         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13805           /* The derived-to-base conversion only persists through one
13806              level of pointers.  */
13807           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13808
13809         return unify (tparms, targs, TREE_TYPE (parm),
13810                       TREE_TYPE (arg), strict);
13811       }
13812
13813     case REFERENCE_TYPE:
13814       if (TREE_CODE (arg) != REFERENCE_TYPE)
13815         return 1;
13816       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13817                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13818
13819     case ARRAY_TYPE:
13820       if (TREE_CODE (arg) != ARRAY_TYPE)
13821         return 1;
13822       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13823           != (TYPE_DOMAIN (arg) == NULL_TREE))
13824         return 1;
13825       if (TYPE_DOMAIN (parm) != NULL_TREE)
13826         {
13827           tree parm_max;
13828           tree arg_max;
13829           bool parm_cst;
13830           bool arg_cst;
13831
13832           /* Our representation of array types uses "N - 1" as the
13833              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13834              not an integer constant.  We cannot unify arbitrarily
13835              complex expressions, so we eliminate the MINUS_EXPRs
13836              here.  */
13837           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13838           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13839           if (!parm_cst)
13840             {
13841               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13842               parm_max = TREE_OPERAND (parm_max, 0);
13843             }
13844           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13845           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13846           if (!arg_cst)
13847             {
13848               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13849                  trying to unify the type of a variable with the type
13850                  of a template parameter.  For example:
13851
13852                    template <unsigned int N>
13853                    void f (char (&) [N]);
13854                    int g(); 
13855                    void h(int i) {
13856                      char a[g(i)];
13857                      f(a); 
13858                    }
13859
13860                 Here, the type of the ARG will be "int [g(i)]", and
13861                 may be a SAVE_EXPR, etc.  */
13862               if (TREE_CODE (arg_max) != MINUS_EXPR)
13863                 return 1;
13864               arg_max = TREE_OPERAND (arg_max, 0);
13865             }
13866
13867           /* If only one of the bounds used a MINUS_EXPR, compensate
13868              by adding one to the other bound.  */
13869           if (parm_cst && !arg_cst)
13870             parm_max = fold_build2 (PLUS_EXPR,
13871                                     integer_type_node,
13872                                     parm_max,
13873                                     integer_one_node);
13874           else if (arg_cst && !parm_cst)
13875             arg_max = fold_build2 (PLUS_EXPR,
13876                                    integer_type_node,
13877                                    arg_max,
13878                                    integer_one_node);
13879
13880           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13881             return 1;
13882         }
13883       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13884                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13885
13886     case REAL_TYPE:
13887     case COMPLEX_TYPE:
13888     case VECTOR_TYPE:
13889     case INTEGER_TYPE:
13890     case BOOLEAN_TYPE:
13891     case ENUMERAL_TYPE:
13892     case VOID_TYPE:
13893       if (TREE_CODE (arg) != TREE_CODE (parm))
13894         return 1;
13895
13896       /* We have already checked cv-qualification at the top of the
13897          function.  */
13898       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13899         return 1;
13900
13901       /* As far as unification is concerned, this wins.  Later checks
13902          will invalidate it if necessary.  */
13903       return 0;
13904
13905       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13906       /* Type INTEGER_CST can come from ordinary constant template args.  */
13907     case INTEGER_CST:
13908       while (TREE_CODE (arg) == NOP_EXPR)
13909         arg = TREE_OPERAND (arg, 0);
13910
13911       if (TREE_CODE (arg) != INTEGER_CST)
13912         return 1;
13913       return !tree_int_cst_equal (parm, arg);
13914
13915     case TREE_VEC:
13916       {
13917         int i;
13918         if (TREE_CODE (arg) != TREE_VEC)
13919           return 1;
13920         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13921           return 1;
13922         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13923           if (unify (tparms, targs,
13924                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13925                      UNIFY_ALLOW_NONE))
13926             return 1;
13927         return 0;
13928       }
13929
13930     case RECORD_TYPE:
13931     case UNION_TYPE:
13932       if (TREE_CODE (arg) != TREE_CODE (parm))
13933         return 1;
13934
13935       if (TYPE_PTRMEMFUNC_P (parm))
13936         {
13937           if (!TYPE_PTRMEMFUNC_P (arg))
13938             return 1;
13939
13940           return unify (tparms, targs,
13941                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13942                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13943                         strict);
13944         }
13945
13946       if (CLASSTYPE_TEMPLATE_INFO (parm))
13947         {
13948           tree t = NULL_TREE;
13949
13950           if (strict_in & UNIFY_ALLOW_DERIVED)
13951             {
13952               /* First, we try to unify the PARM and ARG directly.  */
13953               t = try_class_unification (tparms, targs,
13954                                          parm, arg);
13955
13956               if (!t)
13957                 {
13958                   /* Fallback to the special case allowed in
13959                      [temp.deduct.call]:
13960
13961                        If P is a class, and P has the form
13962                        template-id, then A can be a derived class of
13963                        the deduced A.  Likewise, if P is a pointer to
13964                        a class of the form template-id, A can be a
13965                        pointer to a derived class pointed to by the
13966                        deduced A.  */
13967                   t = get_template_base (tparms, targs, parm, arg);
13968
13969                   if (!t)
13970                     return 1;
13971                 }
13972             }
13973           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13974                    && (CLASSTYPE_TI_TEMPLATE (parm)
13975                        == CLASSTYPE_TI_TEMPLATE (arg)))
13976             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13977                Then, we should unify `int' and `U'.  */
13978             t = arg;
13979           else
13980             /* There's no chance of unification succeeding.  */
13981             return 1;
13982
13983           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13984                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13985         }
13986       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13987         return 1;
13988       return 0;
13989
13990     case METHOD_TYPE:
13991     case FUNCTION_TYPE:
13992       {
13993         unsigned int nargs;
13994         tree *args;
13995         tree a;
13996         unsigned int i;
13997
13998         if (TREE_CODE (arg) != TREE_CODE (parm))
13999           return 1;
14000
14001         /* CV qualifications for methods can never be deduced, they must
14002            match exactly.  We need to check them explicitly here,
14003            because type_unification_real treats them as any other
14004            cv-qualified parameter.  */
14005         if (TREE_CODE (parm) == METHOD_TYPE
14006             && (!check_cv_quals_for_unify
14007                 (UNIFY_ALLOW_NONE,
14008                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14009                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14010           return 1;
14011
14012         if (unify (tparms, targs, TREE_TYPE (parm),
14013                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14014           return 1;
14015
14016         nargs = list_length (TYPE_ARG_TYPES (arg));
14017         args = XALLOCAVEC (tree, nargs);
14018         for (a = TYPE_ARG_TYPES (arg), i = 0;
14019              a != NULL_TREE && a != void_list_node;
14020              a = TREE_CHAIN (a), ++i)
14021           args[i] = TREE_VALUE (a);
14022         nargs = i;
14023
14024         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14025                                       args, nargs, 1, DEDUCE_EXACT,
14026                                       LOOKUP_NORMAL);
14027       }
14028
14029     case OFFSET_TYPE:
14030       /* Unify a pointer to member with a pointer to member function, which
14031          deduces the type of the member as a function type. */
14032       if (TYPE_PTRMEMFUNC_P (arg))
14033         {
14034           tree method_type;
14035           tree fntype;
14036           cp_cv_quals cv_quals;
14037
14038           /* Check top-level cv qualifiers */
14039           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14040             return 1;
14041
14042           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14043                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14044             return 1;
14045
14046           /* Determine the type of the function we are unifying against. */
14047           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14048           fntype =
14049             build_function_type (TREE_TYPE (method_type),
14050                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14051
14052           /* Extract the cv-qualifiers of the member function from the
14053              implicit object parameter and place them on the function
14054              type to be restored later. */
14055           cv_quals =
14056             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14057           fntype = build_qualified_type (fntype, cv_quals);
14058           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14059         }
14060
14061       if (TREE_CODE (arg) != OFFSET_TYPE)
14062         return 1;
14063       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14064                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14065         return 1;
14066       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14067                     strict);
14068
14069     case CONST_DECL:
14070       if (DECL_TEMPLATE_PARM_P (parm))
14071         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14072       if (arg != integral_constant_value (parm))
14073         return 1;
14074       return 0;
14075
14076     case FIELD_DECL:
14077     case TEMPLATE_DECL:
14078       /* Matched cases are handled by the ARG == PARM test above.  */
14079       return 1;
14080
14081     case TYPE_ARGUMENT_PACK:
14082     case NONTYPE_ARGUMENT_PACK:
14083       {
14084         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14085         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14086         int i, len = TREE_VEC_LENGTH (packed_parms);
14087         int argslen = TREE_VEC_LENGTH (packed_args);
14088         int parm_variadic_p = 0;
14089
14090         for (i = 0; i < len; ++i)
14091           {
14092             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14093               {
14094                 if (i == len - 1)
14095                   /* We can unify against something with a trailing
14096                      parameter pack.  */
14097                   parm_variadic_p = 1;
14098                 else
14099                   /* Since there is something following the pack
14100                      expansion, we cannot unify this template argument
14101                      list.  */
14102                   return 0;
14103               }
14104           }
14105           
14106
14107         /* If we don't have enough arguments to satisfy the parameters
14108            (not counting the pack expression at the end), or we have
14109            too many arguments for a parameter list that doesn't end in
14110            a pack expression, we can't unify.  */
14111         if (argslen < (len - parm_variadic_p)
14112             || (argslen > len && !parm_variadic_p))
14113           return 1;
14114
14115         /* Unify all of the parameters that precede the (optional)
14116            pack expression.  */
14117         for (i = 0; i < len - parm_variadic_p; ++i)
14118           {
14119             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14120                        TREE_VEC_ELT (packed_args, i), strict))
14121               return 1;
14122           }
14123
14124         if (parm_variadic_p)
14125           return unify_pack_expansion (tparms, targs, 
14126                                        packed_parms, packed_args,
14127                                        strict, /*call_args_p=*/false,
14128                                        /*subr=*/false);
14129         return 0;
14130       }
14131
14132       break;
14133
14134     case TYPEOF_TYPE:
14135     case DECLTYPE_TYPE:
14136       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14137          nodes.  */
14138       return 0;
14139
14140     case ERROR_MARK:
14141       /* Unification fails if we hit an error node.  */
14142       return 1;
14143
14144     default:
14145       gcc_assert (EXPR_P (parm));
14146
14147       /* We must be looking at an expression.  This can happen with
14148          something like:
14149
14150            template <int I>
14151            void foo(S<I>, S<I + 2>);
14152
14153          This is a "nondeduced context":
14154
14155            [deduct.type]
14156
14157            The nondeduced contexts are:
14158
14159            --A type that is a template-id in which one or more of
14160              the template-arguments is an expression that references
14161              a template-parameter.
14162
14163          In these cases, we assume deduction succeeded, but don't
14164          actually infer any unifications.  */
14165
14166       if (!uses_template_parms (parm)
14167           && !template_args_equal (parm, arg))
14168         return 1;
14169       else
14170         return 0;
14171     }
14172 }
14173 \f
14174 /* Note that DECL can be defined in this translation unit, if
14175    required.  */
14176
14177 static void
14178 mark_definable (tree decl)
14179 {
14180   tree clone;
14181   DECL_NOT_REALLY_EXTERN (decl) = 1;
14182   FOR_EACH_CLONE (clone, decl)
14183     DECL_NOT_REALLY_EXTERN (clone) = 1;
14184 }
14185
14186 /* Called if RESULT is explicitly instantiated, or is a member of an
14187    explicitly instantiated class.  */
14188
14189 void
14190 mark_decl_instantiated (tree result, int extern_p)
14191 {
14192   SET_DECL_EXPLICIT_INSTANTIATION (result);
14193
14194   /* If this entity has already been written out, it's too late to
14195      make any modifications.  */
14196   if (TREE_ASM_WRITTEN (result))
14197     return;
14198
14199   if (TREE_CODE (result) != FUNCTION_DECL)
14200     /* The TREE_PUBLIC flag for function declarations will have been
14201        set correctly by tsubst.  */
14202     TREE_PUBLIC (result) = 1;
14203
14204   /* This might have been set by an earlier implicit instantiation.  */
14205   DECL_COMDAT (result) = 0;
14206
14207   if (extern_p)
14208     DECL_NOT_REALLY_EXTERN (result) = 0;
14209   else
14210     {
14211       mark_definable (result);
14212       /* Always make artificials weak.  */
14213       if (DECL_ARTIFICIAL (result) && flag_weak)
14214         comdat_linkage (result);
14215       /* For WIN32 we also want to put explicit instantiations in
14216          linkonce sections.  */
14217       else if (TREE_PUBLIC (result))
14218         maybe_make_one_only (result);
14219     }
14220
14221   /* If EXTERN_P, then this function will not be emitted -- unless
14222      followed by an explicit instantiation, at which point its linkage
14223      will be adjusted.  If !EXTERN_P, then this function will be
14224      emitted here.  In neither circumstance do we want
14225      import_export_decl to adjust the linkage.  */
14226   DECL_INTERFACE_KNOWN (result) = 1;
14227 }
14228
14229 /* Given two function templates PAT1 and PAT2, return:
14230
14231    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14232    -1 if PAT2 is more specialized than PAT1.
14233    0 if neither is more specialized.
14234
14235    LEN indicates the number of parameters we should consider
14236    (defaulted parameters should not be considered).
14237
14238    The 1998 std underspecified function template partial ordering, and
14239    DR214 addresses the issue.  We take pairs of arguments, one from
14240    each of the templates, and deduce them against each other.  One of
14241    the templates will be more specialized if all the *other*
14242    template's arguments deduce against its arguments and at least one
14243    of its arguments *does* *not* deduce against the other template's
14244    corresponding argument.  Deduction is done as for class templates.
14245    The arguments used in deduction have reference and top level cv
14246    qualifiers removed.  Iff both arguments were originally reference
14247    types *and* deduction succeeds in both directions, the template
14248    with the more cv-qualified argument wins for that pairing (if
14249    neither is more cv-qualified, they both are equal).  Unlike regular
14250    deduction, after all the arguments have been deduced in this way,
14251    we do *not* verify the deduced template argument values can be
14252    substituted into non-deduced contexts, nor do we have to verify
14253    that all template arguments have been deduced.  */
14254
14255 int
14256 more_specialized_fn (tree pat1, tree pat2, int len)
14257 {
14258   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
14259   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
14260   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
14261   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
14262   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
14263   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
14264   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
14265   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
14266   int better1 = 0;
14267   int better2 = 0;
14268
14269   /* Remove the this parameter from non-static member functions.  If
14270      one is a non-static member function and the other is not a static
14271      member function, remove the first parameter from that function
14272      also.  This situation occurs for operator functions where we
14273      locate both a member function (with this pointer) and non-member
14274      operator (with explicit first operand).  */
14275   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
14276     {
14277       len--; /* LEN is the number of significant arguments for DECL1 */
14278       args1 = TREE_CHAIN (args1);
14279       if (!DECL_STATIC_FUNCTION_P (decl2))
14280         args2 = TREE_CHAIN (args2);
14281     }
14282   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
14283     {
14284       args2 = TREE_CHAIN (args2);
14285       if (!DECL_STATIC_FUNCTION_P (decl1))
14286         {
14287           len--;
14288           args1 = TREE_CHAIN (args1);
14289         }
14290     }
14291
14292   /* If only one is a conversion operator, they are unordered.  */
14293   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
14294     return 0;
14295
14296   /* Consider the return type for a conversion function */
14297   if (DECL_CONV_FN_P (decl1))
14298     {
14299       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
14300       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
14301       len++;
14302     }
14303
14304   processing_template_decl++;
14305
14306   while (len--
14307          /* Stop when an ellipsis is seen.  */
14308          && args1 != NULL_TREE && args2 != NULL_TREE)
14309     {
14310       tree arg1 = TREE_VALUE (args1);
14311       tree arg2 = TREE_VALUE (args2);
14312       int deduce1, deduce2;
14313       int quals1 = -1;
14314       int quals2 = -1;
14315
14316       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14317           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14318         {
14319           /* When both arguments are pack expansions, we need only
14320              unify the patterns themselves.  */
14321           arg1 = PACK_EXPANSION_PATTERN (arg1);
14322           arg2 = PACK_EXPANSION_PATTERN (arg2);
14323
14324           /* This is the last comparison we need to do.  */
14325           len = 0;
14326         }
14327
14328       if (TREE_CODE (arg1) == REFERENCE_TYPE)
14329         {
14330           arg1 = TREE_TYPE (arg1);
14331           quals1 = cp_type_quals (arg1);
14332         }
14333
14334       if (TREE_CODE (arg2) == REFERENCE_TYPE)
14335         {
14336           arg2 = TREE_TYPE (arg2);
14337           quals2 = cp_type_quals (arg2);
14338         }
14339
14340       if ((quals1 < 0) != (quals2 < 0))
14341         {
14342           /* Only of the args is a reference, see if we should apply
14343              array/function pointer decay to it.  This is not part of
14344              DR214, but is, IMHO, consistent with the deduction rules
14345              for the function call itself, and with our earlier
14346              implementation of the underspecified partial ordering
14347              rules.  (nathan).  */
14348           if (quals1 >= 0)
14349             {
14350               switch (TREE_CODE (arg1))
14351                 {
14352                 case ARRAY_TYPE:
14353                   arg1 = TREE_TYPE (arg1);
14354                   /* FALLTHROUGH. */
14355                 case FUNCTION_TYPE:
14356                   arg1 = build_pointer_type (arg1);
14357                   break;
14358
14359                 default:
14360                   break;
14361                 }
14362             }
14363           else
14364             {
14365               switch (TREE_CODE (arg2))
14366                 {
14367                 case ARRAY_TYPE:
14368                   arg2 = TREE_TYPE (arg2);
14369                   /* FALLTHROUGH. */
14370                 case FUNCTION_TYPE:
14371                   arg2 = build_pointer_type (arg2);
14372                   break;
14373
14374                 default:
14375                   break;
14376                 }
14377             }
14378         }
14379
14380       arg1 = TYPE_MAIN_VARIANT (arg1);
14381       arg2 = TYPE_MAIN_VARIANT (arg2);
14382
14383       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
14384         {
14385           int i, len2 = list_length (args2);
14386           tree parmvec = make_tree_vec (1);
14387           tree argvec = make_tree_vec (len2);
14388           tree ta = args2;
14389
14390           /* Setup the parameter vector, which contains only ARG1.  */
14391           TREE_VEC_ELT (parmvec, 0) = arg1;
14392
14393           /* Setup the argument vector, which contains the remaining
14394              arguments.  */
14395           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
14396             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14397
14398           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
14399                                            argvec, UNIFY_ALLOW_NONE, 
14400                                            /*call_args_p=*/false, 
14401                                            /*subr=*/0);
14402
14403           /* We cannot deduce in the other direction, because ARG1 is
14404              a pack expansion but ARG2 is not.  */
14405           deduce2 = 0;
14406         }
14407       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14408         {
14409           int i, len1 = list_length (args1);
14410           tree parmvec = make_tree_vec (1);
14411           tree argvec = make_tree_vec (len1);
14412           tree ta = args1;
14413
14414           /* Setup the parameter vector, which contains only ARG1.  */
14415           TREE_VEC_ELT (parmvec, 0) = arg2;
14416
14417           /* Setup the argument vector, which contains the remaining
14418              arguments.  */
14419           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14420             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14421
14422           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14423                                            argvec, UNIFY_ALLOW_NONE, 
14424                                            /*call_args_p=*/false, 
14425                                            /*subr=*/0);
14426
14427           /* We cannot deduce in the other direction, because ARG2 is
14428              a pack expansion but ARG1 is not.*/
14429           deduce1 = 0;
14430         }
14431
14432       else
14433         {
14434           /* The normal case, where neither argument is a pack
14435              expansion.  */
14436           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
14437           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
14438         }
14439
14440       if (!deduce1)
14441         better2 = -1;
14442       if (!deduce2)
14443         better1 = -1;
14444       if (better1 < 0 && better2 < 0)
14445         /* We've failed to deduce something in either direction.
14446            These must be unordered.  */
14447         break;
14448
14449       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
14450         {
14451           /* Deduces in both directions, see if quals can
14452              disambiguate.  Pretend the worse one failed to deduce. */
14453           if ((quals1 & quals2) == quals2)
14454             deduce1 = 0;
14455           if ((quals1 & quals2) == quals1)
14456             deduce2 = 0;
14457         }
14458       if (deduce1 && !deduce2 && !better2)
14459         better2 = 1;
14460       if (deduce2 && !deduce1 && !better1)
14461         better1 = 1;
14462
14463       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14464           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14465         /* We have already processed all of the arguments in our
14466            handing of the pack expansion type.  */
14467         len = 0;
14468
14469       args1 = TREE_CHAIN (args1);
14470       args2 = TREE_CHAIN (args2);
14471     }
14472
14473   processing_template_decl--;
14474
14475   /* All things being equal, if the next argument is a pack expansion
14476      for one function but not for the other, prefer the
14477      non-variadic function.  */
14478   if ((better1 > 0) - (better2 > 0) == 0
14479       && args1 && TREE_VALUE (args1)
14480       && args2 && TREE_VALUE (args2))
14481     {
14482       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
14483         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
14484       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
14485         return 1;
14486     }
14487
14488   return (better1 > 0) - (better2 > 0);
14489 }
14490
14491 /* Determine which of two partial specializations is more specialized.
14492
14493    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
14494    to the first partial specialization.  The TREE_VALUE is the
14495    innermost set of template parameters for the partial
14496    specialization.  PAT2 is similar, but for the second template.
14497
14498    Return 1 if the first partial specialization is more specialized;
14499    -1 if the second is more specialized; 0 if neither is more
14500    specialized.
14501
14502    See [temp.class.order] for information about determining which of
14503    two templates is more specialized.  */
14504
14505 static int
14506 more_specialized_class (tree pat1, tree pat2)
14507 {
14508   tree targs;
14509   tree tmpl1, tmpl2;
14510   int winner = 0;
14511   bool any_deductions = false;
14512
14513   tmpl1 = TREE_TYPE (pat1);
14514   tmpl2 = TREE_TYPE (pat2);
14515
14516   /* Just like what happens for functions, if we are ordering between
14517      different class template specializations, we may encounter dependent
14518      types in the arguments, and we need our dependency check functions
14519      to behave correctly.  */
14520   ++processing_template_decl;
14521   targs = get_class_bindings (TREE_VALUE (pat1),
14522                               CLASSTYPE_TI_ARGS (tmpl1),
14523                               CLASSTYPE_TI_ARGS (tmpl2));
14524   if (targs)
14525     {
14526       --winner;
14527       any_deductions = true;
14528     }
14529
14530   targs = get_class_bindings (TREE_VALUE (pat2),
14531                               CLASSTYPE_TI_ARGS (tmpl2),
14532                               CLASSTYPE_TI_ARGS (tmpl1));
14533   if (targs)
14534     {
14535       ++winner;
14536       any_deductions = true;
14537     }
14538   --processing_template_decl;
14539
14540   /* In the case of a tie where at least one of the class templates
14541      has a parameter pack at the end, the template with the most
14542      non-packed parameters wins.  */
14543   if (winner == 0
14544       && any_deductions
14545       && (template_args_variadic_p (TREE_PURPOSE (pat1))
14546           || template_args_variadic_p (TREE_PURPOSE (pat2))))
14547     {
14548       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
14549       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
14550       int len1 = TREE_VEC_LENGTH (args1);
14551       int len2 = TREE_VEC_LENGTH (args2);
14552
14553       /* We don't count the pack expansion at the end.  */
14554       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
14555         --len1;
14556       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
14557         --len2;
14558
14559       if (len1 > len2)
14560         return 1;
14561       else if (len1 < len2)
14562         return -1;
14563     }
14564
14565   return winner;
14566 }
14567
14568 /* Return the template arguments that will produce the function signature
14569    DECL from the function template FN, with the explicit template
14570    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
14571    also match.  Return NULL_TREE if no satisfactory arguments could be
14572    found.  */
14573
14574 static tree
14575 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
14576 {
14577   int ntparms = DECL_NTPARMS (fn);
14578   tree targs = make_tree_vec (ntparms);
14579   tree decl_type;
14580   tree decl_arg_types;
14581   tree *args;
14582   unsigned int nargs, ix;
14583   tree arg;
14584
14585   /* Substitute the explicit template arguments into the type of DECL.
14586      The call to fn_type_unification will handle substitution into the
14587      FN.  */
14588   decl_type = TREE_TYPE (decl);
14589   if (explicit_args && uses_template_parms (decl_type))
14590     {
14591       tree tmpl;
14592       tree converted_args;
14593
14594       if (DECL_TEMPLATE_INFO (decl))
14595         tmpl = DECL_TI_TEMPLATE (decl);
14596       else
14597         /* We can get here for some invalid specializations.  */
14598         return NULL_TREE;
14599
14600       converted_args
14601         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
14602                                  explicit_args, NULL_TREE,
14603                                  tf_none,
14604                                  /*require_all_args=*/false,
14605                                  /*use_default_args=*/false);
14606       if (converted_args == error_mark_node)
14607         return NULL_TREE;
14608
14609       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
14610       if (decl_type == error_mark_node)
14611         return NULL_TREE;
14612     }
14613
14614   /* Never do unification on the 'this' parameter.  */
14615   decl_arg_types = skip_artificial_parms_for (decl, 
14616                                               TYPE_ARG_TYPES (decl_type));
14617
14618   nargs = list_length (decl_arg_types);
14619   args = XALLOCAVEC (tree, nargs);
14620   for (arg = decl_arg_types, ix = 0;
14621        arg != NULL_TREE && arg != void_list_node;
14622        arg = TREE_CHAIN (arg), ++ix)
14623     args[ix] = TREE_VALUE (arg);
14624
14625   if (fn_type_unification (fn, explicit_args, targs,
14626                            args, ix,
14627                            (check_rettype || DECL_CONV_FN_P (fn)
14628                             ? TREE_TYPE (decl_type) : NULL_TREE),
14629                            DEDUCE_EXACT, LOOKUP_NORMAL))
14630     return NULL_TREE;
14631
14632   return targs;
14633 }
14634
14635 /* Return the innermost template arguments that, when applied to a
14636    template specialization whose innermost template parameters are
14637    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
14638    ARGS.
14639
14640    For example, suppose we have:
14641
14642      template <class T, class U> struct S {};
14643      template <class T> struct S<T*, int> {};
14644
14645    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
14646    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
14647    int}.  The resulting vector will be {double}, indicating that `T'
14648    is bound to `double'.  */
14649
14650 static tree
14651 get_class_bindings (tree tparms, tree spec_args, tree args)
14652 {
14653   int i, ntparms = TREE_VEC_LENGTH (tparms);
14654   tree deduced_args;
14655   tree innermost_deduced_args;
14656
14657   innermost_deduced_args = make_tree_vec (ntparms);
14658   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14659     {
14660       deduced_args = copy_node (args);
14661       SET_TMPL_ARGS_LEVEL (deduced_args,
14662                            TMPL_ARGS_DEPTH (deduced_args),
14663                            innermost_deduced_args);
14664     }
14665   else
14666     deduced_args = innermost_deduced_args;
14667
14668   if (unify (tparms, deduced_args,
14669              INNERMOST_TEMPLATE_ARGS (spec_args),
14670              INNERMOST_TEMPLATE_ARGS (args),
14671              UNIFY_ALLOW_NONE))
14672     return NULL_TREE;
14673
14674   for (i =  0; i < ntparms; ++i)
14675     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14676       return NULL_TREE;
14677
14678   /* Verify that nondeduced template arguments agree with the type
14679      obtained from argument deduction.
14680
14681      For example:
14682
14683        struct A { typedef int X; };
14684        template <class T, class U> struct C {};
14685        template <class T> struct C<T, typename T::X> {};
14686
14687      Then with the instantiation `C<A, int>', we can deduce that
14688      `T' is `A' but unify () does not check whether `typename T::X'
14689      is `int'.  */
14690   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14691   if (spec_args == error_mark_node
14692       /* We only need to check the innermost arguments; the other
14693          arguments will always agree.  */
14694       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14695                               INNERMOST_TEMPLATE_ARGS (args)))
14696     return NULL_TREE;
14697
14698   /* Now that we have bindings for all of the template arguments,
14699      ensure that the arguments deduced for the template template
14700      parameters have compatible template parameter lists.  See the use
14701      of template_template_parm_bindings_ok_p in fn_type_unification
14702      for more information.  */
14703   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14704     return NULL_TREE;
14705
14706   return deduced_args;
14707 }
14708
14709 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14710    Return the TREE_LIST node with the most specialized template, if
14711    any.  If there is no most specialized template, the error_mark_node
14712    is returned.
14713
14714    Note that this function does not look at, or modify, the
14715    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14716    returned is one of the elements of INSTANTIATIONS, callers may
14717    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14718    and retrieve it from the value returned.  */
14719
14720 tree
14721 most_specialized_instantiation (tree templates)
14722 {
14723   tree fn, champ;
14724
14725   ++processing_template_decl;
14726
14727   champ = templates;
14728   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14729     {
14730       int fate = 0;
14731
14732       if (get_bindings (TREE_VALUE (champ),
14733                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14734                         NULL_TREE, /*check_ret=*/false))
14735         fate--;
14736
14737       if (get_bindings (TREE_VALUE (fn),
14738                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14739                         NULL_TREE, /*check_ret=*/false))
14740         fate++;
14741
14742       if (fate == -1)
14743         champ = fn;
14744       else if (!fate)
14745         {
14746           /* Equally specialized, move to next function.  If there
14747              is no next function, nothing's most specialized.  */
14748           fn = TREE_CHAIN (fn);
14749           champ = fn;
14750           if (!fn)
14751             break;
14752         }
14753     }
14754
14755   if (champ)
14756     /* Now verify that champ is better than everything earlier in the
14757        instantiation list.  */
14758     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14759       if (get_bindings (TREE_VALUE (champ),
14760                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14761                         NULL_TREE, /*check_ret=*/false)
14762           || !get_bindings (TREE_VALUE (fn),
14763                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14764                             NULL_TREE, /*check_ret=*/false))
14765         {
14766           champ = NULL_TREE;
14767           break;
14768         }
14769
14770   processing_template_decl--;
14771
14772   if (!champ)
14773     return error_mark_node;
14774
14775   return champ;
14776 }
14777
14778 /* If DECL is a specialization of some template, return the most
14779    general such template.  Otherwise, returns NULL_TREE.
14780
14781    For example, given:
14782
14783      template <class T> struct S { template <class U> void f(U); };
14784
14785    if TMPL is `template <class U> void S<int>::f(U)' this will return
14786    the full template.  This function will not trace past partial
14787    specializations, however.  For example, given in addition:
14788
14789      template <class T> struct S<T*> { template <class U> void f(U); };
14790
14791    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14792    `template <class T> template <class U> S<T*>::f(U)'.  */
14793
14794 tree
14795 most_general_template (tree decl)
14796 {
14797   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14798      an immediate specialization.  */
14799   if (TREE_CODE (decl) == FUNCTION_DECL)
14800     {
14801       if (DECL_TEMPLATE_INFO (decl)) {
14802         decl = DECL_TI_TEMPLATE (decl);
14803
14804         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14805            template friend.  */
14806         if (TREE_CODE (decl) != TEMPLATE_DECL)
14807           return NULL_TREE;
14808       } else
14809         return NULL_TREE;
14810     }
14811
14812   /* Look for more and more general templates.  */
14813   while (DECL_TEMPLATE_INFO (decl))
14814     {
14815       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14816          (See cp-tree.h for details.)  */
14817       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14818         break;
14819
14820       if (CLASS_TYPE_P (TREE_TYPE (decl))
14821           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14822         break;
14823
14824       /* Stop if we run into an explicitly specialized class template.  */
14825       if (!DECL_NAMESPACE_SCOPE_P (decl)
14826           && DECL_CONTEXT (decl)
14827           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14828         break;
14829
14830       decl = DECL_TI_TEMPLATE (decl);
14831     }
14832
14833   return decl;
14834 }
14835
14836 /* Return the most specialized of the class template partial
14837    specializations of TMPL which can produce TYPE, a specialization of
14838    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14839    a _TYPE node corresponding to the partial specialization, while the
14840    TREE_PURPOSE is the set of template arguments that must be
14841    substituted into the TREE_TYPE in order to generate TYPE.
14842
14843    If the choice of partial specialization is ambiguous, a diagnostic
14844    is issued, and the error_mark_node is returned.  If there are no
14845    partial specializations of TMPL matching TYPE, then NULL_TREE is
14846    returned.  */
14847
14848 static tree
14849 most_specialized_class (tree type, tree tmpl)
14850 {
14851   tree list = NULL_TREE;
14852   tree t;
14853   tree champ;
14854   int fate;
14855   bool ambiguous_p;
14856   tree args;
14857   tree outer_args = NULL_TREE;
14858
14859   tmpl = most_general_template (tmpl);
14860   args = CLASSTYPE_TI_ARGS (type);
14861
14862   /* For determining which partial specialization to use, only the
14863      innermost args are interesting.  */
14864   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14865     {
14866       outer_args = strip_innermost_template_args (args, 1);
14867       args = INNERMOST_TEMPLATE_ARGS (args);
14868     }
14869
14870   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14871     {
14872       tree partial_spec_args;
14873       tree spec_args;
14874       tree parms = TREE_VALUE (t);
14875
14876       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14877       if (outer_args)
14878         {
14879           int i;
14880
14881           ++processing_template_decl;
14882
14883           /* Discard the outer levels of args, and then substitute in the
14884              template args from the enclosing class.  */
14885           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14886           partial_spec_args = tsubst_template_args
14887             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14888
14889           /* PARMS already refers to just the innermost parms, but the
14890              template parms in partial_spec_args had their levels lowered
14891              by tsubst, so we need to do the same for the parm list.  We
14892              can't just tsubst the TREE_VEC itself, as tsubst wants to
14893              treat a TREE_VEC as an argument vector.  */
14894           parms = copy_node (parms);
14895           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14896             TREE_VEC_ELT (parms, i) =
14897               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14898
14899           --processing_template_decl;
14900         }
14901       spec_args = get_class_bindings (parms,
14902                                       partial_spec_args,
14903                                       args);
14904       if (spec_args)
14905         {
14906           if (outer_args)
14907             spec_args = add_to_template_args (outer_args, spec_args);
14908           list = tree_cons (spec_args, TREE_VALUE (t), list);
14909           TREE_TYPE (list) = TREE_TYPE (t);
14910         }
14911     }
14912
14913   if (! list)
14914     return NULL_TREE;
14915
14916   ambiguous_p = false;
14917   t = list;
14918   champ = t;
14919   t = TREE_CHAIN (t);
14920   for (; t; t = TREE_CHAIN (t))
14921     {
14922       fate = more_specialized_class (champ, t);
14923       if (fate == 1)
14924         ;
14925       else
14926         {
14927           if (fate == 0)
14928             {
14929               t = TREE_CHAIN (t);
14930               if (! t)
14931                 {
14932                   ambiguous_p = true;
14933                   break;
14934                 }
14935             }
14936           champ = t;
14937         }
14938     }
14939
14940   if (!ambiguous_p)
14941     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14942       {
14943         fate = more_specialized_class (champ, t);
14944         if (fate != 1)
14945           {
14946             ambiguous_p = true;
14947             break;
14948           }
14949       }
14950
14951   if (ambiguous_p)
14952     {
14953       const char *str = "candidates are:";
14954       error ("ambiguous class template instantiation for %q#T", type);
14955       for (t = list; t; t = TREE_CHAIN (t))
14956         {
14957           error ("%s %+#T", str, TREE_TYPE (t));
14958           str = "               ";
14959         }
14960       return error_mark_node;
14961     }
14962
14963   return champ;
14964 }
14965
14966 /* Explicitly instantiate DECL.  */
14967
14968 void
14969 do_decl_instantiation (tree decl, tree storage)
14970 {
14971   tree result = NULL_TREE;
14972   int extern_p = 0;
14973
14974   if (!decl || decl == error_mark_node)
14975     /* An error occurred, for which grokdeclarator has already issued
14976        an appropriate message.  */
14977     return;
14978   else if (! DECL_LANG_SPECIFIC (decl))
14979     {
14980       error ("explicit instantiation of non-template %q#D", decl);
14981       return;
14982     }
14983   else if (TREE_CODE (decl) == VAR_DECL)
14984     {
14985       /* There is an asymmetry here in the way VAR_DECLs and
14986          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14987          the latter, the DECL we get back will be marked as a
14988          template instantiation, and the appropriate
14989          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14990          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14991          should handle VAR_DECLs as it currently handles
14992          FUNCTION_DECLs.  */
14993       if (!DECL_CLASS_SCOPE_P (decl))
14994         {
14995           error ("%qD is not a static data member of a class template", decl);
14996           return;
14997         }
14998       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14999       if (!result || TREE_CODE (result) != VAR_DECL)
15000         {
15001           error ("no matching template for %qD found", decl);
15002           return;
15003         }
15004       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
15005         {
15006           error ("type %qT for explicit instantiation %qD does not match "
15007                  "declared type %qT", TREE_TYPE (result), decl,
15008                  TREE_TYPE (decl));
15009           return;
15010         }
15011     }
15012   else if (TREE_CODE (decl) != FUNCTION_DECL)
15013     {
15014       error ("explicit instantiation of %q#D", decl);
15015       return;
15016     }
15017   else
15018     result = decl;
15019
15020   /* Check for various error cases.  Note that if the explicit
15021      instantiation is valid the RESULT will currently be marked as an
15022      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
15023      until we get here.  */
15024
15025   if (DECL_TEMPLATE_SPECIALIZATION (result))
15026     {
15027       /* DR 259 [temp.spec].
15028
15029          Both an explicit instantiation and a declaration of an explicit
15030          specialization shall not appear in a program unless the explicit
15031          instantiation follows a declaration of the explicit specialization.
15032
15033          For a given set of template parameters, if an explicit
15034          instantiation of a template appears after a declaration of an
15035          explicit specialization for that template, the explicit
15036          instantiation has no effect.  */
15037       return;
15038     }
15039   else if (DECL_EXPLICIT_INSTANTIATION (result))
15040     {
15041       /* [temp.spec]
15042
15043          No program shall explicitly instantiate any template more
15044          than once.
15045
15046          We check DECL_NOT_REALLY_EXTERN so as not to complain when
15047          the first instantiation was `extern' and the second is not,
15048          and EXTERN_P for the opposite case.  */
15049       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
15050         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
15051       /* If an "extern" explicit instantiation follows an ordinary
15052          explicit instantiation, the template is instantiated.  */
15053       if (extern_p)
15054         return;
15055     }
15056   else if (!DECL_IMPLICIT_INSTANTIATION (result))
15057     {
15058       error ("no matching template for %qD found", result);
15059       return;
15060     }
15061   else if (!DECL_TEMPLATE_INFO (result))
15062     {
15063       permerror (input_location, "explicit instantiation of non-template %q#D", result);
15064       return;
15065     }
15066
15067   if (storage == NULL_TREE)
15068     ;
15069   else if (storage == ridpointers[(int) RID_EXTERN])
15070     {
15071       if (!in_system_header && (cxx_dialect == cxx98))
15072         pedwarn (input_location, OPT_pedantic, 
15073                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
15074                  "instantiations");
15075       extern_p = 1;
15076     }
15077   else
15078     error ("storage class %qD applied to template instantiation", storage);
15079
15080   check_explicit_instantiation_namespace (result);
15081   mark_decl_instantiated (result, extern_p);
15082   if (! extern_p)
15083     instantiate_decl (result, /*defer_ok=*/1,
15084                       /*expl_inst_class_mem_p=*/false);
15085 }
15086
15087 static void
15088 mark_class_instantiated (tree t, int extern_p)
15089 {
15090   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
15091   SET_CLASSTYPE_INTERFACE_KNOWN (t);
15092   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
15093   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
15094   if (! extern_p)
15095     {
15096       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
15097       rest_of_type_compilation (t, 1);
15098     }
15099 }
15100
15101 /* Called from do_type_instantiation through binding_table_foreach to
15102    do recursive instantiation for the type bound in ENTRY.  */
15103 static void
15104 bt_instantiate_type_proc (binding_entry entry, void *data)
15105 {
15106   tree storage = *(tree *) data;
15107
15108   if (MAYBE_CLASS_TYPE_P (entry->type)
15109       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15110     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15111 }
15112
15113 /* Called from do_type_instantiation to instantiate a member
15114    (a member function or a static member variable) of an
15115    explicitly instantiated class template.  */
15116 static void
15117 instantiate_class_member (tree decl, int extern_p)
15118 {
15119   mark_decl_instantiated (decl, extern_p);
15120   if (! extern_p)
15121     instantiate_decl (decl, /*defer_ok=*/1,
15122                       /*expl_inst_class_mem_p=*/true);
15123 }
15124
15125 /* Perform an explicit instantiation of template class T.  STORAGE, if
15126    non-null, is the RID for extern, inline or static.  COMPLAIN is
15127    nonzero if this is called from the parser, zero if called recursively,
15128    since the standard is unclear (as detailed below).  */
15129
15130 void
15131 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15132 {
15133   int extern_p = 0;
15134   int nomem_p = 0;
15135   int static_p = 0;
15136   int previous_instantiation_extern_p = 0;
15137
15138   if (TREE_CODE (t) == TYPE_DECL)
15139     t = TREE_TYPE (t);
15140
15141   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15142     {
15143       error ("explicit instantiation of non-template type %qT", t);
15144       return;
15145     }
15146
15147   complete_type (t);
15148
15149   if (!COMPLETE_TYPE_P (t))
15150     {
15151       if (complain & tf_error)
15152         error ("explicit instantiation of %q#T before definition of template",
15153                t);
15154       return;
15155     }
15156
15157   if (storage != NULL_TREE)
15158     {
15159       if (!in_system_header)
15160         {
15161           if (storage == ridpointers[(int) RID_EXTERN])
15162             {
15163               if (cxx_dialect == cxx98)
15164                 pedwarn (input_location, OPT_pedantic, 
15165                          "ISO C++ 1998 forbids the use of %<extern%> on "
15166                          "explicit instantiations");
15167             }
15168           else
15169             pedwarn (input_location, OPT_pedantic, 
15170                      "ISO C++ forbids the use of %qE"
15171                      " on explicit instantiations", storage);
15172         }
15173
15174       if (storage == ridpointers[(int) RID_INLINE])
15175         nomem_p = 1;
15176       else if (storage == ridpointers[(int) RID_EXTERN])
15177         extern_p = 1;
15178       else if (storage == ridpointers[(int) RID_STATIC])
15179         static_p = 1;
15180       else
15181         {
15182           error ("storage class %qD applied to template instantiation",
15183                  storage);
15184           extern_p = 0;
15185         }
15186     }
15187
15188   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15189     {
15190       /* DR 259 [temp.spec].
15191
15192          Both an explicit instantiation and a declaration of an explicit
15193          specialization shall not appear in a program unless the explicit
15194          instantiation follows a declaration of the explicit specialization.
15195
15196          For a given set of template parameters, if an explicit
15197          instantiation of a template appears after a declaration of an
15198          explicit specialization for that template, the explicit
15199          instantiation has no effect.  */
15200       return;
15201     }
15202   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15203     {
15204       /* [temp.spec]
15205
15206          No program shall explicitly instantiate any template more
15207          than once.
15208
15209          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15210          instantiation was `extern'.  If EXTERN_P then the second is.
15211          These cases are OK.  */
15212       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15213
15214       if (!previous_instantiation_extern_p && !extern_p
15215           && (complain & tf_error))
15216         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15217
15218       /* If we've already instantiated the template, just return now.  */
15219       if (!CLASSTYPE_INTERFACE_ONLY (t))
15220         return;
15221     }
15222
15223   check_explicit_instantiation_namespace (TYPE_NAME (t));
15224   mark_class_instantiated (t, extern_p);
15225
15226   if (nomem_p)
15227     return;
15228
15229   {
15230     tree tmp;
15231
15232     /* In contrast to implicit instantiation, where only the
15233        declarations, and not the definitions, of members are
15234        instantiated, we have here:
15235
15236          [temp.explicit]
15237
15238          The explicit instantiation of a class template specialization
15239          implies the instantiation of all of its members not
15240          previously explicitly specialized in the translation unit
15241          containing the explicit instantiation.
15242
15243        Of course, we can't instantiate member template classes, since
15244        we don't have any arguments for them.  Note that the standard
15245        is unclear on whether the instantiation of the members are
15246        *explicit* instantiations or not.  However, the most natural
15247        interpretation is that it should be an explicit instantiation.  */
15248
15249     if (! static_p)
15250       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
15251         if (TREE_CODE (tmp) == FUNCTION_DECL
15252             && DECL_TEMPLATE_INSTANTIATION (tmp))
15253           instantiate_class_member (tmp, extern_p);
15254
15255     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
15256       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
15257         instantiate_class_member (tmp, extern_p);
15258
15259     if (CLASSTYPE_NESTED_UTDS (t))
15260       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
15261                              bt_instantiate_type_proc, &storage);
15262   }
15263 }
15264
15265 /* Given a function DECL, which is a specialization of TMPL, modify
15266    DECL to be a re-instantiation of TMPL with the same template
15267    arguments.  TMPL should be the template into which tsubst'ing
15268    should occur for DECL, not the most general template.
15269
15270    One reason for doing this is a scenario like this:
15271
15272      template <class T>
15273      void f(const T&, int i);
15274
15275      void g() { f(3, 7); }
15276
15277      template <class T>
15278      void f(const T& t, const int i) { }
15279
15280    Note that when the template is first instantiated, with
15281    instantiate_template, the resulting DECL will have no name for the
15282    first parameter, and the wrong type for the second.  So, when we go
15283    to instantiate the DECL, we regenerate it.  */
15284
15285 static void
15286 regenerate_decl_from_template (tree decl, tree tmpl)
15287 {
15288   /* The arguments used to instantiate DECL, from the most general
15289      template.  */
15290   tree args;
15291   tree code_pattern;
15292
15293   args = DECL_TI_ARGS (decl);
15294   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
15295
15296   /* Make sure that we can see identifiers, and compute access
15297      correctly.  */
15298   push_access_scope (decl);
15299
15300   if (TREE_CODE (decl) == FUNCTION_DECL)
15301     {
15302       tree decl_parm;
15303       tree pattern_parm;
15304       tree specs;
15305       int args_depth;
15306       int parms_depth;
15307
15308       args_depth = TMPL_ARGS_DEPTH (args);
15309       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
15310       if (args_depth > parms_depth)
15311         args = get_innermost_template_args (args, parms_depth);
15312
15313       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
15314                                               args, tf_error, NULL_TREE);
15315       if (specs)
15316         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
15317                                                     specs);
15318
15319       /* Merge parameter declarations.  */
15320       decl_parm = skip_artificial_parms_for (decl,
15321                                              DECL_ARGUMENTS (decl));
15322       pattern_parm
15323         = skip_artificial_parms_for (code_pattern,
15324                                      DECL_ARGUMENTS (code_pattern));
15325       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
15326         {
15327           tree parm_type;
15328           tree attributes;
15329           
15330           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15331             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
15332           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
15333                               NULL_TREE);
15334           parm_type = type_decays_to (parm_type);
15335           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15336             TREE_TYPE (decl_parm) = parm_type;
15337           attributes = DECL_ATTRIBUTES (pattern_parm);
15338           if (DECL_ATTRIBUTES (decl_parm) != attributes)
15339             {
15340               DECL_ATTRIBUTES (decl_parm) = attributes;
15341               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15342             }
15343           decl_parm = TREE_CHAIN (decl_parm);
15344           pattern_parm = TREE_CHAIN (pattern_parm);
15345         }
15346       /* Merge any parameters that match with the function parameter
15347          pack.  */
15348       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
15349         {
15350           int i, len;
15351           tree expanded_types;
15352           /* Expand the TYPE_PACK_EXPANSION that provides the types for
15353              the parameters in this function parameter pack.  */
15354           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
15355                                                  args, tf_error, NULL_TREE);
15356           len = TREE_VEC_LENGTH (expanded_types);
15357           for (i = 0; i < len; i++)
15358             {
15359               tree parm_type;
15360               tree attributes;
15361           
15362               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15363                 /* Rename the parameter to include the index.  */
15364                 DECL_NAME (decl_parm) = 
15365                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
15366               parm_type = TREE_VEC_ELT (expanded_types, i);
15367               parm_type = type_decays_to (parm_type);
15368               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15369                 TREE_TYPE (decl_parm) = parm_type;
15370               attributes = DECL_ATTRIBUTES (pattern_parm);
15371               if (DECL_ATTRIBUTES (decl_parm) != attributes)
15372                 {
15373                   DECL_ATTRIBUTES (decl_parm) = attributes;
15374                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15375                 }
15376               decl_parm = TREE_CHAIN (decl_parm);
15377             }
15378         }
15379       /* Merge additional specifiers from the CODE_PATTERN.  */
15380       if (DECL_DECLARED_INLINE_P (code_pattern)
15381           && !DECL_DECLARED_INLINE_P (decl))
15382         DECL_DECLARED_INLINE_P (decl) = 1;
15383     }
15384   else if (TREE_CODE (decl) == VAR_DECL)
15385     DECL_INITIAL (decl) =
15386       tsubst_expr (DECL_INITIAL (code_pattern), args,
15387                    tf_error, DECL_TI_TEMPLATE (decl),
15388                    /*integral_constant_expression_p=*/false);
15389   else
15390     gcc_unreachable ();
15391
15392   pop_access_scope (decl);
15393 }
15394
15395 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
15396    substituted to get DECL.  */
15397
15398 tree
15399 template_for_substitution (tree decl)
15400 {
15401   tree tmpl = DECL_TI_TEMPLATE (decl);
15402
15403   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
15404      for the instantiation.  This is not always the most general
15405      template.  Consider, for example:
15406
15407         template <class T>
15408         struct S { template <class U> void f();
15409                    template <> void f<int>(); };
15410
15411      and an instantiation of S<double>::f<int>.  We want TD to be the
15412      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
15413   while (/* An instantiation cannot have a definition, so we need a
15414             more general template.  */
15415          DECL_TEMPLATE_INSTANTIATION (tmpl)
15416            /* We must also deal with friend templates.  Given:
15417
15418                 template <class T> struct S {
15419                   template <class U> friend void f() {};
15420                 };
15421
15422               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15423               so far as the language is concerned, but that's still
15424               where we get the pattern for the instantiation from.  On
15425               other hand, if the definition comes outside the class, say:
15426
15427                 template <class T> struct S {
15428                   template <class U> friend void f();
15429                 };
15430                 template <class U> friend void f() {}
15431
15432               we don't need to look any further.  That's what the check for
15433               DECL_INITIAL is for.  */
15434           || (TREE_CODE (decl) == FUNCTION_DECL
15435               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
15436               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
15437     {
15438       /* The present template, TD, should not be a definition.  If it
15439          were a definition, we should be using it!  Note that we
15440          cannot restructure the loop to just keep going until we find
15441          a template with a definition, since that might go too far if
15442          a specialization was declared, but not defined.  */
15443       gcc_assert (TREE_CODE (decl) != VAR_DECL
15444                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
15445
15446       /* Fetch the more general template.  */
15447       tmpl = DECL_TI_TEMPLATE (tmpl);
15448     }
15449
15450   return tmpl;
15451 }
15452
15453 /* Produce the definition of D, a _DECL generated from a template.  If
15454    DEFER_OK is nonzero, then we don't have to actually do the
15455    instantiation now; we just have to do it sometime.  Normally it is
15456    an error if this is an explicit instantiation but D is undefined.
15457    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
15458    explicitly instantiated class template.  */
15459
15460 tree
15461 instantiate_decl (tree d, int defer_ok,
15462                   bool expl_inst_class_mem_p)
15463 {
15464   tree tmpl = DECL_TI_TEMPLATE (d);
15465   tree gen_args;
15466   tree args;
15467   tree td;
15468   tree code_pattern;
15469   tree spec;
15470   tree gen_tmpl;
15471   bool pattern_defined;
15472   int need_push;
15473   location_t saved_loc = input_location;
15474   bool external_p;
15475
15476   /* This function should only be used to instantiate templates for
15477      functions and static member variables.  */
15478   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
15479               || TREE_CODE (d) == VAR_DECL);
15480
15481   /* Variables are never deferred; if instantiation is required, they
15482      are instantiated right away.  That allows for better code in the
15483      case that an expression refers to the value of the variable --
15484      if the variable has a constant value the referring expression can
15485      take advantage of that fact.  */
15486   if (TREE_CODE (d) == VAR_DECL)
15487     defer_ok = 0;
15488
15489   /* Don't instantiate cloned functions.  Instead, instantiate the
15490      functions they cloned.  */
15491   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
15492     d = DECL_CLONED_FUNCTION (d);
15493
15494   if (DECL_TEMPLATE_INSTANTIATED (d))
15495     /* D has already been instantiated.  It might seem reasonable to
15496        check whether or not D is an explicit instantiation, and, if so,
15497        stop here.  But when an explicit instantiation is deferred
15498        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
15499        is set, even though we still need to do the instantiation.  */
15500     return d;
15501
15502   /* If we already have a specialization of this declaration, then
15503      there's no reason to instantiate it.  Note that
15504      retrieve_specialization gives us both instantiations and
15505      specializations, so we must explicitly check
15506      DECL_TEMPLATE_SPECIALIZATION.  */
15507   gen_tmpl = most_general_template (tmpl);
15508   gen_args = DECL_TI_ARGS (d);
15509   spec = retrieve_specialization (gen_tmpl, gen_args,
15510                                   /*class_specializations_p=*/false);
15511   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
15512     return spec;
15513
15514   /* This needs to happen before any tsubsting.  */
15515   if (! push_tinst_level (d))
15516     return d;
15517
15518   timevar_push (TV_PARSE);
15519
15520   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
15521      for the instantiation.  */
15522   td = template_for_substitution (d);
15523   code_pattern = DECL_TEMPLATE_RESULT (td);
15524
15525   /* We should never be trying to instantiate a member of a class
15526      template or partial specialization.  */
15527   gcc_assert (d != code_pattern);
15528
15529   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
15530       || DECL_TEMPLATE_SPECIALIZATION (td))
15531     /* In the case of a friend template whose definition is provided
15532        outside the class, we may have too many arguments.  Drop the
15533        ones we don't need.  The same is true for specializations.  */
15534     args = get_innermost_template_args
15535       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
15536   else
15537     args = gen_args;
15538
15539   if (TREE_CODE (d) == FUNCTION_DECL)
15540     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
15541   else
15542     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
15543
15544   /* We may be in the middle of deferred access check.  Disable it now.  */
15545   push_deferring_access_checks (dk_no_deferred);
15546
15547   /* Unless an explicit instantiation directive has already determined
15548      the linkage of D, remember that a definition is available for
15549      this entity.  */
15550   if (pattern_defined
15551       && !DECL_INTERFACE_KNOWN (d)
15552       && !DECL_NOT_REALLY_EXTERN (d))
15553     mark_definable (d);
15554
15555   input_location = DECL_SOURCE_LOCATION (d);
15556
15557   /* If D is a member of an explicitly instantiated class template,
15558      and no definition is available, treat it like an implicit
15559      instantiation.  */
15560   if (!pattern_defined && expl_inst_class_mem_p
15561       && DECL_EXPLICIT_INSTANTIATION (d))
15562     {
15563       DECL_NOT_REALLY_EXTERN (d) = 0;
15564       DECL_INTERFACE_KNOWN (d) = 0;
15565       SET_DECL_IMPLICIT_INSTANTIATION (d);
15566     }
15567
15568   if (!defer_ok)
15569     {
15570       /* Recheck the substitutions to obtain any warning messages
15571          about ignoring cv qualifiers.  */
15572       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
15573       tree type = TREE_TYPE (gen);
15574
15575       /* Make sure that we can see identifiers, and compute access
15576          correctly.  D is already the target FUNCTION_DECL with the
15577          right context.  */
15578       push_access_scope (d);
15579
15580       if (TREE_CODE (gen) == FUNCTION_DECL)
15581         {
15582           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
15583           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
15584                                           d);
15585           /* Don't simply tsubst the function type, as that will give
15586              duplicate warnings about poor parameter qualifications.
15587              The function arguments are the same as the decl_arguments
15588              without the top level cv qualifiers.  */
15589           type = TREE_TYPE (type);
15590         }
15591       tsubst (type, gen_args, tf_warning_or_error, d);
15592
15593       pop_access_scope (d);
15594     }
15595
15596   /* Check to see whether we know that this template will be
15597      instantiated in some other file, as with "extern template"
15598      extension.  */
15599   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
15600   /* In general, we do not instantiate such templates...  */
15601   if (external_p
15602       /* ... but we instantiate inline functions so that we can inline
15603          them.  An explicit instantiation declaration prohibits implicit
15604          instantiation of non-inline functions.  With high levels of
15605          optimization, we would normally inline non-inline functions
15606          -- but we're not allowed to do that for "extern template" functions.
15607          Therefore, we check DECL_DECLARED_INLINE_P, rather than
15608          possibly_inlined_p.  And ...  */
15609       && ! (TREE_CODE (d) == FUNCTION_DECL
15610             && DECL_DECLARED_INLINE_P (d))
15611       /* ... we instantiate static data members whose values are
15612          needed in integral constant expressions.  */
15613       && ! (TREE_CODE (d) == VAR_DECL
15614             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
15615     goto out;
15616   /* Defer all other templates, unless we have been explicitly
15617      forbidden from doing so.  */
15618   if (/* If there is no definition, we cannot instantiate the
15619          template.  */
15620       ! pattern_defined
15621       /* If it's OK to postpone instantiation, do so.  */
15622       || defer_ok
15623       /* If this is a static data member that will be defined
15624          elsewhere, we don't want to instantiate the entire data
15625          member, but we do want to instantiate the initializer so that
15626          we can substitute that elsewhere.  */
15627       || (external_p && TREE_CODE (d) == VAR_DECL))
15628     {
15629       /* The definition of the static data member is now required so
15630          we must substitute the initializer.  */
15631       if (TREE_CODE (d) == VAR_DECL
15632           && !DECL_INITIAL (d)
15633           && DECL_INITIAL (code_pattern))
15634         {
15635           tree ns;
15636           tree init;
15637
15638           ns = decl_namespace_context (d);
15639           push_nested_namespace (ns);
15640           push_nested_class (DECL_CONTEXT (d));
15641           init = tsubst_expr (DECL_INITIAL (code_pattern),
15642                               args,
15643                               tf_warning_or_error, NULL_TREE,
15644                               /*integral_constant_expression_p=*/false);
15645           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
15646                           /*asmspec_tree=*/NULL_TREE,
15647                           LOOKUP_ONLYCONVERTING);
15648           pop_nested_class ();
15649           pop_nested_namespace (ns);
15650         }
15651
15652       /* We restore the source position here because it's used by
15653          add_pending_template.  */
15654       input_location = saved_loc;
15655
15656       if (at_eof && !pattern_defined
15657           && DECL_EXPLICIT_INSTANTIATION (d)
15658           && DECL_NOT_REALLY_EXTERN (d))
15659         /* [temp.explicit]
15660
15661            The definition of a non-exported function template, a
15662            non-exported member function template, or a non-exported
15663            member function or static data member of a class template
15664            shall be present in every translation unit in which it is
15665            explicitly instantiated.  */
15666         permerror (input_location,  "explicit instantiation of %qD "
15667                    "but no definition available", d);
15668
15669       /* ??? Historically, we have instantiated inline functions, even
15670          when marked as "extern template".  */
15671       if (!(external_p && TREE_CODE (d) == VAR_DECL))
15672         add_pending_template (d);
15673       goto out;
15674     }
15675   /* Tell the repository that D is available in this translation unit
15676      -- and see if it is supposed to be instantiated here.  */
15677   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15678     {
15679       /* In a PCH file, despite the fact that the repository hasn't
15680          requested instantiation in the PCH it is still possible that
15681          an instantiation will be required in a file that includes the
15682          PCH.  */
15683       if (pch_file)
15684         add_pending_template (d);
15685       /* Instantiate inline functions so that the inliner can do its
15686          job, even though we'll not be emitting a copy of this
15687          function.  */
15688       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
15689         goto out;
15690     }
15691
15692   need_push = !cfun || !global_bindings_p ();
15693   if (need_push)
15694     push_to_top_level ();
15695
15696   /* Mark D as instantiated so that recursive calls to
15697      instantiate_decl do not try to instantiate it again.  */
15698   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15699
15700   /* Regenerate the declaration in case the template has been modified
15701      by a subsequent redeclaration.  */
15702   regenerate_decl_from_template (d, td);
15703
15704   /* We already set the file and line above.  Reset them now in case
15705      they changed as a result of calling regenerate_decl_from_template.  */
15706   input_location = DECL_SOURCE_LOCATION (d);
15707
15708   if (TREE_CODE (d) == VAR_DECL)
15709     {
15710       tree init;
15711
15712       /* Clear out DECL_RTL; whatever was there before may not be right
15713          since we've reset the type of the declaration.  */
15714       SET_DECL_RTL (d, NULL_RTX);
15715       DECL_IN_AGGR_P (d) = 0;
15716
15717       /* The initializer is placed in DECL_INITIAL by
15718          regenerate_decl_from_template.  Pull it out so that
15719          cp_finish_decl can process it.  */
15720       init = DECL_INITIAL (d);
15721       DECL_INITIAL (d) = NULL_TREE;
15722       DECL_INITIALIZED_P (d) = 0;
15723
15724       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15725          initializer.  That function will defer actual emission until
15726          we have a chance to determine linkage.  */
15727       DECL_EXTERNAL (d) = 0;
15728
15729       /* Enter the scope of D so that access-checking works correctly.  */
15730       push_nested_class (DECL_CONTEXT (d));
15731       cp_finish_decl (d, init, false, NULL_TREE, 0);
15732       pop_nested_class ();
15733     }
15734   else if (TREE_CODE (d) == FUNCTION_DECL)
15735     {
15736       htab_t saved_local_specializations;
15737       tree subst_decl;
15738       tree tmpl_parm;
15739       tree spec_parm;
15740
15741       /* Save away the current list, in case we are instantiating one
15742          template from within the body of another.  */
15743       saved_local_specializations = local_specializations;
15744
15745       /* Set up the list of local specializations.  */
15746       local_specializations = htab_create (37,
15747                                            hash_local_specialization,
15748                                            eq_local_specializations,
15749                                            NULL);
15750
15751       /* Set up context.  */
15752       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15753
15754       /* Create substitution entries for the parameters.  */
15755       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15756       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15757       spec_parm = DECL_ARGUMENTS (d);
15758       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15759         {
15760           register_local_specialization (spec_parm, tmpl_parm);
15761           spec_parm = skip_artificial_parms_for (d, spec_parm);
15762           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15763         }
15764       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15765         {
15766           register_local_specialization (spec_parm, tmpl_parm);
15767           tmpl_parm = TREE_CHAIN (tmpl_parm);
15768           spec_parm = TREE_CHAIN (spec_parm);
15769         }
15770       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15771         {
15772           /* Register the (value) argument pack as a specialization of
15773              TMPL_PARM, then move on.  */
15774           tree argpack = make_fnparm_pack (spec_parm);
15775           register_local_specialization (argpack, tmpl_parm);
15776           tmpl_parm = TREE_CHAIN (tmpl_parm);
15777           spec_parm = NULL_TREE;
15778         }
15779       gcc_assert (!spec_parm);
15780
15781       /* Substitute into the body of the function.  */
15782       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15783                    tf_warning_or_error, tmpl,
15784                    /*integral_constant_expression_p=*/false);
15785
15786       /* Set the current input_location to the end of the function
15787          so that finish_function knows where we are.  */
15788       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15789
15790       /* We don't need the local specializations any more.  */
15791       htab_delete (local_specializations);
15792       local_specializations = saved_local_specializations;
15793
15794       /* Finish the function.  */
15795       d = finish_function (0);
15796       expand_or_defer_fn (d);
15797     }
15798
15799   /* We're not deferring instantiation any more.  */
15800   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15801
15802   if (need_push)
15803     pop_from_top_level ();
15804
15805 out:
15806   input_location = saved_loc;
15807   pop_deferring_access_checks ();
15808   pop_tinst_level ();
15809
15810   timevar_pop (TV_PARSE);
15811
15812   return d;
15813 }
15814
15815 /* Run through the list of templates that we wish we could
15816    instantiate, and instantiate any we can.  RETRIES is the
15817    number of times we retry pending template instantiation.  */
15818
15819 void
15820 instantiate_pending_templates (int retries)
15821 {
15822   int reconsider;
15823   location_t saved_loc = input_location;
15824
15825   /* Instantiating templates may trigger vtable generation.  This in turn
15826      may require further template instantiations.  We place a limit here
15827      to avoid infinite loop.  */
15828   if (pending_templates && retries >= max_tinst_depth)
15829     {
15830       tree decl = pending_templates->tinst->decl;
15831
15832       error ("template instantiation depth exceeds maximum of %d"
15833              " instantiating %q+D, possibly from virtual table generation"
15834              " (use -ftemplate-depth-NN to increase the maximum)",
15835              max_tinst_depth, decl);
15836       if (TREE_CODE (decl) == FUNCTION_DECL)
15837         /* Pretend that we defined it.  */
15838         DECL_INITIAL (decl) = error_mark_node;
15839       return;
15840     }
15841
15842   do
15843     {
15844       struct pending_template **t = &pending_templates;
15845       struct pending_template *last = NULL;
15846       reconsider = 0;
15847       while (*t)
15848         {
15849           tree instantiation = reopen_tinst_level ((*t)->tinst);
15850           bool complete = false;
15851
15852           if (TYPE_P (instantiation))
15853             {
15854               tree fn;
15855
15856               if (!COMPLETE_TYPE_P (instantiation))
15857                 {
15858                   instantiate_class_template (instantiation);
15859                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15860                     for (fn = TYPE_METHODS (instantiation);
15861                          fn;
15862                          fn = TREE_CHAIN (fn))
15863                       if (! DECL_ARTIFICIAL (fn))
15864                         instantiate_decl (fn,
15865                                           /*defer_ok=*/0,
15866                                           /*expl_inst_class_mem_p=*/false);
15867                   if (COMPLETE_TYPE_P (instantiation))
15868                     reconsider = 1;
15869                 }
15870
15871               complete = COMPLETE_TYPE_P (instantiation);
15872             }
15873           else
15874             {
15875               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15876                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15877                 {
15878                   instantiation
15879                     = instantiate_decl (instantiation,
15880                                         /*defer_ok=*/0,
15881                                         /*expl_inst_class_mem_p=*/false);
15882                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15883                     reconsider = 1;
15884                 }
15885
15886               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15887                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15888             }
15889
15890           if (complete)
15891             /* If INSTANTIATION has been instantiated, then we don't
15892                need to consider it again in the future.  */
15893             *t = (*t)->next;
15894           else
15895             {
15896               last = *t;
15897               t = &(*t)->next;
15898             }
15899           tinst_depth = 0;
15900           current_tinst_level = NULL;
15901         }
15902       last_pending_template = last;
15903     }
15904   while (reconsider);
15905
15906   input_location = saved_loc;
15907 }
15908
15909 /* Substitute ARGVEC into T, which is a list of initializers for
15910    either base class or a non-static data member.  The TREE_PURPOSEs
15911    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15912    instantiate_decl.  */
15913
15914 static tree
15915 tsubst_initializer_list (tree t, tree argvec)
15916 {
15917   tree inits = NULL_TREE;
15918
15919   for (; t; t = TREE_CHAIN (t))
15920     {
15921       tree decl;
15922       tree init;
15923       tree expanded_bases = NULL_TREE;
15924       tree expanded_arguments = NULL_TREE;
15925       int i, len = 1;
15926
15927       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15928         {
15929           tree expr;
15930           tree arg;
15931
15932           /* Expand the base class expansion type into separate base
15933              classes.  */
15934           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15935                                                  tf_warning_or_error,
15936                                                  NULL_TREE);
15937           if (expanded_bases == error_mark_node)
15938             continue;
15939           
15940           /* We'll be building separate TREE_LISTs of arguments for
15941              each base.  */
15942           len = TREE_VEC_LENGTH (expanded_bases);
15943           expanded_arguments = make_tree_vec (len);
15944           for (i = 0; i < len; i++)
15945             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15946
15947           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15948              expand each argument in the TREE_VALUE of t.  */
15949           expr = make_node (EXPR_PACK_EXPANSION);
15950           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15951             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15952
15953           if (TREE_VALUE (t) == void_type_node)
15954             /* VOID_TYPE_NODE is used to indicate
15955                value-initialization.  */
15956             {
15957               for (i = 0; i < len; i++)
15958                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
15959             }
15960           else
15961             {
15962               /* Substitute parameter packs into each argument in the
15963                  TREE_LIST.  */
15964               in_base_initializer = 1;
15965               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15966                 {
15967                   tree expanded_exprs;
15968
15969                   /* Expand the argument.  */
15970                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15971                   expanded_exprs 
15972                     = tsubst_pack_expansion (expr, argvec,
15973                                              tf_warning_or_error,
15974                                              NULL_TREE);
15975                   if (expanded_exprs == error_mark_node)
15976                     continue;
15977
15978                   /* Prepend each of the expanded expressions to the
15979                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15980                   for (i = 0; i < len; i++)
15981                     {
15982                       TREE_VEC_ELT (expanded_arguments, i) = 
15983                         tree_cons (NULL_TREE, 
15984                                    TREE_VEC_ELT (expanded_exprs, i),
15985                                    TREE_VEC_ELT (expanded_arguments, i));
15986                     }
15987                 }
15988               in_base_initializer = 0;
15989
15990               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15991                  since we built them backwards.  */
15992               for (i = 0; i < len; i++)
15993                 {
15994                   TREE_VEC_ELT (expanded_arguments, i) = 
15995                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
15996                 }
15997             }
15998         }
15999
16000       for (i = 0; i < len; ++i)
16001         {
16002           if (expanded_bases)
16003             {
16004               decl = TREE_VEC_ELT (expanded_bases, i);
16005               decl = expand_member_init (decl);
16006               init = TREE_VEC_ELT (expanded_arguments, i);
16007             }
16008           else
16009             {
16010               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
16011                                   tf_warning_or_error, NULL_TREE);
16012
16013               decl = expand_member_init (decl);
16014               if (decl && !DECL_P (decl))
16015                 in_base_initializer = 1;
16016
16017               init = tsubst_expr (TREE_VALUE (t), argvec, 
16018                                   tf_warning_or_error, NULL_TREE,
16019                                   /*integral_constant_expression_p=*/false);
16020               in_base_initializer = 0;
16021             }
16022
16023           if (decl)
16024             {
16025               init = build_tree_list (decl, init);
16026               TREE_CHAIN (init) = inits;
16027               inits = init;
16028             }
16029         }
16030     }
16031   return inits;
16032 }
16033
16034 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
16035
16036 static void
16037 set_current_access_from_decl (tree decl)
16038 {
16039   if (TREE_PRIVATE (decl))
16040     current_access_specifier = access_private_node;
16041   else if (TREE_PROTECTED (decl))
16042     current_access_specifier = access_protected_node;
16043   else
16044     current_access_specifier = access_public_node;
16045 }
16046
16047 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
16048    is the instantiation (which should have been created with
16049    start_enum) and ARGS are the template arguments to use.  */
16050
16051 static void
16052 tsubst_enum (tree tag, tree newtag, tree args)
16053 {
16054   tree e;
16055
16056   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
16057     {
16058       tree value;
16059       tree decl;
16060
16061       decl = TREE_VALUE (e);
16062       /* Note that in a template enum, the TREE_VALUE is the
16063          CONST_DECL, not the corresponding INTEGER_CST.  */
16064       value = tsubst_expr (DECL_INITIAL (decl),
16065                            args, tf_warning_or_error, NULL_TREE,
16066                            /*integral_constant_expression_p=*/true);
16067
16068       /* Give this enumeration constant the correct access.  */
16069       set_current_access_from_decl (decl);
16070
16071       /* Actually build the enumerator itself.  */
16072       build_enumerator (DECL_NAME (decl), value, newtag);
16073     }
16074
16075   finish_enum (newtag);
16076   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
16077     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
16078 }
16079
16080 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
16081    its type -- but without substituting the innermost set of template
16082    arguments.  So, innermost set of template parameters will appear in
16083    the type.  */
16084
16085 tree
16086 get_mostly_instantiated_function_type (tree decl)
16087 {
16088   tree fn_type;
16089   tree tmpl;
16090   tree targs;
16091   tree tparms;
16092   int parm_depth;
16093
16094   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16095   targs = DECL_TI_ARGS (decl);
16096   tparms = DECL_TEMPLATE_PARMS (tmpl);
16097   parm_depth = TMPL_PARMS_DEPTH (tparms);
16098
16099   /* There should be as many levels of arguments as there are levels
16100      of parameters.  */
16101   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16102
16103   fn_type = TREE_TYPE (tmpl);
16104
16105   if (parm_depth == 1)
16106     /* No substitution is necessary.  */
16107     ;
16108   else
16109     {
16110       int i, save_access_control;
16111       tree partial_args;
16112
16113       /* Replace the innermost level of the TARGS with NULL_TREEs to
16114          let tsubst know not to substitute for those parameters.  */
16115       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16116       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16117         SET_TMPL_ARGS_LEVEL (partial_args, i,
16118                              TMPL_ARGS_LEVEL (targs, i));
16119       SET_TMPL_ARGS_LEVEL (partial_args,
16120                            TMPL_ARGS_DEPTH (targs),
16121                            make_tree_vec (DECL_NTPARMS (tmpl)));
16122
16123       /* Disable access control as this function is used only during
16124          name-mangling.  */
16125       save_access_control = flag_access_control;
16126       flag_access_control = 0;
16127
16128       ++processing_template_decl;
16129       /* Now, do the (partial) substitution to figure out the
16130          appropriate function type.  */
16131       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16132       --processing_template_decl;
16133
16134       /* Substitute into the template parameters to obtain the real
16135          innermost set of parameters.  This step is important if the
16136          innermost set of template parameters contains value
16137          parameters whose types depend on outer template parameters.  */
16138       TREE_VEC_LENGTH (partial_args)--;
16139       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16140
16141       flag_access_control = save_access_control;
16142     }
16143
16144   return fn_type;
16145 }
16146
16147 /* Return truthvalue if we're processing a template different from
16148    the last one involved in diagnostics.  */
16149 int
16150 problematic_instantiation_changed (void)
16151 {
16152   return last_template_error_tick != tinst_level_tick;
16153 }
16154
16155 /* Remember current template involved in diagnostics.  */
16156 void
16157 record_last_problematic_instantiation (void)
16158 {
16159   last_template_error_tick = tinst_level_tick;
16160 }
16161
16162 struct tinst_level *
16163 current_instantiation (void)
16164 {
16165   return current_tinst_level;
16166 }
16167
16168 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16169    type. Return zero for ok, nonzero for disallowed. Issue error and
16170    warning messages under control of COMPLAIN.  */
16171
16172 static int
16173 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16174 {
16175   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
16176     return 0;
16177   else if (POINTER_TYPE_P (type))
16178     return 0;
16179   else if (TYPE_PTR_TO_MEMBER_P (type))
16180     return 0;
16181   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16182     return 0;
16183   else if (TREE_CODE (type) == TYPENAME_TYPE)
16184     return 0;
16185
16186   if (complain & tf_error)
16187     error ("%q#T is not a valid type for a template constant parameter", type);
16188   return 1;
16189 }
16190
16191 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16192    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16193
16194 static bool
16195 dependent_type_p_r (tree type)
16196 {
16197   tree scope;
16198
16199   /* [temp.dep.type]
16200
16201      A type is dependent if it is:
16202
16203      -- a template parameter. Template template parameters are types
16204         for us (since TYPE_P holds true for them) so we handle
16205         them here.  */
16206   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16207       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
16208     return true;
16209   /* -- a qualified-id with a nested-name-specifier which contains a
16210         class-name that names a dependent type or whose unqualified-id
16211         names a dependent type.  */
16212   if (TREE_CODE (type) == TYPENAME_TYPE)
16213     return true;
16214   /* -- a cv-qualified type where the cv-unqualified type is
16215         dependent.  */
16216   type = TYPE_MAIN_VARIANT (type);
16217   /* -- a compound type constructed from any dependent type.  */
16218   if (TYPE_PTR_TO_MEMBER_P (type))
16219     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
16220             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
16221                                            (type)));
16222   else if (TREE_CODE (type) == POINTER_TYPE
16223            || TREE_CODE (type) == REFERENCE_TYPE)
16224     return dependent_type_p (TREE_TYPE (type));
16225   else if (TREE_CODE (type) == FUNCTION_TYPE
16226            || TREE_CODE (type) == METHOD_TYPE)
16227     {
16228       tree arg_type;
16229
16230       if (dependent_type_p (TREE_TYPE (type)))
16231         return true;
16232       for (arg_type = TYPE_ARG_TYPES (type);
16233            arg_type;
16234            arg_type = TREE_CHAIN (arg_type))
16235         if (dependent_type_p (TREE_VALUE (arg_type)))
16236           return true;
16237       return false;
16238     }
16239   /* -- an array type constructed from any dependent type or whose
16240         size is specified by a constant expression that is
16241         value-dependent.  */
16242   if (TREE_CODE (type) == ARRAY_TYPE)
16243     {
16244       if (TYPE_DOMAIN (type)
16245           && dependent_type_p (TYPE_DOMAIN (type)))
16246         return true;
16247       return dependent_type_p (TREE_TYPE (type));
16248     }
16249   else if (TREE_CODE (type) == INTEGER_TYPE
16250            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
16251     {
16252       /* If this is the TYPE_DOMAIN of an array type, consider it
16253          dependent.  We already checked for value-dependence in
16254          compute_array_index_type.  */
16255       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
16256     }
16257
16258   /* -- a template-id in which either the template name is a template
16259      parameter ...  */
16260   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16261     return true;
16262   /* ... or any of the template arguments is a dependent type or
16263         an expression that is type-dependent or value-dependent.  */
16264   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
16265            && (any_dependent_template_arguments_p
16266                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
16267     return true;
16268
16269   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
16270      argument of the `typeof' expression is not type-dependent, then
16271      it should already been have resolved.  */
16272   if (TREE_CODE (type) == TYPEOF_TYPE
16273       || TREE_CODE (type) == DECLTYPE_TYPE)
16274     return true;
16275
16276   /* A template argument pack is dependent if any of its packed
16277      arguments are.  */
16278   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
16279     {
16280       tree args = ARGUMENT_PACK_ARGS (type);
16281       int i, len = TREE_VEC_LENGTH (args);
16282       for (i = 0; i < len; ++i)
16283         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16284           return true;
16285     }
16286
16287   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
16288      be template parameters.  */
16289   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
16290     return true;
16291
16292   /* The standard does not specifically mention types that are local
16293      to template functions or local classes, but they should be
16294      considered dependent too.  For example:
16295
16296        template <int I> void f() {
16297          enum E { a = I };
16298          S<sizeof (E)> s;
16299        }
16300
16301      The size of `E' cannot be known until the value of `I' has been
16302      determined.  Therefore, `E' must be considered dependent.  */
16303   scope = TYPE_CONTEXT (type);
16304   if (scope && TYPE_P (scope))
16305     return dependent_type_p (scope);
16306   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
16307     return type_dependent_expression_p (scope);
16308
16309   /* Other types are non-dependent.  */
16310   return false;
16311 }
16312
16313 /* Returns TRUE if TYPE is dependent, in the sense of
16314    [temp.dep.type].  */
16315
16316 bool
16317 dependent_type_p (tree type)
16318 {
16319   /* If there are no template parameters in scope, then there can't be
16320      any dependent types.  */
16321   if (!processing_template_decl)
16322     {
16323       /* If we are not processing a template, then nobody should be
16324          providing us with a dependent type.  */
16325       gcc_assert (type);
16326       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
16327       return false;
16328     }
16329
16330   /* If the type is NULL, we have not computed a type for the entity
16331      in question; in that case, the type is dependent.  */
16332   if (!type)
16333     return true;
16334
16335   /* Erroneous types can be considered non-dependent.  */
16336   if (type == error_mark_node)
16337     return false;
16338
16339   /* If we have not already computed the appropriate value for TYPE,
16340      do so now.  */
16341   if (!TYPE_DEPENDENT_P_VALID (type))
16342     {
16343       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
16344       TYPE_DEPENDENT_P_VALID (type) = 1;
16345     }
16346
16347   return TYPE_DEPENDENT_P (type);
16348 }
16349
16350 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
16351    lookup.  In other words, a dependent type that is not the current
16352    instantiation.  */
16353
16354 bool
16355 dependent_scope_p (tree scope)
16356 {
16357   return (scope && TYPE_P (scope) && dependent_type_p (scope)
16358           && !currently_open_class (scope));
16359 }
16360
16361 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
16362
16363 static bool
16364 dependent_scope_ref_p (tree expression, bool criterion (tree))
16365 {
16366   tree scope;
16367   tree name;
16368
16369   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
16370
16371   if (!TYPE_P (TREE_OPERAND (expression, 0)))
16372     return true;
16373
16374   scope = TREE_OPERAND (expression, 0);
16375   name = TREE_OPERAND (expression, 1);
16376
16377   /* [temp.dep.expr]
16378
16379      An id-expression is type-dependent if it contains a
16380      nested-name-specifier that contains a class-name that names a
16381      dependent type.  */
16382   /* The suggested resolution to Core Issue 224 implies that if the
16383      qualifying type is the current class, then we must peek
16384      inside it.  */
16385   if (DECL_P (name)
16386       && currently_open_class (scope)
16387       && !criterion (name))
16388     return false;
16389   if (dependent_type_p (scope))
16390     return true;
16391
16392   return false;
16393 }
16394
16395 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
16396    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
16397    expression.  */
16398
16399 bool
16400 value_dependent_expression_p (tree expression)
16401 {
16402   if (!processing_template_decl)
16403     return false;
16404
16405   /* A name declared with a dependent type.  */
16406   if (DECL_P (expression) && type_dependent_expression_p (expression))
16407     return true;
16408
16409   switch (TREE_CODE (expression))
16410     {
16411     case IDENTIFIER_NODE:
16412       /* A name that has not been looked up -- must be dependent.  */
16413       return true;
16414
16415     case TEMPLATE_PARM_INDEX:
16416       /* A non-type template parm.  */
16417       return true;
16418
16419     case CONST_DECL:
16420       /* A non-type template parm.  */
16421       if (DECL_TEMPLATE_PARM_P (expression))
16422         return true;
16423       return value_dependent_expression_p (DECL_INITIAL (expression));
16424
16425     case VAR_DECL:
16426        /* A constant with integral or enumeration type and is initialized
16427           with an expression that is value-dependent.  */
16428       if (DECL_INITIAL (expression)
16429           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
16430           && value_dependent_expression_p (DECL_INITIAL (expression)))
16431         return true;
16432       return false;
16433
16434     case DYNAMIC_CAST_EXPR:
16435     case STATIC_CAST_EXPR:
16436     case CONST_CAST_EXPR:
16437     case REINTERPRET_CAST_EXPR:
16438     case CAST_EXPR:
16439       /* These expressions are value-dependent if the type to which
16440          the cast occurs is dependent or the expression being casted
16441          is value-dependent.  */
16442       {
16443         tree type = TREE_TYPE (expression);
16444
16445         if (dependent_type_p (type))
16446           return true;
16447
16448         /* A functional cast has a list of operands.  */
16449         expression = TREE_OPERAND (expression, 0);
16450         if (!expression)
16451           {
16452             /* If there are no operands, it must be an expression such
16453                as "int()". This should not happen for aggregate types
16454                because it would form non-constant expressions.  */
16455             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
16456
16457             return false;
16458           }
16459
16460         if (TREE_CODE (expression) == TREE_LIST)
16461           return any_value_dependent_elements_p (expression);
16462
16463         return value_dependent_expression_p (expression);
16464       }
16465
16466     case SIZEOF_EXPR:
16467     case ALIGNOF_EXPR:
16468       /* A `sizeof' expression is value-dependent if the operand is
16469          type-dependent or is a pack expansion.  */
16470       expression = TREE_OPERAND (expression, 0);
16471       if (PACK_EXPANSION_P (expression))
16472         return true;
16473       else if (TYPE_P (expression))
16474         return dependent_type_p (expression);
16475       return type_dependent_expression_p (expression);
16476
16477     case SCOPE_REF:
16478       return dependent_scope_ref_p (expression, value_dependent_expression_p);
16479
16480     case COMPONENT_REF:
16481       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
16482               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
16483
16484     case CALL_EXPR:
16485       /* A CALL_EXPR may appear in a constant expression if it is a
16486          call to a builtin function, e.g., __builtin_constant_p.  All
16487          such calls are value-dependent.  */
16488       return true;
16489
16490     case NONTYPE_ARGUMENT_PACK:
16491       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
16492          is value-dependent.  */
16493       {
16494         tree values = ARGUMENT_PACK_ARGS (expression);
16495         int i, len = TREE_VEC_LENGTH (values);
16496         
16497         for (i = 0; i < len; ++i)
16498           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
16499             return true;
16500         
16501         return false;
16502       }
16503
16504     case TRAIT_EXPR:
16505       {
16506         tree type2 = TRAIT_EXPR_TYPE2 (expression);
16507         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
16508                 || (type2 ? dependent_type_p (type2) : false));
16509       }
16510
16511     case MODOP_EXPR:
16512       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
16513               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
16514
16515     default:
16516       /* A constant expression is value-dependent if any subexpression is
16517          value-dependent.  */
16518       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
16519         {
16520         case tcc_reference:
16521         case tcc_unary:
16522           return (value_dependent_expression_p
16523                   (TREE_OPERAND (expression, 0)));
16524
16525         case tcc_comparison:
16526         case tcc_binary:
16527           return ((value_dependent_expression_p
16528                    (TREE_OPERAND (expression, 0)))
16529                   || (value_dependent_expression_p
16530                       (TREE_OPERAND (expression, 1))));
16531
16532         case tcc_expression:
16533         case tcc_vl_exp:
16534           {
16535             int i;
16536             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
16537               /* In some cases, some of the operands may be missing.
16538                  (For example, in the case of PREDECREMENT_EXPR, the
16539                  amount to increment by may be missing.)  That doesn't
16540                  make the expression dependent.  */
16541               if (TREE_OPERAND (expression, i)
16542                   && (value_dependent_expression_p
16543                       (TREE_OPERAND (expression, i))))
16544                 return true;
16545             return false;
16546           }
16547
16548         default:
16549           break;
16550         }
16551     }
16552
16553   /* The expression is not value-dependent.  */
16554   return false;
16555 }
16556
16557 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
16558    [temp.dep.expr].  */
16559
16560 bool
16561 type_dependent_expression_p (tree expression)
16562 {
16563   if (!processing_template_decl)
16564     return false;
16565
16566   if (expression == error_mark_node)
16567     return false;
16568
16569   /* An unresolved name is always dependent.  */
16570   if (TREE_CODE (expression) == IDENTIFIER_NODE
16571       || TREE_CODE (expression) == USING_DECL)
16572     return true;
16573
16574   /* Some expression forms are never type-dependent.  */
16575   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
16576       || TREE_CODE (expression) == SIZEOF_EXPR
16577       || TREE_CODE (expression) == ALIGNOF_EXPR
16578       || TREE_CODE (expression) == TRAIT_EXPR
16579       || TREE_CODE (expression) == TYPEID_EXPR
16580       || TREE_CODE (expression) == DELETE_EXPR
16581       || TREE_CODE (expression) == VEC_DELETE_EXPR
16582       || TREE_CODE (expression) == THROW_EXPR)
16583     return false;
16584
16585   /* The types of these expressions depends only on the type to which
16586      the cast occurs.  */
16587   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
16588       || TREE_CODE (expression) == STATIC_CAST_EXPR
16589       || TREE_CODE (expression) == CONST_CAST_EXPR
16590       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
16591       || TREE_CODE (expression) == CAST_EXPR)
16592     return dependent_type_p (TREE_TYPE (expression));
16593
16594   /* The types of these expressions depends only on the type created
16595      by the expression.  */
16596   if (TREE_CODE (expression) == NEW_EXPR
16597       || TREE_CODE (expression) == VEC_NEW_EXPR)
16598     {
16599       /* For NEW_EXPR tree nodes created inside a template, either
16600          the object type itself or a TREE_LIST may appear as the
16601          operand 1.  */
16602       tree type = TREE_OPERAND (expression, 1);
16603       if (TREE_CODE (type) == TREE_LIST)
16604         /* This is an array type.  We need to check array dimensions
16605            as well.  */
16606         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
16607                || value_dependent_expression_p
16608                     (TREE_OPERAND (TREE_VALUE (type), 1));
16609       else
16610         return dependent_type_p (type);
16611     }
16612
16613   if (TREE_CODE (expression) == SCOPE_REF
16614       && dependent_scope_ref_p (expression,
16615                                 type_dependent_expression_p))
16616     return true;
16617
16618   if (TREE_CODE (expression) == FUNCTION_DECL
16619       && DECL_LANG_SPECIFIC (expression)
16620       && DECL_TEMPLATE_INFO (expression)
16621       && (any_dependent_template_arguments_p
16622           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
16623     return true;
16624
16625   if (TREE_CODE (expression) == TEMPLATE_DECL
16626       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
16627     return false;
16628
16629   if (TREE_CODE (expression) == STMT_EXPR)
16630     expression = stmt_expr_value_expr (expression);
16631
16632   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
16633     {
16634       tree elt;
16635       unsigned i;
16636
16637       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
16638         {
16639           if (type_dependent_expression_p (elt))
16640             return true;
16641         }
16642       return false;
16643     }
16644
16645   if (TREE_TYPE (expression) == unknown_type_node)
16646     {
16647       if (TREE_CODE (expression) == ADDR_EXPR)
16648         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
16649       if (TREE_CODE (expression) == COMPONENT_REF
16650           || TREE_CODE (expression) == OFFSET_REF)
16651         {
16652           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
16653             return true;
16654           expression = TREE_OPERAND (expression, 1);
16655           if (TREE_CODE (expression) == IDENTIFIER_NODE)
16656             return false;
16657         }
16658       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
16659       if (TREE_CODE (expression) == SCOPE_REF)
16660         return false;
16661
16662       if (TREE_CODE (expression) == BASELINK)
16663         expression = BASELINK_FUNCTIONS (expression);
16664
16665       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
16666         {
16667           if (any_dependent_template_arguments_p
16668               (TREE_OPERAND (expression, 1)))
16669             return true;
16670           expression = TREE_OPERAND (expression, 0);
16671         }
16672       gcc_assert (TREE_CODE (expression) == OVERLOAD
16673                   || TREE_CODE (expression) == FUNCTION_DECL);
16674
16675       while (expression)
16676         {
16677           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16678             return true;
16679           expression = OVL_NEXT (expression);
16680         }
16681       return false;
16682     }
16683
16684   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16685
16686   return (dependent_type_p (TREE_TYPE (expression)));
16687 }
16688
16689 /* Like type_dependent_expression_p, but it also works while not processing
16690    a template definition, i.e. during substitution or mangling.  */
16691
16692 bool
16693 type_dependent_expression_p_push (tree expr)
16694 {
16695   bool b;
16696   ++processing_template_decl;
16697   b = type_dependent_expression_p (expr);
16698   --processing_template_decl;
16699   return b;
16700 }
16701
16702 /* Returns TRUE if ARGS contains a type-dependent expression.  */
16703
16704 bool
16705 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
16706 {
16707   unsigned int i;
16708   tree arg;
16709
16710   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
16711     {
16712       if (type_dependent_expression_p (arg))
16713         return true;
16714     }
16715   return false;
16716 }
16717
16718 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16719    expressions) contains any value-dependent expressions.  */
16720
16721 bool
16722 any_value_dependent_elements_p (const_tree list)
16723 {
16724   for (; list; list = TREE_CHAIN (list))
16725     if (value_dependent_expression_p (TREE_VALUE (list)))
16726       return true;
16727
16728   return false;
16729 }
16730
16731 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16732
16733 bool
16734 dependent_template_arg_p (tree arg)
16735 {
16736   if (!processing_template_decl)
16737     return false;
16738
16739   if (TREE_CODE (arg) == TEMPLATE_DECL
16740       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16741     return dependent_template_p (arg);
16742   else if (ARGUMENT_PACK_P (arg))
16743     {
16744       tree args = ARGUMENT_PACK_ARGS (arg);
16745       int i, len = TREE_VEC_LENGTH (args);
16746       for (i = 0; i < len; ++i)
16747         {
16748           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16749             return true;
16750         }
16751
16752       return false;
16753     }
16754   else if (TYPE_P (arg))
16755     return dependent_type_p (arg);
16756   else
16757     return (type_dependent_expression_p (arg)
16758             || value_dependent_expression_p (arg));
16759 }
16760
16761 /* Returns true if ARGS (a collection of template arguments) contains
16762    any types that require structural equality testing.  */
16763
16764 bool
16765 any_template_arguments_need_structural_equality_p (tree args)
16766 {
16767   int i;
16768   int j;
16769
16770   if (!args)
16771     return false;
16772   if (args == error_mark_node)
16773     return true;
16774
16775   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16776     {
16777       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16778       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16779         {
16780           tree arg = TREE_VEC_ELT (level, j);
16781           tree packed_args = NULL_TREE;
16782           int k, len = 1;
16783
16784           if (ARGUMENT_PACK_P (arg))
16785             {
16786               /* Look inside the argument pack.  */
16787               packed_args = ARGUMENT_PACK_ARGS (arg);
16788               len = TREE_VEC_LENGTH (packed_args);
16789             }
16790
16791           for (k = 0; k < len; ++k)
16792             {
16793               if (packed_args)
16794                 arg = TREE_VEC_ELT (packed_args, k);
16795
16796               if (error_operand_p (arg))
16797                 return true;
16798               else if (TREE_CODE (arg) == TEMPLATE_DECL
16799                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16800                 continue;
16801               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
16802                 return true;
16803               else if (!TYPE_P (arg) && TREE_TYPE (arg)
16804                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
16805                 return true;
16806             }
16807         }
16808     }
16809
16810   return false;
16811 }
16812
16813 /* Returns true if ARGS (a collection of template arguments) contains
16814    any dependent arguments.  */
16815
16816 bool
16817 any_dependent_template_arguments_p (const_tree args)
16818 {
16819   int i;
16820   int j;
16821
16822   if (!args)
16823     return false;
16824   if (args == error_mark_node)
16825     return true;
16826
16827   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16828     {
16829       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16830       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16831         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16832           return true;
16833     }
16834
16835   return false;
16836 }
16837
16838 /* Returns TRUE if the template TMPL is dependent.  */
16839
16840 bool
16841 dependent_template_p (tree tmpl)
16842 {
16843   if (TREE_CODE (tmpl) == OVERLOAD)
16844     {
16845       while (tmpl)
16846         {
16847           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16848             return true;
16849           tmpl = OVL_CHAIN (tmpl);
16850         }
16851       return false;
16852     }
16853
16854   /* Template template parameters are dependent.  */
16855   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16856       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16857     return true;
16858   /* So are names that have not been looked up.  */
16859   if (TREE_CODE (tmpl) == SCOPE_REF
16860       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16861     return true;
16862   /* So are member templates of dependent classes.  */
16863   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16864     return dependent_type_p (DECL_CONTEXT (tmpl));
16865   return false;
16866 }
16867
16868 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16869
16870 bool
16871 dependent_template_id_p (tree tmpl, tree args)
16872 {
16873   return (dependent_template_p (tmpl)
16874           || any_dependent_template_arguments_p (args));
16875 }
16876
16877 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
16878    is dependent.  */
16879
16880 bool
16881 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
16882 {
16883   int i;
16884
16885   if (!processing_template_decl)
16886     return false;
16887
16888   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
16889     {
16890       tree decl = TREE_VEC_ELT (declv, i);
16891       tree init = TREE_VEC_ELT (initv, i);
16892       tree cond = TREE_VEC_ELT (condv, i);
16893       tree incr = TREE_VEC_ELT (incrv, i);
16894
16895       if (type_dependent_expression_p (decl))
16896         return true;
16897
16898       if (init && type_dependent_expression_p (init))
16899         return true;
16900
16901       if (type_dependent_expression_p (cond))
16902         return true;
16903
16904       if (COMPARISON_CLASS_P (cond)
16905           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
16906               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
16907         return true;
16908
16909       if (TREE_CODE (incr) == MODOP_EXPR)
16910         {
16911           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
16912               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
16913             return true;
16914         }
16915       else if (type_dependent_expression_p (incr))
16916         return true;
16917       else if (TREE_CODE (incr) == MODIFY_EXPR)
16918         {
16919           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
16920             return true;
16921           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
16922             {
16923               tree t = TREE_OPERAND (incr, 1);
16924               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
16925                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
16926                 return true;
16927             }
16928         }
16929     }
16930
16931   return false;
16932 }
16933
16934 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16935    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16936    no such TYPE can be found.  Note that this function peers inside
16937    uninstantiated templates and therefore should be used only in
16938    extremely limited situations.  ONLY_CURRENT_P restricts this
16939    peering to the currently open classes hierarchy (which is required
16940    when comparing types).  */
16941
16942 tree
16943 resolve_typename_type (tree type, bool only_current_p)
16944 {
16945   tree scope;
16946   tree name;
16947   tree decl;
16948   int quals;
16949   tree pushed_scope;
16950   tree result;
16951
16952   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16953
16954   scope = TYPE_CONTEXT (type);
16955   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
16956      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
16957      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
16958      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
16959      identifier  of the TYPENAME_TYPE anymore.
16960      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
16961      TYPENAME_TYPE instead, we avoid messing up with a possible
16962      typedef variant case.  */
16963   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
16964
16965   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16966      it first before we can figure out what NAME refers to.  */
16967   if (TREE_CODE (scope) == TYPENAME_TYPE)
16968     scope = resolve_typename_type (scope, only_current_p);
16969   /* If we don't know what SCOPE refers to, then we cannot resolve the
16970      TYPENAME_TYPE.  */
16971   if (TREE_CODE (scope) == TYPENAME_TYPE)
16972     return type;
16973   /* If the SCOPE is a template type parameter, we have no way of
16974      resolving the name.  */
16975   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16976     return type;
16977   /* If the SCOPE is not the current instantiation, there's no reason
16978      to look inside it.  */
16979   if (only_current_p && !currently_open_class (scope))
16980     return type;
16981   /* If SCOPE isn't the template itself, it will not have a valid
16982      TYPE_FIELDS list.  */
16983   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16984     /* scope is either the template itself or a compatible instantiation
16985        like X<T>, so look up the name in the original template.  */
16986     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16987   else
16988     /* scope is a partial instantiation, so we can't do the lookup or we
16989        will lose the template arguments.  */
16990     return type;
16991   /* Enter the SCOPE so that name lookup will be resolved as if we
16992      were in the class definition.  In particular, SCOPE will no
16993      longer be considered a dependent type.  */
16994   pushed_scope = push_scope (scope);
16995   /* Look up the declaration.  */
16996   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16997
16998   result = NULL_TREE;
16999   
17000   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
17001      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
17002   if (!decl)
17003     /*nop*/;
17004   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
17005            && TREE_CODE (decl) == TYPE_DECL)
17006     {
17007       result = TREE_TYPE (decl);
17008       if (result == error_mark_node)
17009         result = NULL_TREE;
17010     }
17011   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
17012            && DECL_CLASS_TEMPLATE_P (decl))
17013     {
17014       tree tmpl;
17015       tree args;
17016       /* Obtain the template and the arguments.  */
17017       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
17018       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
17019       /* Instantiate the template.  */
17020       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
17021                                       /*entering_scope=*/0,
17022                                       tf_error | tf_user);
17023       if (result == error_mark_node)
17024         result = NULL_TREE;
17025     }
17026   
17027   /* Leave the SCOPE.  */
17028   if (pushed_scope)
17029     pop_scope (pushed_scope);
17030
17031   /* If we failed to resolve it, return the original typename.  */
17032   if (!result)
17033     return type;
17034   
17035   /* If lookup found a typename type, resolve that too.  */
17036   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
17037     {
17038       /* Ill-formed programs can cause infinite recursion here, so we
17039          must catch that.  */
17040       TYPENAME_IS_RESOLVING_P (type) = 1;
17041       result = resolve_typename_type (result, only_current_p);
17042       TYPENAME_IS_RESOLVING_P (type) = 0;
17043     }
17044   
17045   /* Qualify the resulting type.  */
17046   quals = cp_type_quals (type);
17047   if (quals)
17048     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
17049
17050   return result;
17051 }
17052
17053 /* EXPR is an expression which is not type-dependent.  Return a proxy
17054    for EXPR that can be used to compute the types of larger
17055    expressions containing EXPR.  */
17056
17057 tree
17058 build_non_dependent_expr (tree expr)
17059 {
17060   tree inner_expr;
17061
17062   /* Preserve null pointer constants so that the type of things like
17063      "p == 0" where "p" is a pointer can be determined.  */
17064   if (null_ptr_cst_p (expr))
17065     return expr;
17066   /* Preserve OVERLOADs; the functions must be available to resolve
17067      types.  */
17068   inner_expr = expr;
17069   if (TREE_CODE (inner_expr) == STMT_EXPR)
17070     inner_expr = stmt_expr_value_expr (inner_expr);
17071   if (TREE_CODE (inner_expr) == ADDR_EXPR)
17072     inner_expr = TREE_OPERAND (inner_expr, 0);
17073   if (TREE_CODE (inner_expr) == COMPONENT_REF)
17074     inner_expr = TREE_OPERAND (inner_expr, 1);
17075   if (is_overloaded_fn (inner_expr)
17076       || TREE_CODE (inner_expr) == OFFSET_REF)
17077     return expr;
17078   /* There is no need to return a proxy for a variable.  */
17079   if (TREE_CODE (expr) == VAR_DECL)
17080     return expr;
17081   /* Preserve string constants; conversions from string constants to
17082      "char *" are allowed, even though normally a "const char *"
17083      cannot be used to initialize a "char *".  */
17084   if (TREE_CODE (expr) == STRING_CST)
17085     return expr;
17086   /* Preserve arithmetic constants, as an optimization -- there is no
17087      reason to create a new node.  */
17088   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
17089     return expr;
17090   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
17091      There is at least one place where we want to know that a
17092      particular expression is a throw-expression: when checking a ?:
17093      expression, there are special rules if the second or third
17094      argument is a throw-expression.  */
17095   if (TREE_CODE (expr) == THROW_EXPR)
17096     return expr;
17097
17098   if (TREE_CODE (expr) == COND_EXPR)
17099     return build3 (COND_EXPR,
17100                    TREE_TYPE (expr),
17101                    TREE_OPERAND (expr, 0),
17102                    (TREE_OPERAND (expr, 1)
17103                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
17104                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
17105                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
17106   if (TREE_CODE (expr) == COMPOUND_EXPR
17107       && !COMPOUND_EXPR_OVERLOADED (expr))
17108     return build2 (COMPOUND_EXPR,
17109                    TREE_TYPE (expr),
17110                    TREE_OPERAND (expr, 0),
17111                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17112
17113   /* If the type is unknown, it can't really be non-dependent */
17114   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17115
17116   /* Otherwise, build a NON_DEPENDENT_EXPR.
17117
17118      REFERENCE_TYPEs are not stripped for expressions in templates
17119      because doing so would play havoc with mangling.  Consider, for
17120      example:
17121
17122        template <typename T> void f<T& g>() { g(); }
17123
17124      In the body of "f", the expression for "g" will have
17125      REFERENCE_TYPE, even though the standard says that it should
17126      not.  The reason is that we must preserve the syntactic form of
17127      the expression so that mangling (say) "f<g>" inside the body of
17128      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17129      stripped here.  */
17130   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17131 }
17132
17133 /* ARGS is a vector of expressions as arguments to a function call.
17134    Replace the arguments with equivalent non-dependent expressions.
17135    This modifies ARGS in place.  */
17136
17137 void
17138 make_args_non_dependent (VEC(tree,gc) *args)
17139 {
17140   unsigned int ix;
17141   tree arg;
17142
17143   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
17144     {
17145       tree newarg = build_non_dependent_expr (arg);
17146       if (newarg != arg)
17147         VEC_replace (tree, args, ix, newarg);
17148     }
17149 }
17150
17151 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17152    with a level one deeper than the actual template parms.  */
17153
17154 tree
17155 make_auto (void)
17156 {
17157   tree au;
17158
17159   /* ??? Is it worth caching this for multiple autos at the same level?  */
17160   au = cxx_make_type (TEMPLATE_TYPE_PARM);
17161   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
17162                                TYPE_DECL, get_identifier ("auto"), au);
17163   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17164   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17165     (0, processing_template_decl + 1, processing_template_decl + 1,
17166      TYPE_NAME (au), NULL_TREE);
17167   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17168   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17169   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17170
17171   return au;
17172 }
17173
17174 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17175
17176 static tree
17177 listify_autos (tree type, tree auto_node)
17178 {
17179   tree std_init_list = namespace_binding
17180     (get_identifier ("initializer_list"), std_node);
17181   tree argvec;
17182   tree init_auto;
17183   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17184     {    
17185       error ("deducing auto from brace-enclosed initializer list requires "
17186              "#include <initializer_list>");
17187       return error_mark_node;
17188     }
17189   argvec = make_tree_vec (1);
17190   TREE_VEC_ELT (argvec, 0) = auto_node;
17191   init_auto = lookup_template_class (std_init_list, argvec, NULL_TREE,
17192                                      NULL_TREE, 0, tf_warning_or_error);
17193
17194   TREE_VEC_ELT (argvec, 0) = init_auto;
17195   if (processing_template_decl)
17196     argvec = add_to_template_args (current_template_args (), argvec);
17197   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17198 }
17199
17200 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
17201    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
17202
17203 tree
17204 do_auto_deduction (tree type, tree init, tree auto_node)
17205 {
17206   tree parms, tparms, targs;
17207   tree args[1];
17208   int val;
17209
17210   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
17211      with either a new invented type template parameter U or, if the
17212      initializer is a braced-init-list (8.5.4), with
17213      std::initializer_list<U>.  */
17214   if (BRACE_ENCLOSED_INITIALIZER_P (init))
17215     type = listify_autos (type, auto_node);
17216
17217   parms = build_tree_list (NULL_TREE, type);
17218   args[0] = init;
17219   tparms = make_tree_vec (1);
17220   targs = make_tree_vec (1);
17221   TREE_VEC_ELT (tparms, 0)
17222     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
17223   val = type_unification_real (tparms, targs, parms, args, 1, 0,
17224                                DEDUCE_CALL, LOOKUP_NORMAL);
17225   if (val > 0)
17226     {
17227       error ("unable to deduce %qT from %qE", type, init);
17228       return error_mark_node;
17229     }
17230
17231   if (processing_template_decl)
17232     targs = add_to_template_args (current_template_args (), targs);
17233   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
17234 }
17235
17236 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
17237    result.  */
17238
17239 tree
17240 splice_late_return_type (tree type, tree late_return_type)
17241 {
17242   tree argvec;
17243
17244   if (late_return_type == NULL_TREE)
17245     return type;
17246   argvec = make_tree_vec (1);
17247   TREE_VEC_ELT (argvec, 0) = late_return_type;
17248   if (processing_template_decl)
17249     argvec = add_to_template_args (current_template_args (), argvec);
17250   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17251 }
17252
17253 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
17254
17255 bool
17256 is_auto (const_tree type)
17257 {
17258   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17259       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
17260     return true;
17261   else
17262     return false;
17263 }
17264
17265 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
17266    appear as a type-specifier for the declaration in question, we don't
17267    have to look through the whole type.  */
17268
17269 tree
17270 type_uses_auto (tree type)
17271 {
17272   enum tree_code code;
17273   if (is_auto (type))
17274     return type;
17275
17276   code = TREE_CODE (type);
17277
17278   if (code == POINTER_TYPE || code == REFERENCE_TYPE
17279       || code == OFFSET_TYPE || code == FUNCTION_TYPE
17280       || code == METHOD_TYPE || code == ARRAY_TYPE)
17281     return type_uses_auto (TREE_TYPE (type));
17282
17283   if (TYPE_PTRMEMFUNC_P (type))
17284     return type_uses_auto (TREE_TYPE (TREE_TYPE
17285                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
17286
17287   return NULL_TREE;
17288 }
17289
17290 /* For a given template T, return the list of typedefs referenced
17291    in T for which access check is needed at T instantiation time.
17292    T is either  a FUNCTION_DECL or a RECORD_TYPE.
17293    Those typedefs were added to T by the function
17294    append_type_to_template_for_access_check.  */
17295
17296 tree
17297 get_types_needing_access_check (tree t)
17298 {
17299   tree ti, result = NULL_TREE;
17300
17301   if (!t || t == error_mark_node)
17302     return t;
17303
17304   if (!(ti = get_template_info (t)))
17305     return NULL_TREE;
17306
17307   if (TREE_CODE (t) == RECORD_TYPE || TREE_CODE (t) == FUNCTION_DECL)
17308     {
17309       if (!TI_TEMPLATE (ti))
17310         return NULL_TREE;
17311
17312       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
17313     }
17314
17315   return result;
17316 }
17317
17318 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
17319    tied to T. That list of typedefs will be access checked at
17320    T instantiation time.
17321    T is either a FUNCTION_DECL or a RECORD_TYPE.
17322    TYPE_DECL is a TYPE_DECL node representing a typedef.
17323    SCOPE is the scope through which TYPE_DECL is accessed.
17324
17325    This function is a subroutine of
17326    append_type_to_template_for_access_check.  */
17327
17328 static void
17329 append_type_to_template_for_access_check_1 (tree t,
17330                                             tree type_decl,
17331                                             tree scope)
17332 {
17333   tree ti;
17334
17335   if (!t || t == error_mark_node)
17336     return;
17337
17338   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
17339                || TREE_CODE (t) == RECORD_TYPE)
17340               && type_decl
17341               && TREE_CODE (type_decl) == TYPE_DECL
17342               && scope);
17343
17344   if (!(ti = get_template_info (t)))
17345     return;
17346
17347   gcc_assert (TI_TEMPLATE (ti));
17348
17349   TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti) =
17350     tree_cons (type_decl, scope, TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti));
17351 }
17352
17353 /* Append TYPE_DECL to the template TEMPL.
17354    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
17355    At TEMPL instanciation time, TYPE_DECL will be checked to see
17356    if it can be accessed through SCOPE.
17357
17358    e.g. consider the following code snippet:
17359
17360      class C
17361      {
17362        typedef int myint;
17363      };
17364
17365      template<class U> struct S
17366      {
17367        C::myint mi;
17368      };
17369
17370      S<char> s;
17371
17372    At S<char> instantiation time, we need to check the access of C::myint
17373    In other words, we need to check the access of the myint typedef through
17374    the C scope. For that purpose, this function will add the myint typedef
17375    and the scope C through which its being accessed to a list of typedefs
17376    tied to the template S. That list will be walked at template instantiation
17377    time and access check performed on each typedefs it contains.
17378    Note that this particular code snippet should yield an error because
17379    myint is private to C.  */
17380
17381 void
17382 append_type_to_template_for_access_check (tree templ,
17383                                           tree type_decl,
17384                                           tree scope)
17385 {
17386   tree node;
17387
17388   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
17389
17390   /* Make sure we don't append the type to the template twice.  */
17391   for (node = get_types_needing_access_check (templ);
17392        node;
17393        node = TREE_CHAIN (node))
17394     {
17395       tree decl = TREE_PURPOSE (node);
17396       tree type_scope = TREE_VALUE (node);
17397
17398       if (decl == type_decl && type_scope == scope)
17399         return;
17400     }
17401
17402   append_type_to_template_for_access_check_1 (templ, type_decl, scope);
17403 }
17404
17405 #include "gt-cp-pt.h"