Import gcc-4.4.2
[dragonfly.git] / contrib / gcc-4.4 / 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 pending_template GTY (()) {
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, tree,
122                                    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 (tree, tree, tsubst_flags_t, tree);
174 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
175 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
176 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
177 static tree tsubst_decl (tree, tree, tsubst_flags_t);
178 static tree listify (tree);
179 static tree listify_autos (tree, tree);
180
181 /* Make the current scope suitable for access checking when we are
182    processing T.  T can be FUNCTION_DECL for instantiated function
183    template, or VAR_DECL for static member variable (need by
184    instantiate_decl).  */
185
186 static void
187 push_access_scope (tree t)
188 {
189   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
190               || TREE_CODE (t) == VAR_DECL);
191
192   if (DECL_FRIEND_CONTEXT (t))
193     push_nested_class (DECL_FRIEND_CONTEXT (t));
194   else if (DECL_CLASS_SCOPE_P (t))
195     push_nested_class (DECL_CONTEXT (t));
196   else
197     push_to_top_level ();
198
199   if (TREE_CODE (t) == FUNCTION_DECL)
200     {
201       saved_access_scope = tree_cons
202         (NULL_TREE, current_function_decl, saved_access_scope);
203       current_function_decl = t;
204     }
205 }
206
207 /* Restore the scope set up by push_access_scope.  T is the node we
208    are processing.  */
209
210 static void
211 pop_access_scope (tree t)
212 {
213   if (TREE_CODE (t) == FUNCTION_DECL)
214     {
215       current_function_decl = TREE_VALUE (saved_access_scope);
216       saved_access_scope = TREE_CHAIN (saved_access_scope);
217     }
218
219   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
220     pop_nested_class ();
221   else
222     pop_from_top_level ();
223 }
224
225 /* Do any processing required when DECL (a member template
226    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
227    to DECL, unless it is a specialization, in which case the DECL
228    itself is returned.  */
229
230 tree
231 finish_member_template_decl (tree decl)
232 {
233   if (decl == error_mark_node)
234     return error_mark_node;
235
236   gcc_assert (DECL_P (decl));
237
238   if (TREE_CODE (decl) == TYPE_DECL)
239     {
240       tree type;
241
242       type = TREE_TYPE (decl);
243       if (type == error_mark_node)
244         return error_mark_node;
245       if (MAYBE_CLASS_TYPE_P (type)
246           && CLASSTYPE_TEMPLATE_INFO (type)
247           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
248         {
249           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
250           check_member_template (tmpl);
251           return tmpl;
252         }
253       return NULL_TREE;
254     }
255   else if (TREE_CODE (decl) == FIELD_DECL)
256     error ("data member %qD cannot be a member template", decl);
257   else if (DECL_TEMPLATE_INFO (decl))
258     {
259       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
260         {
261           check_member_template (DECL_TI_TEMPLATE (decl));
262           return DECL_TI_TEMPLATE (decl);
263         }
264       else
265         return decl;
266     }
267   else
268     error ("invalid member template declaration %qD", decl);
269
270   return error_mark_node;
271 }
272
273 /* Return the template info node corresponding to T, whatever T is.  */
274
275 tree
276 get_template_info (tree t)
277 {
278   tree tinfo = NULL_TREE;
279
280   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
281     tinfo = DECL_TEMPLATE_INFO (t);
282
283   if (!tinfo && TREE_CODE (t) == TYPE_DECL)
284     t = TREE_TYPE (t);
285
286   if (TAGGED_TYPE_P (t))
287     tinfo = TYPE_TEMPLATE_INFO (t);
288
289   return tinfo;
290 }
291
292 /* Returns the template nesting level of the indicated class TYPE.
293
294    For example, in:
295      template <class T>
296      struct A
297      {
298        template <class U>
299        struct B {};
300      };
301
302    A<T>::B<U> has depth two, while A<T> has depth one.
303    Both A<T>::B<int> and A<int>::B<U> have depth one, if
304    they are instantiations, not specializations.
305
306    This function is guaranteed to return 0 if passed NULL_TREE so
307    that, for example, `template_class_depth (current_class_type)' is
308    always safe.  */
309
310 int
311 template_class_depth (tree type)
312 {
313   int depth;
314
315   for (depth = 0;
316        type && TREE_CODE (type) != NAMESPACE_DECL;
317        type = (TREE_CODE (type) == FUNCTION_DECL)
318          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
319     {
320       tree tinfo = get_template_info (type);
321
322       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
323           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
324         ++depth;
325     }
326
327   return depth;
328 }
329
330 /* Subroutine of maybe_begin_member_template_processing.
331    Returns true if processing DECL needs us to push template parms.  */
332
333 static bool
334 inline_needs_template_parms (tree decl)
335 {
336   if (! DECL_TEMPLATE_INFO (decl))
337     return false;
338
339   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
340           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
341 }
342
343 /* Subroutine of maybe_begin_member_template_processing.
344    Push the template parms in PARMS, starting from LEVELS steps into the
345    chain, and ending at the beginning, since template parms are listed
346    innermost first.  */
347
348 static void
349 push_inline_template_parms_recursive (tree parmlist, int levels)
350 {
351   tree parms = TREE_VALUE (parmlist);
352   int i;
353
354   if (levels > 1)
355     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
356
357   ++processing_template_decl;
358   current_template_parms
359     = tree_cons (size_int (processing_template_decl),
360                  parms, current_template_parms);
361   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
362
363   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
364                NULL);
365   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
366     {
367       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
368
369       if (parm == error_mark_node)
370         continue;
371
372       gcc_assert (DECL_P (parm));
373
374       switch (TREE_CODE (parm))
375         {
376         case TYPE_DECL:
377         case TEMPLATE_DECL:
378           pushdecl (parm);
379           break;
380
381         case PARM_DECL:
382           {
383             /* Make a CONST_DECL as is done in process_template_parm.
384                It is ugly that we recreate this here; the original
385                version built in process_template_parm is no longer
386                available.  */
387             tree decl = build_decl (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           && TAGGED_TYPE_P (TREE_TYPE (tmpl)))
955         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
956       else
957         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
958       head = sp;
959       /* Iterate through the list until we find a matching template.  */
960       while (*sp != NULL_TREE)
961         {
962           tree spec = *sp;
963
964           if (comp_template_args (TREE_PURPOSE (spec), args))
965             {
966               /* Use the move-to-front heuristic to speed up future
967                  searches.  */
968               if (spec != *head)
969                 {
970                   *sp = TREE_CHAIN (*sp);
971                   TREE_CHAIN (spec) = *head;
972                   *head = spec;
973                 }
974               return TREE_VALUE (spec);
975             }
976           sp = &TREE_CHAIN (spec);
977         }
978     }
979
980   return NULL_TREE;
981 }
982
983 /* Like retrieve_specialization, but for local declarations.  */
984
985 static tree
986 retrieve_local_specialization (tree tmpl)
987 {
988   tree spec;
989
990   if (local_specializations == NULL)
991     return NULL_TREE;
992
993   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
994                                      htab_hash_pointer (tmpl));
995   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
996 }
997
998 /* Returns nonzero iff DECL is a specialization of TMPL.  */
999
1000 int
1001 is_specialization_of (tree decl, tree tmpl)
1002 {
1003   tree t;
1004
1005   if (TREE_CODE (decl) == FUNCTION_DECL)
1006     {
1007       for (t = decl;
1008            t != NULL_TREE;
1009            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1010         if (t == tmpl)
1011           return 1;
1012     }
1013   else
1014     {
1015       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1016
1017       for (t = TREE_TYPE (decl);
1018            t != NULL_TREE;
1019            t = CLASSTYPE_USE_TEMPLATE (t)
1020              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1021         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1022           return 1;
1023     }
1024
1025   return 0;
1026 }
1027
1028 /* Returns nonzero iff DECL is a specialization of friend declaration
1029    FRIEND_DECL according to [temp.friend].  */
1030
1031 bool
1032 is_specialization_of_friend (tree decl, tree friend_decl)
1033 {
1034   bool need_template = true;
1035   int template_depth;
1036
1037   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1038               || TREE_CODE (decl) == TYPE_DECL);
1039
1040   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1041      of a template class, we want to check if DECL is a specialization
1042      if this.  */
1043   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1044       && DECL_TEMPLATE_INFO (friend_decl)
1045       && !DECL_USE_TEMPLATE (friend_decl))
1046     {
1047       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1048       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1049       need_template = false;
1050     }
1051   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1052            && !PRIMARY_TEMPLATE_P (friend_decl))
1053     need_template = false;
1054
1055   /* There is nothing to do if this is not a template friend.  */
1056   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1057     return false;
1058
1059   if (is_specialization_of (decl, friend_decl))
1060     return true;
1061
1062   /* [temp.friend/6]
1063      A member of a class template may be declared to be a friend of a
1064      non-template class.  In this case, the corresponding member of
1065      every specialization of the class template is a friend of the
1066      class granting friendship.
1067
1068      For example, given a template friend declaration
1069
1070        template <class T> friend void A<T>::f();
1071
1072      the member function below is considered a friend
1073
1074        template <> struct A<int> {
1075          void f();
1076        };
1077
1078      For this type of template friend, TEMPLATE_DEPTH below will be
1079      nonzero.  To determine if DECL is a friend of FRIEND, we first
1080      check if the enclosing class is a specialization of another.  */
1081
1082   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1083   if (template_depth
1084       && DECL_CLASS_SCOPE_P (decl)
1085       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1086                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1087     {
1088       /* Next, we check the members themselves.  In order to handle
1089          a few tricky cases, such as when FRIEND_DECL's are
1090
1091            template <class T> friend void A<T>::g(T t);
1092            template <class T> template <T t> friend void A<T>::h();
1093
1094          and DECL's are
1095
1096            void A<int>::g(int);
1097            template <int> void A<int>::h();
1098
1099          we need to figure out ARGS, the template arguments from
1100          the context of DECL.  This is required for template substitution
1101          of `T' in the function parameter of `g' and template parameter
1102          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1103
1104       tree context = DECL_CONTEXT (decl);
1105       tree args = NULL_TREE;
1106       int current_depth = 0;
1107
1108       while (current_depth < template_depth)
1109         {
1110           if (CLASSTYPE_TEMPLATE_INFO (context))
1111             {
1112               if (current_depth == 0)
1113                 args = TYPE_TI_ARGS (context);
1114               else
1115                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1116               current_depth++;
1117             }
1118           context = TYPE_CONTEXT (context);
1119         }
1120
1121       if (TREE_CODE (decl) == FUNCTION_DECL)
1122         {
1123           bool is_template;
1124           tree friend_type;
1125           tree decl_type;
1126           tree friend_args_type;
1127           tree decl_args_type;
1128
1129           /* Make sure that both DECL and FRIEND_DECL are templates or
1130              non-templates.  */
1131           is_template = DECL_TEMPLATE_INFO (decl)
1132                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1133           if (need_template ^ is_template)
1134             return false;
1135           else if (is_template)
1136             {
1137               /* If both are templates, check template parameter list.  */
1138               tree friend_parms
1139                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1140                                          args, tf_none);
1141               if (!comp_template_parms
1142                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1143                       friend_parms))
1144                 return false;
1145
1146               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1147             }
1148           else
1149             decl_type = TREE_TYPE (decl);
1150
1151           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1152                                               tf_none, NULL_TREE);
1153           if (friend_type == error_mark_node)
1154             return false;
1155
1156           /* Check if return types match.  */
1157           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1158             return false;
1159
1160           /* Check if function parameter types match, ignoring the
1161              `this' parameter.  */
1162           friend_args_type = TYPE_ARG_TYPES (friend_type);
1163           decl_args_type = TYPE_ARG_TYPES (decl_type);
1164           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1165             friend_args_type = TREE_CHAIN (friend_args_type);
1166           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1167             decl_args_type = TREE_CHAIN (decl_args_type);
1168
1169           return compparms (decl_args_type, friend_args_type);
1170         }
1171       else
1172         {
1173           /* DECL is a TYPE_DECL */
1174           bool is_template;
1175           tree decl_type = TREE_TYPE (decl);
1176
1177           /* Make sure that both DECL and FRIEND_DECL are templates or
1178              non-templates.  */
1179           is_template
1180             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1181               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1182
1183           if (need_template ^ is_template)
1184             return false;
1185           else if (is_template)
1186             {
1187               tree friend_parms;
1188               /* If both are templates, check the name of the two
1189                  TEMPLATE_DECL's first because is_friend didn't.  */
1190               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1191                   != DECL_NAME (friend_decl))
1192                 return false;
1193
1194               /* Now check template parameter list.  */
1195               friend_parms
1196                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1197                                          args, tf_none);
1198               return comp_template_parms
1199                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1200                  friend_parms);
1201             }
1202           else
1203             return (DECL_NAME (decl)
1204                     == DECL_NAME (friend_decl));
1205         }
1206     }
1207   return false;
1208 }
1209
1210 /* Register the specialization SPEC as a specialization of TMPL with
1211    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1212    is actually just a friend declaration.  Returns SPEC, or an
1213    equivalent prior declaration, if available.  */
1214
1215 static tree
1216 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1217 {
1218   tree fn;
1219
1220   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1221
1222   if (TREE_CODE (spec) == FUNCTION_DECL
1223       && uses_template_parms (DECL_TI_ARGS (spec)))
1224     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1225        register it; we want the corresponding TEMPLATE_DECL instead.
1226        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1227        the more obvious `uses_template_parms (spec)' to avoid problems
1228        with default function arguments.  In particular, given
1229        something like this:
1230
1231           template <class T> void f(T t1, T t = T())
1232
1233        the default argument expression is not substituted for in an
1234        instantiation unless and until it is actually needed.  */
1235     return spec;
1236
1237   fn = retrieve_specialization (tmpl, args,
1238                                 /*class_specializations_p=*/false);
1239   /* We can sometimes try to re-register a specialization that we've
1240      already got.  In particular, regenerate_decl_from_template calls
1241      duplicate_decls which will update the specialization list.  But,
1242      we'll still get called again here anyhow.  It's more convenient
1243      to simply allow this than to try to prevent it.  */
1244   if (fn == spec)
1245     return spec;
1246   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1247     {
1248       if (DECL_TEMPLATE_INSTANTIATION (fn))
1249         {
1250           if (TREE_USED (fn)
1251               || DECL_EXPLICIT_INSTANTIATION (fn))
1252             {
1253               error ("specialization of %qD after instantiation",
1254                      fn);
1255               return error_mark_node;
1256             }
1257           else
1258             {
1259               tree clone;
1260               /* This situation should occur only if the first
1261                  specialization is an implicit instantiation, the
1262                  second is an explicit specialization, and the
1263                  implicit instantiation has not yet been used.  That
1264                  situation can occur if we have implicitly
1265                  instantiated a member function and then specialized
1266                  it later.
1267
1268                  We can also wind up here if a friend declaration that
1269                  looked like an instantiation turns out to be a
1270                  specialization:
1271
1272                    template <class T> void foo(T);
1273                    class S { friend void foo<>(int) };
1274                    template <> void foo(int);
1275
1276                  We transform the existing DECL in place so that any
1277                  pointers to it become pointers to the updated
1278                  declaration.
1279
1280                  If there was a definition for the template, but not
1281                  for the specialization, we want this to look as if
1282                  there were no definition, and vice versa.  */
1283               DECL_INITIAL (fn) = NULL_TREE;
1284               duplicate_decls (spec, fn, is_friend);
1285               /* The call to duplicate_decls will have applied
1286                  [temp.expl.spec]:
1287
1288                    An explicit specialization of a function template
1289                    is inline only if it is explicitly declared to be,
1290                    and independently of whether its function template
1291                    is.
1292
1293                 to the primary function; now copy the inline bits to
1294                 the various clones.  */
1295               FOR_EACH_CLONE (clone, fn)
1296                 {
1297                   DECL_DECLARED_INLINE_P (clone)
1298                     = DECL_DECLARED_INLINE_P (fn);
1299                   DECL_SOURCE_LOCATION (clone)
1300                     = DECL_SOURCE_LOCATION (fn);
1301                 }
1302               check_specialization_namespace (fn);
1303
1304               return fn;
1305             }
1306         }
1307       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1308         {
1309           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1310             /* Dup decl failed, but this is a new definition. Set the
1311                line number so any errors match this new
1312                definition.  */
1313             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1314
1315           return fn;
1316         }
1317     }
1318
1319   /* A specialization must be declared in the same namespace as the
1320      template it is specializing.  */
1321   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1322       && !check_specialization_namespace (tmpl))
1323     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1324
1325   if (!optimize_specialization_lookup_p (tmpl))
1326     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1327       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1328
1329   return spec;
1330 }
1331
1332 /* Unregister the specialization SPEC as a specialization of TMPL.
1333    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1334    if the SPEC was listed as a specialization of TMPL.  */
1335
1336 bool
1337 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1338 {
1339   tree* s;
1340
1341   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1342        *s != NULL_TREE;
1343        s = &TREE_CHAIN (*s))
1344     if (TREE_VALUE (*s) == spec)
1345       {
1346         if (!new_spec)
1347           *s = TREE_CHAIN (*s);
1348         else
1349           TREE_VALUE (*s) = new_spec;
1350         return 1;
1351       }
1352
1353   return 0;
1354 }
1355
1356 /* Compare an entry in the local specializations hash table P1 (which
1357    is really a pointer to a TREE_LIST) with P2 (which is really a
1358    DECL).  */
1359
1360 static int
1361 eq_local_specializations (const void *p1, const void *p2)
1362 {
1363   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1364 }
1365
1366 /* Hash P1, an entry in the local specializations table.  */
1367
1368 static hashval_t
1369 hash_local_specialization (const void* p1)
1370 {
1371   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1372 }
1373
1374 /* Like register_specialization, but for local declarations.  We are
1375    registering SPEC, an instantiation of TMPL.  */
1376
1377 static void
1378 register_local_specialization (tree spec, tree tmpl)
1379 {
1380   void **slot;
1381
1382   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1383                                    htab_hash_pointer (tmpl), INSERT);
1384   *slot = build_tree_list (spec, tmpl);
1385 }
1386
1387 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1388    specialized class.  */
1389
1390 bool
1391 explicit_class_specialization_p (tree type)
1392 {
1393   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1394     return false;
1395   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1396 }
1397
1398 /* Print the list of candidate FNS in an error message.  */
1399
1400 void
1401 print_candidates (tree fns)
1402 {
1403   tree fn;
1404
1405   const char *str = "candidates are:";
1406
1407   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1408     {
1409       tree f;
1410
1411       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1412         error ("%s %+#D", str, OVL_CURRENT (f));
1413       str = "               ";
1414     }
1415 }
1416
1417 /* Returns the template (one of the functions given by TEMPLATE_ID)
1418    which can be specialized to match the indicated DECL with the
1419    explicit template args given in TEMPLATE_ID.  The DECL may be
1420    NULL_TREE if none is available.  In that case, the functions in
1421    TEMPLATE_ID are non-members.
1422
1423    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1424    specialization of a member template.
1425
1426    The TEMPLATE_COUNT is the number of references to qualifying
1427    template classes that appeared in the name of the function. See
1428    check_explicit_specialization for a more accurate description.
1429
1430    TSK indicates what kind of template declaration (if any) is being
1431    declared.  TSK_TEMPLATE indicates that the declaration given by
1432    DECL, though a FUNCTION_DECL, has template parameters, and is
1433    therefore a template function.
1434
1435    The template args (those explicitly specified and those deduced)
1436    are output in a newly created vector *TARGS_OUT.
1437
1438    If it is impossible to determine the result, an error message is
1439    issued.  The error_mark_node is returned to indicate failure.  */
1440
1441 static tree
1442 determine_specialization (tree template_id,
1443                           tree decl,
1444                           tree* targs_out,
1445                           int need_member_template,
1446                           int template_count,
1447                           tmpl_spec_kind tsk)
1448 {
1449   tree fns;
1450   tree targs;
1451   tree explicit_targs;
1452   tree candidates = NULL_TREE;
1453   /* A TREE_LIST of templates of which DECL may be a specialization.
1454      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1455      corresponding TREE_PURPOSE is the set of template arguments that,
1456      when used to instantiate the template, would produce a function
1457      with the signature of DECL.  */
1458   tree templates = NULL_TREE;
1459   int header_count;
1460   struct cp_binding_level *b;
1461
1462   *targs_out = NULL_TREE;
1463
1464   if (template_id == error_mark_node || decl == error_mark_node)
1465     return error_mark_node;
1466
1467   fns = TREE_OPERAND (template_id, 0);
1468   explicit_targs = TREE_OPERAND (template_id, 1);
1469
1470   if (fns == error_mark_node)
1471     return error_mark_node;
1472
1473   /* Check for baselinks.  */
1474   if (BASELINK_P (fns))
1475     fns = BASELINK_FUNCTIONS (fns);
1476
1477   if (!is_overloaded_fn (fns))
1478     {
1479       error ("%qD is not a function template", fns);
1480       return error_mark_node;
1481     }
1482
1483   /* Count the number of template headers specified for this
1484      specialization.  */
1485   header_count = 0;
1486   for (b = current_binding_level;
1487        b->kind == sk_template_parms;
1488        b = b->level_chain)
1489     ++header_count;
1490
1491   for (; fns; fns = OVL_NEXT (fns))
1492     {
1493       tree fn = OVL_CURRENT (fns);
1494
1495       if (TREE_CODE (fn) == TEMPLATE_DECL)
1496         {
1497           tree decl_arg_types;
1498           tree fn_arg_types;
1499
1500           /* In case of explicit specialization, we need to check if
1501              the number of template headers appearing in the specialization
1502              is correct. This is usually done in check_explicit_specialization,
1503              but the check done there cannot be exhaustive when specializing
1504              member functions. Consider the following code:
1505
1506              template <> void A<int>::f(int);
1507              template <> template <> void A<int>::f(int);
1508
1509              Assuming that A<int> is not itself an explicit specialization
1510              already, the first line specializes "f" which is a non-template
1511              member function, whilst the second line specializes "f" which
1512              is a template member function. So both lines are syntactically
1513              correct, and check_explicit_specialization does not reject
1514              them.
1515
1516              Here, we can do better, as we are matching the specialization
1517              against the declarations. We count the number of template
1518              headers, and we check if they match TEMPLATE_COUNT + 1
1519              (TEMPLATE_COUNT is the number of qualifying template classes,
1520              plus there must be another header for the member template
1521              itself).
1522
1523              Notice that if header_count is zero, this is not a
1524              specialization but rather a template instantiation, so there
1525              is no check we can perform here.  */
1526           if (header_count && header_count != template_count + 1)
1527             continue;
1528
1529           /* Check that the number of template arguments at the
1530              innermost level for DECL is the same as for FN.  */
1531           if (current_binding_level->kind == sk_template_parms
1532               && !current_binding_level->explicit_spec_p
1533               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1534                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1535                                       (current_template_parms))))
1536             continue;
1537
1538           /* DECL might be a specialization of FN.  */
1539           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1540           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1541
1542           /* For a non-static member function, we need to make sure
1543              that the const qualification is the same.  Since
1544              get_bindings does not try to merge the "this" parameter,
1545              we must do the comparison explicitly.  */
1546           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1547               && !same_type_p (TREE_VALUE (fn_arg_types),
1548                                TREE_VALUE (decl_arg_types)))
1549             continue;
1550
1551           /* Skip the "this" parameter and, for constructors of
1552              classes with virtual bases, the VTT parameter.  A
1553              full specialization of a constructor will have a VTT
1554              parameter, but a template never will.  */ 
1555           decl_arg_types 
1556             = skip_artificial_parms_for (decl, decl_arg_types);
1557           fn_arg_types 
1558             = skip_artificial_parms_for (fn, fn_arg_types);
1559
1560           /* Check that the number of function parameters matches.
1561              For example,
1562                template <class T> void f(int i = 0);
1563                template <> void f<int>();
1564              The specialization f<int> is invalid but is not caught
1565              by get_bindings below.  */
1566           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1567             continue;
1568
1569           /* Function templates cannot be specializations; there are
1570              no partial specializations of functions.  Therefore, if
1571              the type of DECL does not match FN, there is no
1572              match.  */
1573           if (tsk == tsk_template)
1574             {
1575               if (compparms (fn_arg_types, decl_arg_types))
1576                 candidates = tree_cons (NULL_TREE, fn, candidates);
1577               continue;
1578             }
1579
1580           /* See whether this function might be a specialization of this
1581              template.  */
1582           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1583
1584           if (!targs)
1585             /* We cannot deduce template arguments that when used to
1586                specialize TMPL will produce DECL.  */
1587             continue;
1588
1589           /* Save this template, and the arguments deduced.  */
1590           templates = tree_cons (targs, fn, templates);
1591         }
1592       else if (need_member_template)
1593         /* FN is an ordinary member function, and we need a
1594            specialization of a member template.  */
1595         ;
1596       else if (TREE_CODE (fn) != FUNCTION_DECL)
1597         /* We can get IDENTIFIER_NODEs here in certain erroneous
1598            cases.  */
1599         ;
1600       else if (!DECL_FUNCTION_MEMBER_P (fn))
1601         /* This is just an ordinary non-member function.  Nothing can
1602            be a specialization of that.  */
1603         ;
1604       else if (DECL_ARTIFICIAL (fn))
1605         /* Cannot specialize functions that are created implicitly.  */
1606         ;
1607       else
1608         {
1609           tree decl_arg_types;
1610
1611           /* This is an ordinary member function.  However, since
1612              we're here, we can assume it's enclosing class is a
1613              template class.  For example,
1614
1615                template <typename T> struct S { void f(); };
1616                template <> void S<int>::f() {}
1617
1618              Here, S<int>::f is a non-template, but S<int> is a
1619              template class.  If FN has the same type as DECL, we
1620              might be in business.  */
1621
1622           if (!DECL_TEMPLATE_INFO (fn))
1623             /* Its enclosing class is an explicit specialization
1624                of a template class.  This is not a candidate.  */
1625             continue;
1626
1627           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1628                             TREE_TYPE (TREE_TYPE (fn))))
1629             /* The return types differ.  */
1630             continue;
1631
1632           /* Adjust the type of DECL in case FN is a static member.  */
1633           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1634           if (DECL_STATIC_FUNCTION_P (fn)
1635               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1636             decl_arg_types = TREE_CHAIN (decl_arg_types);
1637
1638           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1639                          decl_arg_types))
1640             /* They match!  */
1641             candidates = tree_cons (NULL_TREE, fn, candidates);
1642         }
1643     }
1644
1645   if (templates && TREE_CHAIN (templates))
1646     {
1647       /* We have:
1648
1649            [temp.expl.spec]
1650
1651            It is possible for a specialization with a given function
1652            signature to be instantiated from more than one function
1653            template.  In such cases, explicit specification of the
1654            template arguments must be used to uniquely identify the
1655            function template specialization being specialized.
1656
1657          Note that here, there's no suggestion that we're supposed to
1658          determine which of the candidate templates is most
1659          specialized.  However, we, also have:
1660
1661            [temp.func.order]
1662
1663            Partial ordering of overloaded function template
1664            declarations is used in the following contexts to select
1665            the function template to which a function template
1666            specialization refers:
1667
1668            -- when an explicit specialization refers to a function
1669               template.
1670
1671          So, we do use the partial ordering rules, at least for now.
1672          This extension can only serve to make invalid programs valid,
1673          so it's safe.  And, there is strong anecdotal evidence that
1674          the committee intended the partial ordering rules to apply;
1675          the EDG front end has that behavior, and John Spicer claims
1676          that the committee simply forgot to delete the wording in
1677          [temp.expl.spec].  */
1678       tree tmpl = most_specialized_instantiation (templates);
1679       if (tmpl != error_mark_node)
1680         {
1681           templates = tmpl;
1682           TREE_CHAIN (templates) = NULL_TREE;
1683         }
1684     }
1685
1686   if (templates == NULL_TREE && candidates == NULL_TREE)
1687     {
1688       error ("template-id %qD for %q+D does not match any template "
1689              "declaration", template_id, decl);
1690       return error_mark_node;
1691     }
1692   else if ((templates && TREE_CHAIN (templates))
1693            || (candidates && TREE_CHAIN (candidates))
1694            || (templates && candidates))
1695     {
1696       error ("ambiguous template specialization %qD for %q+D",
1697              template_id, decl);
1698       chainon (candidates, templates);
1699       print_candidates (candidates);
1700       return error_mark_node;
1701     }
1702
1703   /* We have one, and exactly one, match.  */
1704   if (candidates)
1705     {
1706       tree fn = TREE_VALUE (candidates);
1707       /* DECL is a re-declaration of a template function.  */
1708       if (TREE_CODE (fn) == TEMPLATE_DECL)
1709         return fn;
1710       /* It was a specialization of an ordinary member function in a
1711          template class.  */
1712       *targs_out = copy_node (DECL_TI_ARGS (fn));
1713       return DECL_TI_TEMPLATE (fn);
1714     }
1715
1716   /* It was a specialization of a template.  */
1717   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1718   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1719     {
1720       *targs_out = copy_node (targs);
1721       SET_TMPL_ARGS_LEVEL (*targs_out,
1722                            TMPL_ARGS_DEPTH (*targs_out),
1723                            TREE_PURPOSE (templates));
1724     }
1725   else
1726     *targs_out = TREE_PURPOSE (templates);
1727   return TREE_VALUE (templates);
1728 }
1729
1730 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1731    but with the default argument values filled in from those in the
1732    TMPL_TYPES.  */
1733
1734 static tree
1735 copy_default_args_to_explicit_spec_1 (tree spec_types,
1736                                       tree tmpl_types)
1737 {
1738   tree new_spec_types;
1739
1740   if (!spec_types)
1741     return NULL_TREE;
1742
1743   if (spec_types == void_list_node)
1744     return void_list_node;
1745
1746   /* Substitute into the rest of the list.  */
1747   new_spec_types =
1748     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1749                                           TREE_CHAIN (tmpl_types));
1750
1751   /* Add the default argument for this parameter.  */
1752   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1753                          TREE_VALUE (spec_types),
1754                          new_spec_types);
1755 }
1756
1757 /* DECL is an explicit specialization.  Replicate default arguments
1758    from the template it specializes.  (That way, code like:
1759
1760      template <class T> void f(T = 3);
1761      template <> void f(double);
1762      void g () { f (); }
1763
1764    works, as required.)  An alternative approach would be to look up
1765    the correct default arguments at the call-site, but this approach
1766    is consistent with how implicit instantiations are handled.  */
1767
1768 static void
1769 copy_default_args_to_explicit_spec (tree decl)
1770 {
1771   tree tmpl;
1772   tree spec_types;
1773   tree tmpl_types;
1774   tree new_spec_types;
1775   tree old_type;
1776   tree new_type;
1777   tree t;
1778   tree object_type = NULL_TREE;
1779   tree in_charge = NULL_TREE;
1780   tree vtt = NULL_TREE;
1781
1782   /* See if there's anything we need to do.  */
1783   tmpl = DECL_TI_TEMPLATE (decl);
1784   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1785   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1786     if (TREE_PURPOSE (t))
1787       break;
1788   if (!t)
1789     return;
1790
1791   old_type = TREE_TYPE (decl);
1792   spec_types = TYPE_ARG_TYPES (old_type);
1793
1794   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1795     {
1796       /* Remove the this pointer, but remember the object's type for
1797          CV quals.  */
1798       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1799       spec_types = TREE_CHAIN (spec_types);
1800       tmpl_types = TREE_CHAIN (tmpl_types);
1801
1802       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1803         {
1804           /* DECL may contain more parameters than TMPL due to the extra
1805              in-charge parameter in constructors and destructors.  */
1806           in_charge = spec_types;
1807           spec_types = TREE_CHAIN (spec_types);
1808         }
1809       if (DECL_HAS_VTT_PARM_P (decl))
1810         {
1811           vtt = spec_types;
1812           spec_types = TREE_CHAIN (spec_types);
1813         }
1814     }
1815
1816   /* Compute the merged default arguments.  */
1817   new_spec_types =
1818     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1819
1820   /* Compute the new FUNCTION_TYPE.  */
1821   if (object_type)
1822     {
1823       if (vtt)
1824         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1825                                          TREE_VALUE (vtt),
1826                                          new_spec_types);
1827
1828       if (in_charge)
1829         /* Put the in-charge parameter back.  */
1830         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1831                                          TREE_VALUE (in_charge),
1832                                          new_spec_types);
1833
1834       new_type = build_method_type_directly (object_type,
1835                                              TREE_TYPE (old_type),
1836                                              new_spec_types);
1837     }
1838   else
1839     new_type = build_function_type (TREE_TYPE (old_type),
1840                                     new_spec_types);
1841   new_type = cp_build_type_attribute_variant (new_type,
1842                                               TYPE_ATTRIBUTES (old_type));
1843   new_type = build_exception_variant (new_type,
1844                                       TYPE_RAISES_EXCEPTIONS (old_type));
1845   TREE_TYPE (decl) = new_type;
1846 }
1847
1848 /* Check to see if the function just declared, as indicated in
1849    DECLARATOR, and in DECL, is a specialization of a function
1850    template.  We may also discover that the declaration is an explicit
1851    instantiation at this point.
1852
1853    Returns DECL, or an equivalent declaration that should be used
1854    instead if all goes well.  Issues an error message if something is
1855    amiss.  Returns error_mark_node if the error is not easily
1856    recoverable.
1857
1858    FLAGS is a bitmask consisting of the following flags:
1859
1860    2: The function has a definition.
1861    4: The function is a friend.
1862
1863    The TEMPLATE_COUNT is the number of references to qualifying
1864    template classes that appeared in the name of the function.  For
1865    example, in
1866
1867      template <class T> struct S { void f(); };
1868      void S<int>::f();
1869
1870    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1871    classes are not counted in the TEMPLATE_COUNT, so that in
1872
1873      template <class T> struct S {};
1874      template <> struct S<int> { void f(); }
1875      template <> void S<int>::f();
1876
1877    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1878    invalid; there should be no template <>.)
1879
1880    If the function is a specialization, it is marked as such via
1881    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1882    is set up correctly, and it is added to the list of specializations
1883    for that template.  */
1884
1885 tree
1886 check_explicit_specialization (tree declarator,
1887                                tree decl,
1888                                int template_count,
1889                                int flags)
1890 {
1891   int have_def = flags & 2;
1892   int is_friend = flags & 4;
1893   int specialization = 0;
1894   int explicit_instantiation = 0;
1895   int member_specialization = 0;
1896   tree ctype = DECL_CLASS_CONTEXT (decl);
1897   tree dname = DECL_NAME (decl);
1898   tmpl_spec_kind tsk;
1899
1900   if (is_friend)
1901     {
1902       if (!processing_specialization)
1903         tsk = tsk_none;
1904       else
1905         tsk = tsk_excessive_parms;
1906     }
1907   else
1908     tsk = current_tmpl_spec_kind (template_count);
1909
1910   switch (tsk)
1911     {
1912     case tsk_none:
1913       if (processing_specialization)
1914         {
1915           specialization = 1;
1916           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1917         }
1918       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1919         {
1920           if (is_friend)
1921             /* This could be something like:
1922
1923                template <class T> void f(T);
1924                class S { friend void f<>(int); }  */
1925             specialization = 1;
1926           else
1927             {
1928               /* This case handles bogus declarations like template <>
1929                  template <class T> void f<int>(); */
1930
1931               error ("template-id %qD in declaration of primary template",
1932                      declarator);
1933               return decl;
1934             }
1935         }
1936       break;
1937
1938     case tsk_invalid_member_spec:
1939       /* The error has already been reported in
1940          check_specialization_scope.  */
1941       return error_mark_node;
1942
1943     case tsk_invalid_expl_inst:
1944       error ("template parameter list used in explicit instantiation");
1945
1946       /* Fall through.  */
1947
1948     case tsk_expl_inst:
1949       if (have_def)
1950         error ("definition provided for explicit instantiation");
1951
1952       explicit_instantiation = 1;
1953       break;
1954
1955     case tsk_excessive_parms:
1956     case tsk_insufficient_parms:
1957       if (tsk == tsk_excessive_parms)
1958         error ("too many template parameter lists in declaration of %qD",
1959                decl);
1960       else if (template_header_count)
1961         error("too few template parameter lists in declaration of %qD", decl);
1962       else
1963         error("explicit specialization of %qD must be introduced by "
1964               "%<template <>%>", decl);
1965
1966       /* Fall through.  */
1967     case tsk_expl_spec:
1968       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1969       if (ctype)
1970         member_specialization = 1;
1971       else
1972         specialization = 1;
1973       break;
1974
1975     case tsk_template:
1976       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1977         {
1978           /* This case handles bogus declarations like template <>
1979              template <class T> void f<int>(); */
1980
1981           if (uses_template_parms (declarator))
1982             error ("function template partial specialization %qD "
1983                    "is not allowed", declarator);
1984           else
1985             error ("template-id %qD in declaration of primary template",
1986                    declarator);
1987           return decl;
1988         }
1989
1990       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1991         /* This is a specialization of a member template, without
1992            specialization the containing class.  Something like:
1993
1994              template <class T> struct S {
1995                template <class U> void f (U);
1996              };
1997              template <> template <class U> void S<int>::f(U) {}
1998
1999            That's a specialization -- but of the entire template.  */
2000         specialization = 1;
2001       break;
2002
2003     default:
2004       gcc_unreachable ();
2005     }
2006
2007   if (specialization || member_specialization)
2008     {
2009       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2010       for (; t; t = TREE_CHAIN (t))
2011         if (TREE_PURPOSE (t))
2012           {
2013             permerror (input_location, 
2014                        "default argument specified in explicit specialization");
2015             break;
2016           }
2017     }
2018
2019   if (specialization || member_specialization || explicit_instantiation)
2020     {
2021       tree tmpl = NULL_TREE;
2022       tree targs = NULL_TREE;
2023
2024       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2025       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2026         {
2027           tree fns;
2028
2029           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2030           if (ctype)
2031             fns = dname;
2032           else
2033             {
2034               /* If there is no class context, the explicit instantiation
2035                  must be at namespace scope.  */
2036               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2037
2038               /* Find the namespace binding, using the declaration
2039                  context.  */
2040               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2041                                            false, true);
2042               if (fns == error_mark_node || !is_overloaded_fn (fns))
2043                 {
2044                   error ("%qD is not a template function", dname);
2045                   fns = error_mark_node;
2046                 }
2047               else
2048                 {
2049                   tree fn = OVL_CURRENT (fns);
2050                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2051                                                 CP_DECL_CONTEXT (fn)))
2052                     error ("%qD is not declared in %qD",
2053                            decl, current_namespace);
2054                 }
2055             }
2056
2057           declarator = lookup_template_function (fns, NULL_TREE);
2058         }
2059
2060       if (declarator == error_mark_node)
2061         return error_mark_node;
2062
2063       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2064         {
2065           if (!explicit_instantiation)
2066             /* A specialization in class scope.  This is invalid,
2067                but the error will already have been flagged by
2068                check_specialization_scope.  */
2069             return error_mark_node;
2070           else
2071             {
2072               /* It's not valid to write an explicit instantiation in
2073                  class scope, e.g.:
2074
2075                    class C { template void f(); }
2076
2077                    This case is caught by the parser.  However, on
2078                    something like:
2079
2080                    template class C { void f(); };
2081
2082                    (which is invalid) we can get here.  The error will be
2083                    issued later.  */
2084               ;
2085             }
2086
2087           return decl;
2088         }
2089       else if (ctype != NULL_TREE
2090                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2091                    IDENTIFIER_NODE))
2092         {
2093           /* Find the list of functions in ctype that have the same
2094              name as the declared function.  */
2095           tree name = TREE_OPERAND (declarator, 0);
2096           tree fns = NULL_TREE;
2097           int idx;
2098
2099           if (constructor_name_p (name, ctype))
2100             {
2101               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2102
2103               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2104                   : !CLASSTYPE_DESTRUCTORS (ctype))
2105                 {
2106                   /* From [temp.expl.spec]:
2107
2108                      If such an explicit specialization for the member
2109                      of a class template names an implicitly-declared
2110                      special member function (clause _special_), the
2111                      program is ill-formed.
2112
2113                      Similar language is found in [temp.explicit].  */
2114                   error ("specialization of implicitly-declared special member function");
2115                   return error_mark_node;
2116                 }
2117
2118               name = is_constructor ? ctor_identifier : dtor_identifier;
2119             }
2120
2121           if (!DECL_CONV_FN_P (decl))
2122             {
2123               idx = lookup_fnfields_1 (ctype, name);
2124               if (idx >= 0)
2125                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2126             }
2127           else
2128             {
2129               VEC(tree,gc) *methods;
2130               tree ovl;
2131
2132               /* For a type-conversion operator, we cannot do a
2133                  name-based lookup.  We might be looking for `operator
2134                  int' which will be a specialization of `operator T'.
2135                  So, we find *all* the conversion operators, and then
2136                  select from them.  */
2137               fns = NULL_TREE;
2138
2139               methods = CLASSTYPE_METHOD_VEC (ctype);
2140               if (methods)
2141                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2142                      VEC_iterate (tree, methods, idx, ovl);
2143                      ++idx)
2144                   {
2145                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2146                       /* There are no more conversion functions.  */
2147                       break;
2148
2149                     /* Glue all these conversion functions together
2150                        with those we already have.  */
2151                     for (; ovl; ovl = OVL_NEXT (ovl))
2152                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2153                   }
2154             }
2155
2156           if (fns == NULL_TREE)
2157             {
2158               error ("no member function %qD declared in %qT", name, ctype);
2159               return error_mark_node;
2160             }
2161           else
2162             TREE_OPERAND (declarator, 0) = fns;
2163         }
2164
2165       /* Figure out what exactly is being specialized at this point.
2166          Note that for an explicit instantiation, even one for a
2167          member function, we cannot tell apriori whether the
2168          instantiation is for a member template, or just a member
2169          function of a template class.  Even if a member template is
2170          being instantiated, the member template arguments may be
2171          elided if they can be deduced from the rest of the
2172          declaration.  */
2173       tmpl = determine_specialization (declarator, decl,
2174                                        &targs,
2175                                        member_specialization,
2176                                        template_count,
2177                                        tsk);
2178
2179       if (!tmpl || tmpl == error_mark_node)
2180         /* We couldn't figure out what this declaration was
2181            specializing.  */
2182         return error_mark_node;
2183       else
2184         {
2185           tree gen_tmpl = most_general_template (tmpl);
2186
2187           if (explicit_instantiation)
2188             {
2189               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2190                  is done by do_decl_instantiation later.  */
2191
2192               int arg_depth = TMPL_ARGS_DEPTH (targs);
2193               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2194
2195               if (arg_depth > parm_depth)
2196                 {
2197                   /* If TMPL is not the most general template (for
2198                      example, if TMPL is a friend template that is
2199                      injected into namespace scope), then there will
2200                      be too many levels of TARGS.  Remove some of them
2201                      here.  */
2202                   int i;
2203                   tree new_targs;
2204
2205                   new_targs = make_tree_vec (parm_depth);
2206                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2207                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2208                       = TREE_VEC_ELT (targs, i);
2209                   targs = new_targs;
2210                 }
2211
2212               return instantiate_template (tmpl, targs, tf_error);
2213             }
2214
2215           /* If we thought that the DECL was a member function, but it
2216              turns out to be specializing a static member function,
2217              make DECL a static member function as well.  */
2218           if (DECL_STATIC_FUNCTION_P (tmpl)
2219               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2220             revert_static_member_fn (decl);
2221
2222           /* If this is a specialization of a member template of a
2223              template class, we want to return the TEMPLATE_DECL, not
2224              the specialization of it.  */
2225           if (tsk == tsk_template)
2226             {
2227               tree result = DECL_TEMPLATE_RESULT (tmpl);
2228               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2229               DECL_INITIAL (result) = NULL_TREE;
2230               if (have_def)
2231                 {
2232                   tree parm;
2233                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2234                   DECL_SOURCE_LOCATION (result)
2235                     = DECL_SOURCE_LOCATION (decl);
2236                   /* We want to use the argument list specified in the
2237                      definition, not in the original declaration.  */
2238                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2239                   for (parm = DECL_ARGUMENTS (result); parm;
2240                        parm = TREE_CHAIN (parm))
2241                     DECL_CONTEXT (parm) = result;
2242                 }
2243               return tmpl;
2244             }
2245
2246           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2247           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2248
2249           /* Inherit default function arguments from the template
2250              DECL is specializing.  */
2251           copy_default_args_to_explicit_spec (decl);
2252
2253           /* This specialization has the same protection as the
2254              template it specializes.  */
2255           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2256           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2257
2258           /* 7.1.1-1 [dcl.stc]
2259
2260              A storage-class-specifier shall not be specified in an
2261              explicit specialization...
2262
2263              The parser rejects these, so unless action is taken here,
2264              explicit function specializations will always appear with
2265              global linkage.
2266
2267              The action recommended by the C++ CWG in response to C++
2268              defect report 605 is to make the storage class and linkage
2269              of the explicit specialization match the templated function:
2270
2271              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2272            */
2273           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2274             {
2275               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2276               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2277
2278               /* This specialization has the same linkage and visibility as
2279                  the function template it specializes.  */
2280               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2281               if (! TREE_PUBLIC (decl))
2282                 {
2283                   DECL_INTERFACE_KNOWN (decl) = 1;
2284                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2285                 }
2286               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2287               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2288                 {
2289                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2290                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2291                 }
2292             }
2293
2294           /* If DECL is a friend declaration, declared using an
2295              unqualified name, the namespace associated with DECL may
2296              have been set incorrectly.  For example, in:
2297
2298                template <typename T> void f(T);
2299                namespace N {
2300                  struct S { friend void f<int>(int); }
2301                }
2302
2303              we will have set the DECL_CONTEXT for the friend
2304              declaration to N, rather than to the global namespace.  */
2305           if (DECL_NAMESPACE_SCOPE_P (decl))
2306             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2307
2308           if (is_friend && !have_def)
2309             /* This is not really a declaration of a specialization.
2310                It's just the name of an instantiation.  But, it's not
2311                a request for an instantiation, either.  */
2312             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2313           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2314             /* This is indeed a specialization.  In case of constructors
2315                and destructors, we need in-charge and not-in-charge
2316                versions in V3 ABI.  */
2317             clone_function_decl (decl, /*update_method_vec_p=*/0);
2318
2319           /* Register this specialization so that we can find it
2320              again.  */
2321           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2322         }
2323     }
2324
2325   return decl;
2326 }
2327
2328 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2329    parameters.  These are represented in the same format used for
2330    DECL_TEMPLATE_PARMS.  */
2331
2332 int
2333 comp_template_parms (const_tree parms1, const_tree parms2)
2334 {
2335   const_tree p1;
2336   const_tree p2;
2337
2338   if (parms1 == parms2)
2339     return 1;
2340
2341   for (p1 = parms1, p2 = parms2;
2342        p1 != NULL_TREE && p2 != NULL_TREE;
2343        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2344     {
2345       tree t1 = TREE_VALUE (p1);
2346       tree t2 = TREE_VALUE (p2);
2347       int i;
2348
2349       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2350       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2351
2352       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2353         return 0;
2354
2355       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2356         {
2357           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2358           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2359
2360           /* If either of the template parameters are invalid, assume
2361              they match for the sake of error recovery. */
2362           if (parm1 == error_mark_node || parm2 == error_mark_node)
2363             return 1;
2364
2365           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2366             return 0;
2367
2368           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2369               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2370                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2371             continue;
2372           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2373             return 0;
2374         }
2375     }
2376
2377   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2378     /* One set of parameters has more parameters lists than the
2379        other.  */
2380     return 0;
2381
2382   return 1;
2383 }
2384
2385 /* Determine whether PARM is a parameter pack.  */
2386 bool 
2387 template_parameter_pack_p (const_tree parm)
2388 {
2389   /* Determine if we have a non-type template parameter pack.  */
2390   if (TREE_CODE (parm) == PARM_DECL)
2391     return (DECL_TEMPLATE_PARM_P (parm) 
2392             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2393
2394   /* If this is a list of template parameters, we could get a
2395      TYPE_DECL or a TEMPLATE_DECL.  */ 
2396   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2397     parm = TREE_TYPE (parm);
2398
2399   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2400            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2401           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2402 }
2403
2404 /* Determine whether ARGS describes a variadic template args list,
2405    i.e., one that is terminated by a template argument pack.  */
2406 static bool 
2407 template_args_variadic_p (tree args)
2408 {
2409   int nargs;
2410   tree last_parm;
2411
2412   if (args == NULL_TREE)
2413     return false;
2414
2415   args = INNERMOST_TEMPLATE_ARGS (args);
2416   nargs = TREE_VEC_LENGTH (args);
2417
2418   if (nargs == 0)
2419     return false;
2420
2421   last_parm = TREE_VEC_ELT (args, nargs - 1);
2422
2423   return ARGUMENT_PACK_P (last_parm);
2424 }
2425
2426 /* Generate a new name for the parameter pack name NAME (an
2427    IDENTIFIER_NODE) that incorporates its */
2428 static tree
2429 make_ith_pack_parameter_name (tree name, int i)
2430 {
2431   /* Munge the name to include the parameter index.  */
2432   char numbuf[128];
2433   char* newname;
2434   
2435   sprintf(numbuf, "%i", i);
2436   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2437   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2438   return get_identifier (newname);
2439 }
2440
2441 /* Structure used to track the progress of find_parameter_packs_r.  */
2442 struct find_parameter_pack_data 
2443 {
2444   /* TREE_LIST that will contain all of the parameter packs found by
2445      the traversal.  */
2446   tree* parameter_packs;
2447
2448   /* Set of AST nodes that have been visited by the traversal.  */
2449   struct pointer_set_t *visited;
2450 };
2451
2452 /* Identifies all of the argument packs that occur in a template
2453    argument and appends them to the TREE_LIST inside DATA, which is a
2454    find_parameter_pack_data structure. This is a subroutine of
2455    make_pack_expansion and uses_parameter_packs.  */
2456 static tree
2457 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2458 {
2459   tree t = *tp;
2460   struct find_parameter_pack_data* ppd = 
2461     (struct find_parameter_pack_data*)data;
2462   bool parameter_pack_p = false;
2463
2464   /* Identify whether this is a parameter pack or not.  */
2465   switch (TREE_CODE (t))
2466     {
2467     case TEMPLATE_PARM_INDEX:
2468       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2469         parameter_pack_p = true;
2470       break;
2471
2472     case TEMPLATE_TYPE_PARM:
2473     case TEMPLATE_TEMPLATE_PARM:
2474       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2475         parameter_pack_p = true;
2476       break;
2477
2478     case PARM_DECL:
2479       if (FUNCTION_PARAMETER_PACK_P (t))
2480         {
2481           /* We don't want to walk into the type of a PARM_DECL,
2482              because we don't want to see the type parameter pack.  */
2483           *walk_subtrees = 0;
2484           parameter_pack_p = true;
2485         }
2486       break;
2487
2488     default:
2489       /* Not a parameter pack.  */
2490       break;
2491     }
2492
2493   if (parameter_pack_p)
2494     {
2495       /* Add this parameter pack to the list.  */
2496       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2497     }
2498
2499   if (TYPE_P (t))
2500     cp_walk_tree (&TYPE_CONTEXT (t), 
2501                   &find_parameter_packs_r, ppd, ppd->visited);
2502
2503   /* This switch statement will return immediately if we don't find a
2504      parameter pack.  */
2505   switch (TREE_CODE (t)) 
2506     {
2507     case TEMPLATE_PARM_INDEX:
2508       return NULL_TREE;
2509
2510     case BOUND_TEMPLATE_TEMPLATE_PARM:
2511       /* Check the template itself.  */
2512       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2513                     &find_parameter_packs_r, ppd, ppd->visited);
2514       /* Check the template arguments.  */
2515       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2516                     ppd->visited);
2517       *walk_subtrees = 0;
2518       return NULL_TREE;
2519
2520     case TEMPLATE_TYPE_PARM:
2521     case TEMPLATE_TEMPLATE_PARM:
2522       return NULL_TREE;
2523
2524     case PARM_DECL:
2525       return NULL_TREE;
2526
2527     case RECORD_TYPE:
2528       if (TYPE_PTRMEMFUNC_P (t))
2529         return NULL_TREE;
2530       /* Fall through.  */
2531
2532     case UNION_TYPE:
2533     case ENUMERAL_TYPE:
2534       if (TYPE_TEMPLATE_INFO (t))
2535         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2536                       &find_parameter_packs_r, ppd, ppd->visited);
2537
2538       *walk_subtrees = 0;
2539       return NULL_TREE;
2540
2541     case TEMPLATE_DECL:
2542       cp_walk_tree (&TREE_TYPE (t),
2543                     &find_parameter_packs_r, ppd, ppd->visited);
2544       return NULL_TREE;
2545  
2546     case TYPENAME_TYPE:
2547       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2548                    ppd, ppd->visited);
2549       *walk_subtrees = 0;
2550       return NULL_TREE;
2551       
2552     case TYPE_PACK_EXPANSION:
2553     case EXPR_PACK_EXPANSION:
2554       *walk_subtrees = 0;
2555       return NULL_TREE;
2556
2557     case INTEGER_TYPE:
2558       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2559                     ppd, ppd->visited);
2560       *walk_subtrees = 0;
2561       return NULL_TREE;
2562
2563     case IDENTIFIER_NODE:
2564       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2565                     ppd->visited);
2566       *walk_subtrees = 0;
2567       return NULL_TREE;
2568
2569     default:
2570       return NULL_TREE;
2571     }
2572
2573   return NULL_TREE;
2574 }
2575
2576 /* Determines if the expression or type T uses any parameter packs.  */
2577 bool
2578 uses_parameter_packs (tree t)
2579 {
2580   tree parameter_packs = NULL_TREE;
2581   struct find_parameter_pack_data ppd;
2582   ppd.parameter_packs = &parameter_packs;
2583   ppd.visited = pointer_set_create ();
2584   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2585   pointer_set_destroy (ppd.visited);
2586   return parameter_packs != NULL_TREE;
2587 }
2588
2589 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2590    representation a base-class initializer into a parameter pack
2591    expansion. If all goes well, the resulting node will be an
2592    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2593    respectively.  */
2594 tree 
2595 make_pack_expansion (tree arg)
2596 {
2597   tree result;
2598   tree parameter_packs = NULL_TREE;
2599   bool for_types = false;
2600   struct find_parameter_pack_data ppd;
2601
2602   if (!arg || arg == error_mark_node)
2603     return arg;
2604
2605   if (TREE_CODE (arg) == TREE_LIST)
2606     {
2607       /* The only time we will see a TREE_LIST here is for a base
2608          class initializer.  In this case, the TREE_PURPOSE will be a
2609          _TYPE node (representing the base class expansion we're
2610          initializing) and the TREE_VALUE will be a TREE_LIST
2611          containing the initialization arguments. 
2612
2613          The resulting expansion looks somewhat different from most
2614          expansions. Rather than returning just one _EXPANSION, we
2615          return a TREE_LIST whose TREE_PURPOSE is a
2616          TYPE_PACK_EXPANSION containing the bases that will be
2617          initialized.  The TREE_VALUE will be identical to the
2618          original TREE_VALUE, which is a list of arguments that will
2619          be passed to each base.  We do not introduce any new pack
2620          expansion nodes into the TREE_VALUE (although it is possible
2621          that some already exist), because the TREE_PURPOSE and
2622          TREE_VALUE all need to be expanded together with the same
2623          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2624          resulting TREE_PURPOSE will mention the parameter packs in
2625          both the bases and the arguments to the bases.  */
2626       tree purpose;
2627       tree value;
2628       tree parameter_packs = NULL_TREE;
2629
2630       /* Determine which parameter packs will be used by the base
2631          class expansion.  */
2632       ppd.visited = pointer_set_create ();
2633       ppd.parameter_packs = &parameter_packs;
2634       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2635                     &ppd, ppd.visited);
2636
2637       if (parameter_packs == NULL_TREE)
2638         {
2639           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2640           pointer_set_destroy (ppd.visited);
2641           return error_mark_node;
2642         }
2643
2644       if (TREE_VALUE (arg) != void_type_node)
2645         {
2646           /* Collect the sets of parameter packs used in each of the
2647              initialization arguments.  */
2648           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2649             {
2650               /* Determine which parameter packs will be expanded in this
2651                  argument.  */
2652               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2653                             &ppd, ppd.visited);
2654             }
2655         }
2656
2657       pointer_set_destroy (ppd.visited);
2658
2659       /* Create the pack expansion type for the base type.  */
2660       purpose = make_node (TYPE_PACK_EXPANSION);
2661       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2662       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2663
2664       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2665          they will rarely be compared to anything.  */
2666       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2667
2668       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2669     }
2670
2671   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2672     for_types = true;
2673
2674   /* Build the PACK_EXPANSION_* node.  */
2675   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2676   SET_PACK_EXPANSION_PATTERN (result, arg);
2677   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2678     {
2679       /* Propagate type and const-expression information.  */
2680       TREE_TYPE (result) = TREE_TYPE (arg);
2681       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2682     }
2683   else
2684     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2685        they will rarely be compared to anything.  */
2686     SET_TYPE_STRUCTURAL_EQUALITY (result);
2687
2688   /* Determine which parameter packs will be expanded.  */
2689   ppd.parameter_packs = &parameter_packs;
2690   ppd.visited = pointer_set_create ();
2691   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2692   pointer_set_destroy (ppd.visited);
2693
2694   /* Make sure we found some parameter packs.  */
2695   if (parameter_packs == NULL_TREE)
2696     {
2697       if (TYPE_P (arg))
2698         error ("expansion pattern %<%T%> contains no argument packs", arg);
2699       else
2700         error ("expansion pattern %<%E%> contains no argument packs", arg);
2701       return error_mark_node;
2702     }
2703   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2704
2705   return result;
2706 }
2707
2708 /* Checks T for any "bare" parameter packs, which have not yet been
2709    expanded, and issues an error if any are found. This operation can
2710    only be done on full expressions or types (e.g., an expression
2711    statement, "if" condition, etc.), because we could have expressions like:
2712
2713      foo(f(g(h(args)))...)
2714
2715    where "args" is a parameter pack. check_for_bare_parameter_packs
2716    should not be called for the subexpressions args, h(args),
2717    g(h(args)), or f(g(h(args))), because we would produce erroneous
2718    error messages. 
2719
2720    Returns TRUE and emits an error if there were bare parameter packs,
2721    returns FALSE otherwise.  */
2722 bool 
2723 check_for_bare_parameter_packs (tree t)
2724 {
2725   tree parameter_packs = NULL_TREE;
2726   struct find_parameter_pack_data ppd;
2727
2728   if (!processing_template_decl || !t || t == error_mark_node)
2729     return false;
2730
2731   if (TREE_CODE (t) == TYPE_DECL)
2732     t = TREE_TYPE (t);
2733
2734   ppd.parameter_packs = &parameter_packs;
2735   ppd.visited = pointer_set_create ();
2736   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2737   pointer_set_destroy (ppd.visited);
2738
2739   if (parameter_packs) 
2740     {
2741       error ("parameter packs not expanded with %<...%>:");
2742       while (parameter_packs)
2743         {
2744           tree pack = TREE_VALUE (parameter_packs);
2745           tree name = NULL_TREE;
2746
2747           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2748               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2749             name = TYPE_NAME (pack);
2750           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2751             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2752           else
2753             name = DECL_NAME (pack);
2754
2755           if (name)
2756             inform (input_location, "        %qD", name);
2757           else
2758             inform (input_location, "        <anonymous>");
2759
2760           parameter_packs = TREE_CHAIN (parameter_packs);
2761         }
2762
2763       return true;
2764     }
2765
2766   return false;
2767 }
2768
2769 /* Expand any parameter packs that occur in the template arguments in
2770    ARGS.  */
2771 tree
2772 expand_template_argument_pack (tree args)
2773 {
2774   tree result_args = NULL_TREE;
2775   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2776   int num_result_args = -1;
2777
2778   /* First, determine if we need to expand anything, and the number of
2779      slots we'll need.  */
2780   for (in_arg = 0; in_arg < nargs; ++in_arg)
2781     {
2782       tree arg = TREE_VEC_ELT (args, in_arg);
2783       if (ARGUMENT_PACK_P (arg))
2784         {
2785           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2786           if (num_result_args < 0)
2787             num_result_args = in_arg + num_packed;
2788           else
2789             num_result_args += num_packed;
2790         }
2791       else
2792         {
2793           if (num_result_args >= 0)
2794             num_result_args++;
2795         }
2796     }
2797
2798   /* If no expansion is necessary, we're done.  */
2799   if (num_result_args < 0)
2800     return args;
2801
2802   /* Expand arguments.  */
2803   result_args = make_tree_vec (num_result_args);
2804   for (in_arg = 0; in_arg < nargs; ++in_arg)
2805     {
2806       tree arg = TREE_VEC_ELT (args, in_arg);
2807       if (ARGUMENT_PACK_P (arg))
2808         {
2809           tree packed = ARGUMENT_PACK_ARGS (arg);
2810           int i, num_packed = TREE_VEC_LENGTH (packed);
2811           for (i = 0; i < num_packed; ++i, ++out_arg)
2812             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2813         }
2814       else
2815         {
2816           TREE_VEC_ELT (result_args, out_arg) = arg;
2817           ++out_arg;
2818         }
2819     }
2820
2821   return result_args;
2822 }
2823
2824 /* Checks if DECL shadows a template parameter.
2825
2826    [temp.local]: A template-parameter shall not be redeclared within its
2827    scope (including nested scopes).
2828
2829    Emits an error and returns TRUE if the DECL shadows a parameter,
2830    returns FALSE otherwise.  */
2831
2832 bool
2833 check_template_shadow (tree decl)
2834 {
2835   tree olddecl;
2836
2837   /* If we're not in a template, we can't possibly shadow a template
2838      parameter.  */
2839   if (!current_template_parms)
2840     return true;
2841
2842   /* Figure out what we're shadowing.  */
2843   if (TREE_CODE (decl) == OVERLOAD)
2844     decl = OVL_CURRENT (decl);
2845   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2846
2847   /* If there's no previous binding for this name, we're not shadowing
2848      anything, let alone a template parameter.  */
2849   if (!olddecl)
2850     return true;
2851
2852   /* If we're not shadowing a template parameter, we're done.  Note
2853      that OLDDECL might be an OVERLOAD (or perhaps even an
2854      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2855      node.  */
2856   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2857     return true;
2858
2859   /* We check for decl != olddecl to avoid bogus errors for using a
2860      name inside a class.  We check TPFI to avoid duplicate errors for
2861      inline member templates.  */
2862   if (decl == olddecl
2863       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2864     return true;
2865
2866   error ("declaration of %q+#D", decl);
2867   error (" shadows template parm %q+#D", olddecl);
2868   return false;
2869 }
2870
2871 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2872    ORIG_LEVEL, DECL, and TYPE.  */
2873
2874 static tree
2875 build_template_parm_index (int index,
2876                            int level,
2877                            int orig_level,
2878                            tree decl,
2879                            tree type)
2880 {
2881   tree t = make_node (TEMPLATE_PARM_INDEX);
2882   TEMPLATE_PARM_IDX (t) = index;
2883   TEMPLATE_PARM_LEVEL (t) = level;
2884   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2885   TEMPLATE_PARM_DECL (t) = decl;
2886   TREE_TYPE (t) = type;
2887   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2888   TREE_READONLY (t) = TREE_READONLY (decl);
2889
2890   return t;
2891 }
2892
2893 /* Find the canonical type parameter for the given template type
2894    parameter.  Returns the canonical type parameter, which may be TYPE
2895    if no such parameter existed.  */
2896 static tree
2897 canonical_type_parameter (tree type)
2898 {
2899   tree list;
2900   int idx = TEMPLATE_TYPE_IDX (type);
2901   if (!canonical_template_parms)
2902     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2903
2904   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2905     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2906
2907   list = VEC_index (tree, canonical_template_parms, idx);
2908   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2909     list = TREE_CHAIN (list);
2910
2911   if (list)
2912     return TREE_VALUE (list);
2913   else
2914     {
2915       VEC_replace(tree, canonical_template_parms, idx,
2916                   tree_cons (NULL_TREE, type, 
2917                              VEC_index (tree, canonical_template_parms, idx)));
2918       return type;
2919     }
2920 }
2921
2922 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2923    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2924    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2925    new one is created.  */
2926
2927 static tree
2928 reduce_template_parm_level (tree index, tree type, int levels, tree args,
2929                             tsubst_flags_t complain)
2930 {
2931   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2932       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2933           != TEMPLATE_PARM_LEVEL (index) - levels))
2934     {
2935       tree orig_decl = TEMPLATE_PARM_DECL (index);
2936       tree decl, t;
2937
2938       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2939       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2940       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2941       DECL_ARTIFICIAL (decl) = 1;
2942       SET_DECL_TEMPLATE_PARM_P (decl);
2943
2944       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2945                                      TEMPLATE_PARM_LEVEL (index) - levels,
2946                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2947                                      decl, type);
2948       TEMPLATE_PARM_DESCENDANTS (index) = t;
2949       TEMPLATE_PARM_PARAMETER_PACK (t) 
2950         = TEMPLATE_PARM_PARAMETER_PACK (index);
2951
2952         /* Template template parameters need this.  */
2953       if (TREE_CODE (decl) == TEMPLATE_DECL)
2954         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
2955           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
2956            args, complain);
2957     }
2958
2959   return TEMPLATE_PARM_DESCENDANTS (index);
2960 }
2961
2962 /* Process information from new template parameter PARM and append it to the
2963    LIST being built.  This new parameter is a non-type parameter iff
2964    IS_NON_TYPE is true. This new parameter is a parameter
2965    pack iff IS_PARAMETER_PACK is true.  */
2966
2967 tree
2968 process_template_parm (tree list, tree parm, bool is_non_type, 
2969                        bool is_parameter_pack)
2970 {
2971   tree decl = 0;
2972   tree defval;
2973   tree err_parm_list;
2974   int idx = 0;
2975
2976   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2977   defval = TREE_PURPOSE (parm);
2978
2979   if (list)
2980     {
2981       tree p = tree_last (list);
2982
2983       if (p && TREE_VALUE (p) != error_mark_node)
2984         {
2985           p = TREE_VALUE (p);
2986           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2987             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2988           else
2989             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2990         }
2991
2992       ++idx;
2993     }
2994   else
2995     idx = 0;
2996
2997   if (is_non_type)
2998     {
2999       parm = TREE_VALUE (parm);
3000
3001       SET_DECL_TEMPLATE_PARM_P (parm);
3002
3003       if (TREE_TYPE (parm) == error_mark_node)
3004         {
3005           err_parm_list = build_tree_list (defval, parm);
3006           TREE_VALUE (err_parm_list) = error_mark_node;
3007            return chainon (list, err_parm_list);
3008         }
3009       else
3010       {
3011         /* [temp.param]
3012
3013            The top-level cv-qualifiers on the template-parameter are
3014            ignored when determining its type.  */
3015         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3016         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3017           {
3018             err_parm_list = build_tree_list (defval, parm);
3019             TREE_VALUE (err_parm_list) = error_mark_node;
3020              return chainon (list, err_parm_list);
3021           }
3022
3023         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3024           {
3025             /* This template parameter is not a parameter pack, but it
3026                should be. Complain about "bare" parameter packs.  */
3027             check_for_bare_parameter_packs (TREE_TYPE (parm));
3028             
3029             /* Recover by calling this a parameter pack.  */
3030             is_parameter_pack = true;
3031           }
3032       }
3033
3034       /* A template parameter is not modifiable.  */
3035       TREE_CONSTANT (parm) = 1;
3036       TREE_READONLY (parm) = 1;
3037       decl = build_decl (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 (TYPE_DECL, parm, t);
3067         }
3068
3069       TYPE_NAME (t) = decl;
3070       TYPE_STUB_DECL (t) = decl;
3071       parm = decl;
3072       TEMPLATE_TYPE_PARM_INDEX (t)
3073         = build_template_parm_index (idx, processing_template_decl,
3074                                      processing_template_decl,
3075                                      decl, TREE_TYPE (parm));
3076       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3077       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3078     }
3079   DECL_ARTIFICIAL (decl) = 1;
3080   SET_DECL_TEMPLATE_PARM_P (decl);
3081   pushdecl (decl);
3082   parm = build_tree_list (defval, parm);
3083   return chainon (list, parm);
3084 }
3085
3086 /* The end of a template parameter list has been reached.  Process the
3087    tree list into a parameter vector, converting each parameter into a more
3088    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3089    as PARM_DECLs.  */
3090
3091 tree
3092 end_template_parm_list (tree parms)
3093 {
3094   int nparms;
3095   tree parm, next;
3096   tree saved_parmlist = make_tree_vec (list_length (parms));
3097
3098   current_template_parms
3099     = tree_cons (size_int (processing_template_decl),
3100                  saved_parmlist, current_template_parms);
3101
3102   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3103     {
3104       next = TREE_CHAIN (parm);
3105       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3106       TREE_CHAIN (parm) = NULL_TREE;
3107     }
3108
3109   --processing_template_parmlist;
3110
3111   return saved_parmlist;
3112 }
3113
3114 /* end_template_decl is called after a template declaration is seen.  */
3115
3116 void
3117 end_template_decl (void)
3118 {
3119   reset_specialization ();
3120
3121   if (! processing_template_decl)
3122     return;
3123
3124   /* This matches the pushlevel in begin_template_parm_list.  */
3125   finish_scope ();
3126
3127   --processing_template_decl;
3128   current_template_parms = TREE_CHAIN (current_template_parms);
3129 }
3130
3131 /* Within the declaration of a template, return all levels of template
3132    parameters that apply.  The template parameters are represented as
3133    a TREE_VEC, in the form documented in cp-tree.h for template
3134    arguments.  */
3135
3136 static tree
3137 current_template_args (void)
3138 {
3139   tree header;
3140   tree args = NULL_TREE;
3141   int length = TMPL_PARMS_DEPTH (current_template_parms);
3142   int l = length;
3143
3144   /* If there is only one level of template parameters, we do not
3145      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3146      TREE_VEC containing the arguments.  */
3147   if (length > 1)
3148     args = make_tree_vec (length);
3149
3150   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3151     {
3152       tree a = copy_node (TREE_VALUE (header));
3153       int i;
3154
3155       TREE_TYPE (a) = NULL_TREE;
3156       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3157         {
3158           tree t = TREE_VEC_ELT (a, i);
3159
3160           /* T will be a list if we are called from within a
3161              begin/end_template_parm_list pair, but a vector directly
3162              if within a begin/end_member_template_processing pair.  */
3163           if (TREE_CODE (t) == TREE_LIST)
3164             {
3165               t = TREE_VALUE (t);
3166
3167               if (!error_operand_p (t))
3168                 {
3169                   if (TREE_CODE (t) == TYPE_DECL
3170                       || TREE_CODE (t) == TEMPLATE_DECL)
3171                     {
3172                       t = TREE_TYPE (t);
3173                       
3174                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3175                         {
3176                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3177                              with a single element, which expands T.  */
3178                           tree vec = make_tree_vec (1);
3179                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3180                           
3181                           t = make_node (TYPE_ARGUMENT_PACK);
3182                           SET_ARGUMENT_PACK_ARGS (t, vec);
3183                         }
3184                     }
3185                   else
3186                     {
3187                       t = DECL_INITIAL (t);
3188                       
3189                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3190                         {
3191                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3192                              with a single element, which expands T.  */
3193                           tree vec = make_tree_vec (1);
3194                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3195                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3196                           
3197                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3198                           SET_ARGUMENT_PACK_ARGS (t, vec);
3199                           TREE_TYPE (t) = type;
3200                         }
3201                     }
3202                   TREE_VEC_ELT (a, i) = t;
3203                 }
3204             }
3205         }
3206
3207       if (length > 1)
3208         TREE_VEC_ELT (args, --l) = a;
3209       else
3210         args = a;
3211     }
3212
3213   return args;
3214 }
3215
3216 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3217    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3218    a member template.  Used by push_template_decl below.  */
3219
3220 static tree
3221 build_template_decl (tree decl, tree parms, bool member_template_p)
3222 {
3223   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3224   DECL_TEMPLATE_PARMS (tmpl) = parms;
3225   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3226   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3227   if (DECL_LANG_SPECIFIC (decl))
3228     {
3229       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3230       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3231       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3232       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3233       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3234       if (DECL_OVERLOADED_OPERATOR_P (decl))
3235         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3236                                       DECL_OVERLOADED_OPERATOR_P (decl));
3237     }
3238
3239   return tmpl;
3240 }
3241
3242 struct template_parm_data
3243 {
3244   /* The level of the template parameters we are currently
3245      processing.  */
3246   int level;
3247
3248   /* The index of the specialization argument we are currently
3249      processing.  */
3250   int current_arg;
3251
3252   /* An array whose size is the number of template parameters.  The
3253      elements are nonzero if the parameter has been used in any one
3254      of the arguments processed so far.  */
3255   int* parms;
3256
3257   /* An array whose size is the number of template arguments.  The
3258      elements are nonzero if the argument makes use of template
3259      parameters of this level.  */
3260   int* arg_uses_template_parms;
3261 };
3262
3263 /* Subroutine of push_template_decl used to see if each template
3264    parameter in a partial specialization is used in the explicit
3265    argument list.  If T is of the LEVEL given in DATA (which is
3266    treated as a template_parm_data*), then DATA->PARMS is marked
3267    appropriately.  */
3268
3269 static int
3270 mark_template_parm (tree t, void* data)
3271 {
3272   int level;
3273   int idx;
3274   struct template_parm_data* tpd = (struct template_parm_data*) data;
3275
3276   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3277     {
3278       level = TEMPLATE_PARM_LEVEL (t);
3279       idx = TEMPLATE_PARM_IDX (t);
3280     }
3281   else
3282     {
3283       level = TEMPLATE_TYPE_LEVEL (t);
3284       idx = TEMPLATE_TYPE_IDX (t);
3285     }
3286
3287   if (level == tpd->level)
3288     {
3289       tpd->parms[idx] = 1;
3290       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3291     }
3292
3293   /* Return zero so that for_each_template_parm will continue the
3294      traversal of the tree; we want to mark *every* template parm.  */
3295   return 0;
3296 }
3297
3298 /* Process the partial specialization DECL.  */
3299
3300 static tree
3301 process_partial_specialization (tree decl)
3302 {
3303   tree type = TREE_TYPE (decl);
3304   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3305   tree specargs = CLASSTYPE_TI_ARGS (type);
3306   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3307   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3308   tree inner_parms;
3309   int nargs = TREE_VEC_LENGTH (inner_args);
3310   int ntparms;
3311   int  i;
3312   int did_error_intro = 0;
3313   struct template_parm_data tpd;
3314   struct template_parm_data tpd2;
3315
3316   gcc_assert (current_template_parms);
3317
3318   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3319   ntparms = TREE_VEC_LENGTH (inner_parms);
3320
3321   /* We check that each of the template parameters given in the
3322      partial specialization is used in the argument list to the
3323      specialization.  For example:
3324
3325        template <class T> struct S;
3326        template <class T> struct S<T*>;
3327
3328      The second declaration is OK because `T*' uses the template
3329      parameter T, whereas
3330
3331        template <class T> struct S<int>;
3332
3333      is no good.  Even trickier is:
3334
3335        template <class T>
3336        struct S1
3337        {
3338           template <class U>
3339           struct S2;
3340           template <class U>
3341           struct S2<T>;
3342        };
3343
3344      The S2<T> declaration is actually invalid; it is a
3345      full-specialization.  Of course,
3346
3347           template <class U>
3348           struct S2<T (*)(U)>;
3349
3350      or some such would have been OK.  */
3351   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3352   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3353   memset (tpd.parms, 0, sizeof (int) * ntparms);
3354
3355   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3356   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3357   for (i = 0; i < nargs; ++i)
3358     {
3359       tpd.current_arg = i;
3360       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3361                               &mark_template_parm,
3362                               &tpd,
3363                               NULL,
3364                               /*include_nondeduced_p=*/false);
3365     }
3366   for (i = 0; i < ntparms; ++i)
3367     if (tpd.parms[i] == 0)
3368       {
3369         /* One of the template parms was not used in the
3370            specialization.  */
3371         if (!did_error_intro)
3372           {
3373             error ("template parameters not used in partial specialization:");
3374             did_error_intro = 1;
3375           }
3376
3377         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3378       }
3379
3380   /* [temp.class.spec]
3381
3382      The argument list of the specialization shall not be identical to
3383      the implicit argument list of the primary template.  */
3384   if (comp_template_args
3385       (inner_args,
3386        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3387                                                    (maintmpl)))))
3388     error ("partial specialization %qT does not specialize any template arguments", type);
3389
3390   /* [temp.class.spec]
3391
3392      A partially specialized non-type argument expression shall not
3393      involve template parameters of the partial specialization except
3394      when the argument expression is a simple identifier.
3395
3396      The type of a template parameter corresponding to a specialized
3397      non-type argument shall not be dependent on a parameter of the
3398      specialization. 
3399
3400      Also, we verify that pack expansions only occur at the
3401      end of the argument list.  */
3402   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3403   tpd2.parms = 0;
3404   for (i = 0; i < nargs; ++i)
3405     {
3406       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3407       tree arg = TREE_VEC_ELT (inner_args, i);
3408       tree packed_args = NULL_TREE;
3409       int j, len = 1;
3410
3411       if (ARGUMENT_PACK_P (arg))
3412         {
3413           /* Extract the arguments from the argument pack. We'll be
3414              iterating over these in the following loop.  */
3415           packed_args = ARGUMENT_PACK_ARGS (arg);
3416           len = TREE_VEC_LENGTH (packed_args);
3417         }
3418
3419       for (j = 0; j < len; j++)
3420         {
3421           if (packed_args)
3422             /* Get the Jth argument in the parameter pack.  */
3423             arg = TREE_VEC_ELT (packed_args, j);
3424
3425           if (PACK_EXPANSION_P (arg))
3426             {
3427               /* Pack expansions must come at the end of the
3428                  argument list.  */
3429               if ((packed_args && j < len - 1)
3430                   || (!packed_args && i < nargs - 1))
3431                 {
3432                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3433                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3434                   else
3435                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3436
3437                   if (packed_args)
3438                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3439                 }
3440             }
3441
3442           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3443             /* We only care about the pattern.  */
3444             arg = PACK_EXPANSION_PATTERN (arg);
3445
3446           if (/* These first two lines are the `non-type' bit.  */
3447               !TYPE_P (arg)
3448               && TREE_CODE (arg) != TEMPLATE_DECL
3449               /* This next line is the `argument expression is not just a
3450                  simple identifier' condition and also the `specialized
3451                  non-type argument' bit.  */
3452               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3453             {
3454               if ((!packed_args && tpd.arg_uses_template_parms[i])
3455                   || (packed_args && uses_template_parms (arg)))
3456                 error ("template argument %qE involves template parameter(s)",
3457                        arg);
3458               else 
3459                 {
3460                   /* Look at the corresponding template parameter,
3461                      marking which template parameters its type depends
3462                      upon.  */
3463                   tree type = TREE_TYPE (parm);
3464
3465                   if (!tpd2.parms)
3466                     {
3467                       /* We haven't yet initialized TPD2.  Do so now.  */
3468                       tpd2.arg_uses_template_parms 
3469                         = (int *) alloca (sizeof (int) * nargs);
3470                       /* The number of parameters here is the number in the
3471                          main template, which, as checked in the assertion
3472                          above, is NARGS.  */
3473                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3474                       tpd2.level = 
3475                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3476                     }
3477
3478                   /* Mark the template parameters.  But this time, we're
3479                      looking for the template parameters of the main
3480                      template, not in the specialization.  */
3481                   tpd2.current_arg = i;
3482                   tpd2.arg_uses_template_parms[i] = 0;
3483                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3484                   for_each_template_parm (type,
3485                                           &mark_template_parm,
3486                                           &tpd2,
3487                                           NULL,
3488                                           /*include_nondeduced_p=*/false);
3489
3490                   if (tpd2.arg_uses_template_parms [i])
3491                     {
3492                       /* The type depended on some template parameters.
3493                          If they are fully specialized in the
3494                          specialization, that's OK.  */
3495                       int j;
3496                       for (j = 0; j < nargs; ++j)
3497                         if (tpd2.parms[j] != 0
3498                             && tpd.arg_uses_template_parms [j])
3499                           {
3500                             error ("type %qT of template argument %qE depends "
3501                                    "on template parameter(s)", 
3502                                    type,
3503                                    arg);
3504                             break;
3505                           }
3506                     }
3507                 }
3508             }
3509         }
3510     }
3511
3512   if (retrieve_specialization (maintmpl, specargs,
3513                                /*class_specializations_p=*/true))
3514     /* We've already got this specialization.  */
3515     return decl;
3516
3517   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3518     = tree_cons (specargs, inner_parms,
3519                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3520   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3521   return decl;
3522 }
3523
3524 /* Check that a template declaration's use of default arguments and
3525    parameter packs is not invalid.  Here, PARMS are the template
3526    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3527    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3528    specialization.
3529    
3530
3531    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3532    declaration (but not a definition); 1 indicates a declaration, 2
3533    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3534    emitted for extraneous default arguments.
3535
3536    Returns TRUE if there were no errors found, FALSE otherwise. */
3537
3538 bool
3539 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3540                          int is_partial, int is_friend_decl)
3541 {
3542   const char *msg;
3543   int last_level_to_check;
3544   tree parm_level;
3545   bool no_errors = true;
3546
3547   /* [temp.param]
3548
3549      A default template-argument shall not be specified in a
3550      function template declaration or a function template definition, nor
3551      in the template-parameter-list of the definition of a member of a
3552      class template.  */
3553
3554   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3555     /* You can't have a function template declaration in a local
3556        scope, nor you can you define a member of a class template in a
3557        local scope.  */
3558     return true;
3559
3560   if (current_class_type
3561       && !TYPE_BEING_DEFINED (current_class_type)
3562       && DECL_LANG_SPECIFIC (decl)
3563       /* If this is either a friend defined in the scope of the class
3564          or a member function.  */
3565       && (DECL_FUNCTION_MEMBER_P (decl)
3566           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3567           : DECL_FRIEND_CONTEXT (decl)
3568           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3569           : false)
3570       /* And, if it was a member function, it really was defined in
3571          the scope of the class.  */
3572       && (!DECL_FUNCTION_MEMBER_P (decl)
3573           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3574     /* We already checked these parameters when the template was
3575        declared, so there's no need to do it again now.  This function
3576        was defined in class scope, but we're processing it's body now
3577        that the class is complete.  */
3578     return true;
3579
3580   /* Core issue 226 (C++0x only): the following only applies to class
3581      templates.  */
3582   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3583     {
3584       /* [temp.param]
3585
3586          If a template-parameter has a default template-argument, all
3587          subsequent template-parameters shall have a default
3588          template-argument supplied.  */
3589       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3590         {
3591           tree inner_parms = TREE_VALUE (parm_level);
3592           int ntparms = TREE_VEC_LENGTH (inner_parms);
3593           int seen_def_arg_p = 0;
3594           int i;
3595
3596           for (i = 0; i < ntparms; ++i)
3597             {
3598               tree parm = TREE_VEC_ELT (inner_parms, i);
3599
3600               if (parm == error_mark_node)
3601                 continue;
3602
3603               if (TREE_PURPOSE (parm))
3604                 seen_def_arg_p = 1;
3605               else if (seen_def_arg_p
3606                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3607                 {
3608                   error ("no default argument for %qD", TREE_VALUE (parm));
3609                   /* For better subsequent error-recovery, we indicate that
3610                      there should have been a default argument.  */
3611                   TREE_PURPOSE (parm) = error_mark_node;
3612                   no_errors = false;
3613                 }
3614               else if (is_primary
3615                        && !is_partial
3616                        && !is_friend_decl
3617                        /* Don't complain about an enclosing partial
3618                           specialization.  */
3619                        && parm_level == parms
3620                        && TREE_CODE (decl) == TYPE_DECL
3621                        && i < ntparms - 1
3622                        && template_parameter_pack_p (TREE_VALUE (parm)))
3623                 {
3624                   /* A primary class template can only have one
3625                      parameter pack, at the end of the template
3626                      parameter list.  */
3627
3628                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3629                     error ("parameter pack %qE must be at the end of the"
3630                            " template parameter list", TREE_VALUE (parm));
3631                   else
3632                     error ("parameter pack %qT must be at the end of the"
3633                            " template parameter list", 
3634                            TREE_TYPE (TREE_VALUE (parm)));
3635
3636                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3637                     = error_mark_node;
3638                   no_errors = false;
3639                 }
3640             }
3641         }
3642     }
3643
3644   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3645       || is_partial 
3646       || !is_primary
3647       || is_friend_decl)
3648     /* For an ordinary class template, default template arguments are
3649        allowed at the innermost level, e.g.:
3650          template <class T = int>
3651          struct S {};
3652        but, in a partial specialization, they're not allowed even
3653        there, as we have in [temp.class.spec]:
3654
3655          The template parameter list of a specialization shall not
3656          contain default template argument values.
3657
3658        So, for a partial specialization, or for a function template
3659        (in C++98/C++03), we look at all of them.  */
3660     ;
3661   else
3662     /* But, for a primary class template that is not a partial
3663        specialization we look at all template parameters except the
3664        innermost ones.  */
3665     parms = TREE_CHAIN (parms);
3666
3667   /* Figure out what error message to issue.  */
3668   if (is_friend_decl == 2)
3669     msg = "default template arguments may not be used in function template friend re-declaration";
3670   else if (is_friend_decl)
3671     msg = "default template arguments may not be used in function template friend declarations";
3672   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3673     msg = "default template arguments may not be used in function templates";
3674   else if (is_partial)
3675     msg = "default template arguments may not be used in partial specializations";
3676   else
3677     msg = "default argument for template parameter for class enclosing %qD";
3678
3679   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3680     /* If we're inside a class definition, there's no need to
3681        examine the parameters to the class itself.  On the one
3682        hand, they will be checked when the class is defined, and,
3683        on the other, default arguments are valid in things like:
3684          template <class T = double>
3685          struct S { template <class U> void f(U); };
3686        Here the default argument for `S' has no bearing on the
3687        declaration of `f'.  */
3688     last_level_to_check = template_class_depth (current_class_type) + 1;
3689   else
3690     /* Check everything.  */
3691     last_level_to_check = 0;
3692
3693   for (parm_level = parms;
3694        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3695        parm_level = TREE_CHAIN (parm_level))
3696     {
3697       tree inner_parms = TREE_VALUE (parm_level);
3698       int i;
3699       int ntparms;
3700
3701       ntparms = TREE_VEC_LENGTH (inner_parms);
3702       for (i = 0; i < ntparms; ++i)
3703         {
3704           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3705             continue;
3706
3707           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3708             {
3709               if (msg)
3710                 {
3711                   no_errors = false;
3712                   if (is_friend_decl == 2)
3713                     return no_errors;
3714
3715                   error (msg, decl);
3716                   msg = 0;
3717                 }
3718
3719               /* Clear out the default argument so that we are not
3720                  confused later.  */
3721               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3722             }
3723         }
3724
3725       /* At this point, if we're still interested in issuing messages,
3726          they must apply to classes surrounding the object declared.  */
3727       if (msg)
3728         msg = "default argument for template parameter for class enclosing %qD";
3729     }
3730
3731   return no_errors;
3732 }
3733
3734 /* Worker for push_template_decl_real, called via
3735    for_each_template_parm.  DATA is really an int, indicating the
3736    level of the parameters we are interested in.  If T is a template
3737    parameter of that level, return nonzero.  */
3738
3739 static int
3740 template_parm_this_level_p (tree t, void* data)
3741 {
3742   int this_level = *(int *)data;
3743   int level;
3744
3745   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3746     level = TEMPLATE_PARM_LEVEL (t);
3747   else
3748     level = TEMPLATE_TYPE_LEVEL (t);
3749   return level == this_level;
3750 }
3751
3752 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3753    parameters given by current_template_args, or reuses a
3754    previously existing one, if appropriate.  Returns the DECL, or an
3755    equivalent one, if it is replaced via a call to duplicate_decls.
3756
3757    If IS_FRIEND is true, DECL is a friend declaration.  */
3758
3759 tree
3760 push_template_decl_real (tree decl, bool is_friend)
3761 {
3762   tree tmpl;
3763   tree args;
3764   tree info;
3765   tree ctx;
3766   int primary;
3767   int is_partial;
3768   int new_template_p = 0;
3769   /* True if the template is a member template, in the sense of
3770      [temp.mem].  */
3771   bool member_template_p = false;
3772
3773   if (decl == error_mark_node || !current_template_parms)
3774     return error_mark_node;
3775
3776   /* See if this is a partial specialization.  */
3777   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3778                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3779                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3780
3781   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3782     is_friend = true;
3783
3784   if (is_friend)
3785     /* For a friend, we want the context of the friend function, not
3786        the type of which it is a friend.  */
3787     ctx = DECL_CONTEXT (decl);
3788   else if (CP_DECL_CONTEXT (decl)
3789            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3790     /* In the case of a virtual function, we want the class in which
3791        it is defined.  */
3792     ctx = CP_DECL_CONTEXT (decl);
3793   else
3794     /* Otherwise, if we're currently defining some class, the DECL
3795        is assumed to be a member of the class.  */
3796     ctx = current_scope ();
3797
3798   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3799     ctx = NULL_TREE;
3800
3801   if (!DECL_CONTEXT (decl))
3802     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3803
3804   /* See if this is a primary template.  */
3805   if (is_friend && ctx)
3806     /* A friend template that specifies a class context, i.e.
3807          template <typename T> friend void A<T>::f();
3808        is not primary.  */
3809     primary = 0;
3810   else
3811     primary = template_parm_scope_p ();
3812
3813   if (primary)
3814     {
3815       if (DECL_CLASS_SCOPE_P (decl))
3816         member_template_p = true;
3817       if (TREE_CODE (decl) == TYPE_DECL
3818           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3819         {
3820           error ("template class without a name");
3821           return error_mark_node;
3822         }
3823       else if (TREE_CODE (decl) == FUNCTION_DECL)
3824         {
3825           if (DECL_DESTRUCTOR_P (decl))
3826             {
3827               /* [temp.mem]
3828
3829                  A destructor shall not be a member template.  */
3830               error ("destructor %qD declared as member template", decl);
3831               return error_mark_node;
3832             }
3833           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3834               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3835                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3836                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3837                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3838                       == void_list_node)))
3839             {
3840               /* [basic.stc.dynamic.allocation]
3841
3842                  An allocation function can be a function
3843                  template. ... Template allocation functions shall
3844                  have two or more parameters.  */
3845               error ("invalid template declaration of %qD", decl);
3846               return error_mark_node;
3847             }
3848         }
3849       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3850                && CLASS_TYPE_P (TREE_TYPE (decl)))
3851         /* OK */;
3852       else
3853         {
3854           error ("template declaration of %q#D", decl);
3855           return error_mark_node;
3856         }
3857     }
3858
3859   /* Check to see that the rules regarding the use of default
3860      arguments are not being violated.  */
3861   check_default_tmpl_args (decl, current_template_parms,
3862                            primary, is_partial, /*is_friend_decl=*/0);
3863
3864   /* Ensure that there are no parameter packs in the type of this
3865      declaration that have not been expanded.  */
3866   if (TREE_CODE (decl) == FUNCTION_DECL)
3867     {
3868       /* Check each of the arguments individually to see if there are
3869          any bare parameter packs.  */
3870       tree type = TREE_TYPE (decl);
3871       tree arg = DECL_ARGUMENTS (decl);
3872       tree argtype = TYPE_ARG_TYPES (type);
3873
3874       while (arg && argtype)
3875         {
3876           if (!FUNCTION_PARAMETER_PACK_P (arg)
3877               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
3878             {
3879             /* This is a PARM_DECL that contains unexpanded parameter
3880                packs. We have already complained about this in the
3881                check_for_bare_parameter_packs call, so just replace
3882                these types with ERROR_MARK_NODE.  */
3883               TREE_TYPE (arg) = error_mark_node;
3884               TREE_VALUE (argtype) = error_mark_node;
3885             }
3886
3887           arg = TREE_CHAIN (arg);
3888           argtype = TREE_CHAIN (argtype);
3889         }
3890
3891       /* Check for bare parameter packs in the return type and the
3892          exception specifiers.  */
3893       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
3894         /* Errors were already issued, set return type to int
3895            as the frontend doesn't expect error_mark_node as
3896            the return type.  */
3897         TREE_TYPE (type) = integer_type_node;
3898       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
3899         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
3900     }
3901   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
3902     {
3903       TREE_TYPE (decl) = error_mark_node;
3904       return error_mark_node;
3905     }
3906
3907   if (is_partial)
3908     return process_partial_specialization (decl);
3909
3910   args = current_template_args ();
3911
3912   if (!ctx
3913       || TREE_CODE (ctx) == FUNCTION_DECL
3914       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3915       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3916     {
3917       if (DECL_LANG_SPECIFIC (decl)
3918           && DECL_TEMPLATE_INFO (decl)
3919           && DECL_TI_TEMPLATE (decl))
3920         tmpl = DECL_TI_TEMPLATE (decl);
3921       /* If DECL is a TYPE_DECL for a class-template, then there won't
3922          be DECL_LANG_SPECIFIC.  The information equivalent to
3923          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3924       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3925                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3926                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3927         {
3928           /* Since a template declaration already existed for this
3929              class-type, we must be redeclaring it here.  Make sure
3930              that the redeclaration is valid.  */
3931           redeclare_class_template (TREE_TYPE (decl),
3932                                     current_template_parms);
3933           /* We don't need to create a new TEMPLATE_DECL; just use the
3934              one we already had.  */
3935           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3936         }
3937       else
3938         {
3939           tmpl = build_template_decl (decl, current_template_parms,
3940                                       member_template_p);
3941           new_template_p = 1;
3942
3943           if (DECL_LANG_SPECIFIC (decl)
3944               && DECL_TEMPLATE_SPECIALIZATION (decl))
3945             {
3946               /* A specialization of a member template of a template
3947                  class.  */
3948               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3949               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3950               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3951             }
3952         }
3953     }
3954   else
3955     {
3956       tree a, t, current, parms;
3957       int i;
3958       tree tinfo = get_template_info (decl);
3959
3960       if (!tinfo)
3961         {
3962           error ("template definition of non-template %q#D", decl);
3963           return error_mark_node;
3964         }
3965
3966       tmpl = TI_TEMPLATE (tinfo);
3967
3968       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3969           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3970           && DECL_TEMPLATE_SPECIALIZATION (decl)
3971           && DECL_MEMBER_TEMPLATE_P (tmpl))
3972         {
3973           tree new_tmpl;
3974
3975           /* The declaration is a specialization of a member
3976              template, declared outside the class.  Therefore, the
3977              innermost template arguments will be NULL, so we
3978              replace them with the arguments determined by the
3979              earlier call to check_explicit_specialization.  */
3980           args = DECL_TI_ARGS (decl);
3981
3982           new_tmpl
3983             = build_template_decl (decl, current_template_parms,
3984                                    member_template_p);
3985           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3986           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3987           DECL_TI_TEMPLATE (decl) = new_tmpl;
3988           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3989           DECL_TEMPLATE_INFO (new_tmpl)
3990             = tree_cons (tmpl, args, NULL_TREE);
3991
3992           register_specialization (new_tmpl,
3993                                    most_general_template (tmpl),
3994                                    args,
3995                                    is_friend);
3996           return decl;
3997         }
3998
3999       /* Make sure the template headers we got make sense.  */
4000
4001       parms = DECL_TEMPLATE_PARMS (tmpl);
4002       i = TMPL_PARMS_DEPTH (parms);
4003       if (TMPL_ARGS_DEPTH (args) != i)
4004         {
4005           error ("expected %d levels of template parms for %q#D, got %d",
4006                  i, decl, TMPL_ARGS_DEPTH (args));
4007         }
4008       else
4009         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4010           {
4011             a = TMPL_ARGS_LEVEL (args, i);
4012             t = INNERMOST_TEMPLATE_PARMS (parms);
4013
4014             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4015               {
4016                 if (current == decl)
4017                   error ("got %d template parameters for %q#D",
4018                          TREE_VEC_LENGTH (a), decl);
4019                 else
4020                   error ("got %d template parameters for %q#T",
4021                          TREE_VEC_LENGTH (a), current);
4022                 error ("  but %d required", TREE_VEC_LENGTH (t));
4023                 return error_mark_node;
4024               }
4025
4026             if (current == decl)
4027               current = ctx;
4028             else
4029               current = (TYPE_P (current)
4030                          ? TYPE_CONTEXT (current)
4031                          : DECL_CONTEXT (current));
4032           }
4033
4034       /* Check that the parms are used in the appropriate qualifying scopes
4035          in the declarator.  */
4036       if (!comp_template_args
4037           (TI_ARGS (tinfo),
4038            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4039         {
4040           error ("\
4041 template arguments to %qD do not match original template %qD",
4042                  decl, DECL_TEMPLATE_RESULT (tmpl));
4043           if (!uses_template_parms (TI_ARGS (tinfo)))
4044             inform (input_location, "use template<> for an explicit specialization");
4045           /* Avoid crash in import_export_decl.  */
4046           DECL_INTERFACE_KNOWN (decl) = 1;
4047           return error_mark_node;
4048         }
4049     }
4050
4051   DECL_TEMPLATE_RESULT (tmpl) = decl;
4052   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4053
4054   /* Push template declarations for global functions and types.  Note
4055      that we do not try to push a global template friend declared in a
4056      template class; such a thing may well depend on the template
4057      parameters of the class.  */
4058   if (new_template_p && !ctx
4059       && !(is_friend && template_class_depth (current_class_type) > 0))
4060     {
4061       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4062       if (tmpl == error_mark_node)
4063         return error_mark_node;
4064
4065       /* Hide template friend classes that haven't been declared yet.  */
4066       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4067         {
4068           DECL_ANTICIPATED (tmpl) = 1;
4069           DECL_FRIEND_P (tmpl) = 1;
4070         }
4071     }
4072
4073   if (primary)
4074     {
4075       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4076       int i;
4077
4078       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4079       if (DECL_CONV_FN_P (tmpl))
4080         {
4081           int depth = TMPL_PARMS_DEPTH (parms);
4082
4083           /* It is a conversion operator. See if the type converted to
4084              depends on innermost template operands.  */
4085
4086           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4087                                          depth))
4088             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4089         }
4090
4091       /* Give template template parms a DECL_CONTEXT of the template
4092          for which they are a parameter.  */
4093       parms = INNERMOST_TEMPLATE_PARMS (parms);
4094       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4095         {
4096           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4097           if (TREE_CODE (parm) == TEMPLATE_DECL)
4098             DECL_CONTEXT (parm) = tmpl;
4099         }
4100     }
4101
4102   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4103      back to its most general template.  If TMPL is a specialization,
4104      ARGS may only have the innermost set of arguments.  Add the missing
4105      argument levels if necessary.  */
4106   if (DECL_TEMPLATE_INFO (tmpl))
4107     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4108
4109   info = tree_cons (tmpl, args, NULL_TREE);
4110
4111   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4112     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4113   else if (DECL_LANG_SPECIFIC (decl))
4114     DECL_TEMPLATE_INFO (decl) = info;
4115
4116   return DECL_TEMPLATE_RESULT (tmpl);
4117 }
4118
4119 tree
4120 push_template_decl (tree decl)
4121 {
4122   return push_template_decl_real (decl, false);
4123 }
4124
4125 /* Called when a class template TYPE is redeclared with the indicated
4126    template PARMS, e.g.:
4127
4128      template <class T> struct S;
4129      template <class T> struct S {};  */
4130
4131 bool
4132 redeclare_class_template (tree type, tree parms)
4133 {
4134   tree tmpl;
4135   tree tmpl_parms;
4136   int i;
4137
4138   if (!TYPE_TEMPLATE_INFO (type))
4139     {
4140       error ("%qT is not a template type", type);
4141       return false;
4142     }
4143
4144   tmpl = TYPE_TI_TEMPLATE (type);
4145   if (!PRIMARY_TEMPLATE_P (tmpl))
4146     /* The type is nested in some template class.  Nothing to worry
4147        about here; there are no new template parameters for the nested
4148        type.  */
4149     return true;
4150
4151   if (!parms)
4152     {
4153       error ("template specifiers not specified in declaration of %qD",
4154              tmpl);
4155       return false;
4156     }
4157
4158   parms = INNERMOST_TEMPLATE_PARMS (parms);
4159   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4160
4161   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4162     {
4163       error ("redeclared with %d template parameter(s)", 
4164              TREE_VEC_LENGTH (parms));
4165       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4166              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4167       return false;
4168     }
4169
4170   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4171     {
4172       tree tmpl_parm;
4173       tree parm;
4174       tree tmpl_default;
4175       tree parm_default;
4176
4177       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4178           || TREE_VEC_ELT (parms, i) == error_mark_node)
4179         continue;
4180
4181       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4182       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4183       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4184       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4185
4186       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4187          TEMPLATE_DECL.  */
4188       if (tmpl_parm != error_mark_node
4189           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4190               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4191                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4192               || (TREE_CODE (tmpl_parm) != PARM_DECL
4193                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4194                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4195               || (TREE_CODE (tmpl_parm) == PARM_DECL
4196                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4197                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4198         {
4199           error ("template parameter %q+#D", tmpl_parm);
4200           error ("redeclared here as %q#D", parm);
4201           return false;
4202         }
4203
4204       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4205         {
4206           /* We have in [temp.param]:
4207
4208              A template-parameter may not be given default arguments
4209              by two different declarations in the same scope.  */
4210           error ("redefinition of default argument for %q#D", parm);
4211           inform (input_location, "%Joriginal definition appeared here", tmpl_parm);
4212           return false;
4213         }
4214
4215       if (parm_default != NULL_TREE)
4216         /* Update the previous template parameters (which are the ones
4217            that will really count) with the new default value.  */
4218         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4219       else if (tmpl_default != NULL_TREE)
4220         /* Update the new parameters, too; they'll be used as the
4221            parameters for any members.  */
4222         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4223     }
4224
4225     return true;
4226 }
4227
4228 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4229    (possibly simplified) expression.  */
4230
4231 tree
4232 fold_non_dependent_expr (tree expr)
4233 {
4234   if (expr == NULL_TREE)
4235     return NULL_TREE;
4236
4237   /* If we're in a template, but EXPR isn't value dependent, simplify
4238      it.  We're supposed to treat:
4239
4240        template <typename T> void f(T[1 + 1]);
4241        template <typename T> void f(T[2]);
4242
4243      as two declarations of the same function, for example.  */
4244   if (processing_template_decl
4245       && !type_dependent_expression_p (expr)
4246       && !value_dependent_expression_p (expr))
4247     {
4248       HOST_WIDE_INT saved_processing_template_decl;
4249
4250       saved_processing_template_decl = processing_template_decl;
4251       processing_template_decl = 0;
4252       expr = tsubst_copy_and_build (expr,
4253                                     /*args=*/NULL_TREE,
4254                                     tf_error,
4255                                     /*in_decl=*/NULL_TREE,
4256                                     /*function_p=*/false,
4257                                     /*integral_constant_expression_p=*/true);
4258       processing_template_decl = saved_processing_template_decl;
4259     }
4260   return expr;
4261 }
4262
4263 /* EXPR is an expression which is used in a constant-expression context.
4264    For instance, it could be a VAR_DECL with a constant initializer.
4265    Extract the innermost constant expression.
4266
4267    This is basically a more powerful version of
4268    integral_constant_value, which can be used also in templates where
4269    initializers can maintain a syntactic rather than semantic form
4270    (even if they are non-dependent, for access-checking purposes).  */
4271
4272 static tree
4273 fold_decl_constant_value (tree expr)
4274 {
4275   tree const_expr = expr;
4276   do
4277     {
4278       expr = fold_non_dependent_expr (const_expr);
4279       const_expr = integral_constant_value (expr);
4280     }
4281   while (expr != const_expr);
4282
4283   return expr;
4284 }
4285
4286 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4287    must be a function or a pointer-to-function type, as specified
4288    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4289    and check that the resulting function has external linkage.  */
4290
4291 static tree
4292 convert_nontype_argument_function (tree type, tree expr)
4293 {
4294   tree fns = expr;
4295   tree fn, fn_no_ptr;
4296
4297   fn = instantiate_type (type, fns, tf_none);
4298   if (fn == error_mark_node)
4299     return error_mark_node;
4300
4301   fn_no_ptr = fn;
4302   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4303     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4304   if (TREE_CODE (fn_no_ptr) == BASELINK)
4305     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4306  
4307   /* [temp.arg.nontype]/1
4308
4309      A template-argument for a non-type, non-template template-parameter
4310      shall be one of:
4311      [...]
4312      -- the address of an object or function with external linkage.  */
4313   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4314     {
4315       error ("%qE is not a valid template argument for type %qT "
4316              "because function %qD has not external linkage",
4317              expr, type, fn_no_ptr);
4318       return NULL_TREE;
4319     }
4320
4321   return fn;
4322 }
4323
4324 /* Attempt to convert the non-type template parameter EXPR to the
4325    indicated TYPE.  If the conversion is successful, return the
4326    converted value.  If the conversion is unsuccessful, return
4327    NULL_TREE if we issued an error message, or error_mark_node if we
4328    did not.  We issue error messages for out-and-out bad template
4329    parameters, but not simply because the conversion failed, since we
4330    might be just trying to do argument deduction.  Both TYPE and EXPR
4331    must be non-dependent.
4332
4333    The conversion follows the special rules described in
4334    [temp.arg.nontype], and it is much more strict than an implicit
4335    conversion.
4336
4337    This function is called twice for each template argument (see
4338    lookup_template_class for a more accurate description of this
4339    problem). This means that we need to handle expressions which
4340    are not valid in a C++ source, but can be created from the
4341    first call (for instance, casts to perform conversions). These
4342    hacks can go away after we fix the double coercion problem.  */
4343
4344 static tree
4345 convert_nontype_argument (tree type, tree expr)
4346 {
4347   tree expr_type;
4348
4349   /* Detect immediately string literals as invalid non-type argument.
4350      This special-case is not needed for correctness (we would easily
4351      catch this later), but only to provide better diagnostic for this
4352      common user mistake. As suggested by DR 100, we do not mention
4353      linkage issues in the diagnostic as this is not the point.  */
4354   if (TREE_CODE (expr) == STRING_CST)
4355     {
4356       error ("%qE is not a valid template argument for type %qT "
4357              "because string literals can never be used in this context",
4358              expr, type);
4359       return NULL_TREE;
4360     }
4361
4362   /* If we are in a template, EXPR may be non-dependent, but still
4363      have a syntactic, rather than semantic, form.  For example, EXPR
4364      might be a SCOPE_REF, rather than the VAR_DECL to which the
4365      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4366      so that access checking can be performed when the template is
4367      instantiated -- but here we need the resolved form so that we can
4368      convert the argument.  */
4369   expr = fold_non_dependent_expr (expr);
4370   if (error_operand_p (expr))
4371     return error_mark_node;
4372   expr_type = TREE_TYPE (expr);
4373
4374   /* HACK: Due to double coercion, we can get a
4375      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4376      which is the tree that we built on the first call (see
4377      below when coercing to reference to object or to reference to
4378      function). We just strip everything and get to the arg.
4379      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4380      for examples.  */
4381   if (TREE_CODE (expr) == NOP_EXPR)
4382     {
4383       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4384         {
4385           /* ??? Maybe we could use convert_from_reference here, but we
4386              would need to relax its constraints because the NOP_EXPR
4387              could actually change the type to something more cv-qualified,
4388              and this is not folded by convert_from_reference.  */
4389           tree addr = TREE_OPERAND (expr, 0);
4390           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4391           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4392           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4393           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4394                       (TREE_TYPE (expr_type),
4395                        TREE_TYPE (TREE_TYPE (addr))));
4396
4397           expr = TREE_OPERAND (addr, 0);
4398           expr_type = TREE_TYPE (expr);
4399         }
4400
4401       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4402          parameter is a pointer to object, through decay and
4403          qualification conversion. Let's strip everything.  */
4404       else if (TYPE_PTROBV_P (type))
4405         {
4406           STRIP_NOPS (expr);
4407           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4408           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4409           /* Skip the ADDR_EXPR only if it is part of the decay for
4410              an array. Otherwise, it is part of the original argument
4411              in the source code.  */
4412           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4413             expr = TREE_OPERAND (expr, 0);
4414           expr_type = TREE_TYPE (expr);
4415         }
4416     }
4417
4418   /* [temp.arg.nontype]/5, bullet 1
4419
4420      For a non-type template-parameter of integral or enumeration type,
4421      integral promotions (_conv.prom_) and integral conversions
4422      (_conv.integral_) are applied.  */
4423   if (INTEGRAL_TYPE_P (type))
4424     {
4425       if (!INTEGRAL_TYPE_P (expr_type))
4426         return error_mark_node;
4427
4428       expr = fold_decl_constant_value (expr);
4429       /* Notice that there are constant expressions like '4 % 0' which
4430          do not fold into integer constants.  */
4431       if (TREE_CODE (expr) != INTEGER_CST)
4432         {
4433           error ("%qE is not a valid template argument for type %qT "
4434                  "because it is a non-constant expression", expr, type);
4435           return NULL_TREE;
4436         }
4437
4438       /* At this point, an implicit conversion does what we want,
4439          because we already know that the expression is of integral
4440          type.  */
4441       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4442       if (expr == error_mark_node)
4443         return error_mark_node;
4444
4445       /* Conversion was allowed: fold it to a bare integer constant.  */
4446       expr = fold (expr);
4447     }
4448   /* [temp.arg.nontype]/5, bullet 2
4449
4450      For a non-type template-parameter of type pointer to object,
4451      qualification conversions (_conv.qual_) and the array-to-pointer
4452      conversion (_conv.array_) are applied.  */
4453   else if (TYPE_PTROBV_P (type))
4454     {
4455       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4456
4457          A template-argument for a non-type, non-template template-parameter
4458          shall be one of: [...]
4459
4460          -- the name of a non-type template-parameter;
4461          -- the address of an object or function with external linkage, [...]
4462             expressed as "& id-expression" where the & is optional if the name
4463             refers to a function or array, or if the corresponding
4464             template-parameter is a reference.
4465
4466         Here, we do not care about functions, as they are invalid anyway
4467         for a parameter of type pointer-to-object.  */
4468
4469       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4470         /* Non-type template parameters are OK.  */
4471         ;
4472       else if (TREE_CODE (expr) != ADDR_EXPR
4473                && TREE_CODE (expr_type) != ARRAY_TYPE)
4474         {
4475           if (TREE_CODE (expr) == VAR_DECL)
4476             {
4477               error ("%qD is not a valid template argument "
4478                      "because %qD is a variable, not the address of "
4479                      "a variable",
4480                      expr, expr);
4481               return NULL_TREE;
4482             }
4483           /* Other values, like integer constants, might be valid
4484              non-type arguments of some other type.  */
4485           return error_mark_node;
4486         }
4487       else
4488         {
4489           tree decl;
4490
4491           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4492                   ? TREE_OPERAND (expr, 0) : expr);
4493           if (TREE_CODE (decl) != VAR_DECL)
4494             {
4495               error ("%qE is not a valid template argument of type %qT "
4496                      "because %qE is not a variable",
4497                      expr, type, decl);
4498               return NULL_TREE;
4499             }
4500           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4501             {
4502               error ("%qE is not a valid template argument of type %qT "
4503                      "because %qD does not have external linkage",
4504                      expr, type, decl);
4505               return NULL_TREE;
4506             }
4507         }
4508
4509       expr = decay_conversion (expr);
4510       if (expr == error_mark_node)
4511         return error_mark_node;
4512
4513       expr = perform_qualification_conversions (type, expr);
4514       if (expr == error_mark_node)
4515         return error_mark_node;
4516     }
4517   /* [temp.arg.nontype]/5, bullet 3
4518
4519      For a non-type template-parameter of type reference to object, no
4520      conversions apply. The type referred to by the reference may be more
4521      cv-qualified than the (otherwise identical) type of the
4522      template-argument. The template-parameter is bound directly to the
4523      template-argument, which must be an lvalue.  */
4524   else if (TYPE_REF_OBJ_P (type))
4525     {
4526       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4527                                                       expr_type))
4528         return error_mark_node;
4529
4530       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4531         {
4532           error ("%qE is not a valid template argument for type %qT "
4533                  "because of conflicts in cv-qualification", expr, type);
4534           return NULL_TREE;
4535         }
4536
4537       if (!real_lvalue_p (expr))
4538         {
4539           error ("%qE is not a valid template argument for type %qT "
4540                  "because it is not an lvalue", expr, type);
4541           return NULL_TREE;
4542         }
4543
4544       /* [temp.arg.nontype]/1
4545
4546          A template-argument for a non-type, non-template template-parameter
4547          shall be one of: [...]
4548
4549          -- the address of an object or function with external linkage.  */
4550       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4551         {
4552           error ("%qE is not a valid template argument for type %qT "
4553                  "because object %qD has not external linkage",
4554                  expr, type, expr);
4555           return NULL_TREE;
4556         }
4557
4558       expr = build_nop (type, build_address (expr));
4559     }
4560   /* [temp.arg.nontype]/5, bullet 4
4561
4562      For a non-type template-parameter of type pointer to function, only
4563      the function-to-pointer conversion (_conv.func_) is applied. If the
4564      template-argument represents a set of overloaded functions (or a
4565      pointer to such), the matching function is selected from the set
4566      (_over.over_).  */
4567   else if (TYPE_PTRFN_P (type))
4568     {
4569       /* If the argument is a template-id, we might not have enough
4570          context information to decay the pointer.  */
4571       if (!type_unknown_p (expr_type))
4572         {
4573           expr = decay_conversion (expr);
4574           if (expr == error_mark_node)
4575             return error_mark_node;
4576         }
4577
4578       expr = convert_nontype_argument_function (type, expr);
4579       if (!expr || expr == error_mark_node)
4580         return expr;
4581
4582       if (TREE_CODE (expr) != ADDR_EXPR)
4583         {
4584           error ("%qE is not a valid template argument for type %qT", expr, type);
4585           error ("it must be the address of a function with external linkage");
4586           return NULL_TREE;
4587         }
4588     }
4589   /* [temp.arg.nontype]/5, bullet 5
4590
4591      For a non-type template-parameter of type reference to function, no
4592      conversions apply. If the template-argument represents a set of
4593      overloaded functions, the matching function is selected from the set
4594      (_over.over_).  */
4595   else if (TYPE_REFFN_P (type))
4596     {
4597       if (TREE_CODE (expr) == ADDR_EXPR)
4598         {
4599           error ("%qE is not a valid template argument for type %qT "
4600                  "because it is a pointer", expr, type);
4601           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4602           return NULL_TREE;
4603         }
4604
4605       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4606       if (!expr || expr == error_mark_node)
4607         return expr;
4608
4609       expr = build_nop (type, build_address (expr));
4610     }
4611   /* [temp.arg.nontype]/5, bullet 6
4612
4613      For a non-type template-parameter of type pointer to member function,
4614      no conversions apply. If the template-argument represents a set of
4615      overloaded member functions, the matching member function is selected
4616      from the set (_over.over_).  */
4617   else if (TYPE_PTRMEMFUNC_P (type))
4618     {
4619       expr = instantiate_type (type, expr, tf_none);
4620       if (expr == error_mark_node)
4621         return error_mark_node;
4622
4623       /* There is no way to disable standard conversions in
4624          resolve_address_of_overloaded_function (called by
4625          instantiate_type). It is possible that the call succeeded by
4626          converting &B::I to &D::I (where B is a base of D), so we need
4627          to reject this conversion here.
4628
4629          Actually, even if there was a way to disable standard conversions,
4630          it would still be better to reject them here so that we can
4631          provide a superior diagnostic.  */
4632       if (!same_type_p (TREE_TYPE (expr), type))
4633         {
4634           /* Make sure we are just one standard conversion off.  */
4635           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4636           error ("%qE is not a valid template argument for type %qT "
4637                  "because it is of type %qT", expr, type,
4638                  TREE_TYPE (expr));
4639           inform (input_location, "standard conversions are not allowed in this context");
4640           return NULL_TREE;
4641         }
4642     }
4643   /* [temp.arg.nontype]/5, bullet 7
4644
4645      For a non-type template-parameter of type pointer to data member,
4646      qualification conversions (_conv.qual_) are applied.  */
4647   else if (TYPE_PTRMEM_P (type))
4648     {
4649       expr = perform_qualification_conversions (type, expr);
4650       if (expr == error_mark_node)
4651         return expr;
4652     }
4653   /* A template non-type parameter must be one of the above.  */
4654   else
4655     gcc_unreachable ();
4656
4657   /* Sanity check: did we actually convert the argument to the
4658      right type?  */
4659   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4660   return expr;
4661 }
4662
4663 /* Subroutine of coerce_template_template_parms, which returns 1 if
4664    PARM_PARM and ARG_PARM match using the rule for the template
4665    parameters of template template parameters. Both PARM and ARG are
4666    template parameters; the rest of the arguments are the same as for
4667    coerce_template_template_parms.
4668  */
4669 static int
4670 coerce_template_template_parm (tree parm,
4671                               tree arg,
4672                               tsubst_flags_t complain,
4673                               tree in_decl,
4674                               tree outer_args)
4675 {
4676   if (arg == NULL_TREE || arg == error_mark_node
4677       || parm == NULL_TREE || parm == error_mark_node)
4678     return 0;
4679   
4680   if (TREE_CODE (arg) != TREE_CODE (parm))
4681     return 0;
4682   
4683   switch (TREE_CODE (parm))
4684     {
4685     case TEMPLATE_DECL:
4686       /* We encounter instantiations of templates like
4687          template <template <template <class> class> class TT>
4688          class C;  */
4689       {
4690         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4691         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4692         
4693         if (!coerce_template_template_parms
4694             (parmparm, argparm, complain, in_decl, outer_args))
4695           return 0;
4696       }
4697       /* Fall through.  */
4698       
4699     case TYPE_DECL:
4700       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
4701           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4702         /* Argument is a parameter pack but parameter is not.  */
4703         return 0;
4704       break;
4705       
4706     case PARM_DECL:
4707       /* The tsubst call is used to handle cases such as
4708          
4709            template <int> class C {};
4710            template <class T, template <T> class TT> class D {};
4711            D<int, C> d;
4712
4713          i.e. the parameter list of TT depends on earlier parameters.  */
4714       if (!uses_template_parms (TREE_TYPE (arg))
4715           && !same_type_p
4716                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4717                  TREE_TYPE (arg)))
4718         return 0;
4719       
4720       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
4721           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4722         /* Argument is a parameter pack but parameter is not.  */
4723         return 0;
4724       
4725       break;
4726
4727     default:
4728       gcc_unreachable ();
4729     }
4730
4731   return 1;
4732 }
4733
4734
4735 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4736    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4737    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4738    or PARM_DECL.
4739
4740    Consider the example:
4741      template <class T> class A;
4742      template<template <class U> class TT> class B;
4743
4744    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4745    the parameters to A, and OUTER_ARGS contains A.  */
4746
4747 static int
4748 coerce_template_template_parms (tree parm_parms,
4749                                 tree arg_parms,
4750                                 tsubst_flags_t complain,
4751                                 tree in_decl,
4752                                 tree outer_args)
4753 {
4754   int nparms, nargs, i;
4755   tree parm, arg;
4756   int variadic_p = 0;
4757
4758   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4759   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4760
4761   nparms = TREE_VEC_LENGTH (parm_parms);
4762   nargs = TREE_VEC_LENGTH (arg_parms);
4763
4764   /* Determine whether we have a parameter pack at the end of the
4765      template template parameter's template parameter list.  */
4766   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
4767     {
4768       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
4769       
4770       if (parm == error_mark_node)
4771         return 0;
4772
4773       switch (TREE_CODE (parm))
4774         {
4775         case TEMPLATE_DECL:
4776         case TYPE_DECL:
4777           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4778             variadic_p = 1;
4779           break;
4780           
4781         case PARM_DECL:
4782           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4783             variadic_p = 1;
4784           break;
4785           
4786         default:
4787           gcc_unreachable ();
4788         }
4789     }
4790  
4791   if (nargs != nparms
4792       && !(variadic_p && nargs >= nparms - 1))
4793     return 0;
4794
4795   /* Check all of the template parameters except the parameter pack at
4796      the end (if any).  */
4797   for (i = 0; i < nparms - variadic_p; ++i)
4798     {
4799       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4800           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4801         continue;
4802
4803       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4804       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4805
4806       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4807                                           outer_args))
4808         return 0;
4809
4810     }
4811
4812   if (variadic_p)
4813     {
4814       /* Check each of the template parameters in the template
4815          argument against the template parameter pack at the end of
4816          the template template parameter.  */
4817       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
4818         return 0;
4819
4820       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4821
4822       for (; i < nargs; ++i)
4823         {
4824           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4825             continue;
4826  
4827           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4828  
4829           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4830                                               outer_args))
4831             return 0;
4832         }
4833     }
4834
4835   return 1;
4836 }
4837
4838 /* Verifies that the deduced template arguments (in TARGS) for the
4839    template template parameters (in TPARMS) represent valid bindings,
4840    by comparing the template parameter list of each template argument
4841    to the template parameter list of its corresponding template
4842    template parameter, in accordance with DR150. This
4843    routine can only be called after all template arguments have been
4844    deduced. It will return TRUE if all of the template template
4845    parameter bindings are okay, FALSE otherwise.  */
4846 bool 
4847 template_template_parm_bindings_ok_p (tree tparms, tree targs)
4848 {
4849   int i, ntparms = TREE_VEC_LENGTH (tparms);
4850   bool ret = true;
4851
4852   /* We're dealing with template parms in this process.  */
4853   ++processing_template_decl;
4854
4855   targs = INNERMOST_TEMPLATE_ARGS (targs);
4856
4857   for (i = 0; i < ntparms; ++i)
4858     {
4859       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
4860       tree targ = TREE_VEC_ELT (targs, i);
4861
4862       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
4863         {
4864           tree packed_args = NULL_TREE;
4865           int idx, len = 1;
4866
4867           if (ARGUMENT_PACK_P (targ))
4868             {
4869               /* Look inside the argument pack.  */
4870               packed_args = ARGUMENT_PACK_ARGS (targ);
4871               len = TREE_VEC_LENGTH (packed_args);
4872             }
4873
4874           for (idx = 0; idx < len; ++idx)
4875             {
4876               tree targ_parms = NULL_TREE;
4877
4878               if (packed_args)
4879                 /* Extract the next argument from the argument
4880                    pack.  */
4881                 targ = TREE_VEC_ELT (packed_args, idx);
4882
4883               if (PACK_EXPANSION_P (targ))
4884                 /* Look at the pattern of the pack expansion.  */
4885                 targ = PACK_EXPANSION_PATTERN (targ);
4886
4887               /* Extract the template parameters from the template
4888                  argument.  */
4889               if (TREE_CODE (targ) == TEMPLATE_DECL)
4890                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
4891               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
4892                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
4893
4894               /* Verify that we can coerce the template template
4895                  parameters from the template argument to the template
4896                  parameter.  This requires an exact match.  */
4897               if (targ_parms
4898                   && !coerce_template_template_parms
4899                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
4900                         targ_parms,
4901                         tf_none,
4902                         tparm,
4903                         targs))
4904                 {
4905                   ret = false;
4906                   goto out;
4907                 }
4908             }
4909         }
4910     }
4911
4912  out:
4913
4914   --processing_template_decl;
4915   return ret;
4916 }
4917
4918 /* Convert the indicated template ARG as necessary to match the
4919    indicated template PARM.  Returns the converted ARG, or
4920    error_mark_node if the conversion was unsuccessful.  Error and
4921    warning messages are issued under control of COMPLAIN.  This
4922    conversion is for the Ith parameter in the parameter list.  ARGS is
4923    the full set of template arguments deduced so far.  */
4924
4925 static tree
4926 convert_template_argument (tree parm,
4927                            tree arg,
4928                            tree args,
4929                            tsubst_flags_t complain,
4930                            int i,
4931                            tree in_decl)
4932 {
4933   tree orig_arg;
4934   tree val;
4935   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4936
4937   if (TREE_CODE (arg) == TREE_LIST
4938       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4939     {
4940       /* The template argument was the name of some
4941          member function.  That's usually
4942          invalid, but static members are OK.  In any
4943          case, grab the underlying fields/functions
4944          and issue an error later if required.  */
4945       orig_arg = TREE_VALUE (arg);
4946       TREE_TYPE (arg) = unknown_type_node;
4947     }
4948
4949   orig_arg = arg;
4950
4951   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4952   requires_type = (TREE_CODE (parm) == TYPE_DECL
4953                    || requires_tmpl_type);
4954
4955   /* When determining whether an argument pack expansion is a template,
4956      look at the pattern.  */
4957   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
4958     arg = PACK_EXPANSION_PATTERN (arg);
4959
4960   is_tmpl_type = 
4961     ((TREE_CODE (arg) == TEMPLATE_DECL
4962       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
4963      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4964      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
4965
4966   if (is_tmpl_type
4967       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4968           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4969     arg = TYPE_STUB_DECL (arg);
4970
4971   is_type = TYPE_P (arg) || is_tmpl_type;
4972
4973   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4974       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4975     {
4976       permerror (input_location, "to refer to a type member of a template parameter, "
4977                  "use %<typename %E%>", orig_arg);
4978
4979       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
4980                                      TREE_OPERAND (arg, 1),
4981                                      typename_type,
4982                                      complain & tf_error);
4983       arg = orig_arg;
4984       is_type = 1;
4985     }
4986   if (is_type != requires_type)
4987     {
4988       if (in_decl)
4989         {
4990           if (complain & tf_error)
4991             {
4992               error ("type/value mismatch at argument %d in template "
4993                      "parameter list for %qD",
4994                      i + 1, in_decl);
4995               if (is_type)
4996                 error ("  expected a constant of type %qT, got %qT",
4997                        TREE_TYPE (parm),
4998                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
4999               else if (requires_tmpl_type)
5000                 error ("  expected a class template, got %qE", orig_arg);
5001               else
5002                 error ("  expected a type, got %qE", orig_arg);
5003             }
5004         }
5005       return error_mark_node;
5006     }
5007   if (is_tmpl_type ^ requires_tmpl_type)
5008     {
5009       if (in_decl && (complain & tf_error))
5010         {
5011           error ("type/value mismatch at argument %d in template "
5012                  "parameter list for %qD",
5013                  i + 1, in_decl);
5014           if (is_tmpl_type)
5015             error ("  expected a type, got %qT", DECL_NAME (arg));
5016           else
5017             error ("  expected a class template, got %qT", orig_arg);
5018         }
5019       return error_mark_node;
5020     }
5021
5022   if (is_type)
5023     {
5024       if (requires_tmpl_type)
5025         {
5026           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5027             /* The number of argument required is not known yet.
5028                Just accept it for now.  */
5029             val = TREE_TYPE (arg);
5030           else
5031             {
5032               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5033               tree argparm;
5034
5035               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5036
5037               if (coerce_template_template_parms (parmparm, argparm,
5038                                                   complain, in_decl,
5039                                                   args))
5040                 {
5041                   val = orig_arg;
5042
5043                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5044                      TEMPLATE_DECL.  */
5045                   if (val != error_mark_node)
5046                     {
5047                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5048                         val = TREE_TYPE (val);
5049                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5050                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5051                         {
5052                           val = TREE_TYPE (arg);
5053                           val = make_pack_expansion (val);
5054                         }
5055                     }
5056                 }
5057               else
5058                 {
5059                   if (in_decl && (complain & tf_error))
5060                     {
5061                       error ("type/value mismatch at argument %d in "
5062                              "template parameter list for %qD",
5063                              i + 1, in_decl);
5064                       error ("  expected a template of type %qD, got %qD",
5065                              parm, orig_arg);
5066                     }
5067
5068                   val = error_mark_node;
5069                 }
5070             }
5071         }
5072       else
5073         val = orig_arg;
5074       /* We only form one instance of each template specialization.
5075          Therefore, if we use a non-canonical variant (i.e., a
5076          typedef), any future messages referring to the type will use
5077          the typedef, which is confusing if those future uses do not
5078          themselves also use the typedef.  */
5079       if (TYPE_P (val))
5080         val = canonical_type_variant (val);
5081     }
5082   else
5083     {
5084       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5085
5086       if (invalid_nontype_parm_type_p (t, complain))
5087         return error_mark_node;
5088
5089       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5090         {
5091           if (same_type_p (t, TREE_TYPE (orig_arg)))
5092             val = orig_arg;
5093           else
5094             {
5095               /* Not sure if this is reachable, but it doesn't hurt
5096                  to be robust.  */
5097               error ("type mismatch in nontype parameter pack");
5098               val = error_mark_node;
5099             }
5100         }
5101       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5102         /* We used to call digest_init here.  However, digest_init
5103            will report errors, which we don't want when complain
5104            is zero.  More importantly, digest_init will try too
5105            hard to convert things: for example, `0' should not be
5106            converted to pointer type at this point according to
5107            the standard.  Accepting this is not merely an
5108            extension, since deciding whether or not these
5109            conversions can occur is part of determining which
5110            function template to call, or whether a given explicit
5111            argument specification is valid.  */
5112         val = convert_nontype_argument (t, orig_arg);
5113       else
5114         val = orig_arg;
5115
5116       if (val == NULL_TREE)
5117         val = error_mark_node;
5118       else if (val == error_mark_node && (complain & tf_error))
5119         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5120     }
5121
5122   return val;
5123 }
5124
5125 /* Coerces the remaining template arguments in INNER_ARGS (from
5126    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5127    Returns the coerced argument pack. PARM_IDX is the position of this
5128    parameter in the template parameter list. ARGS is the original
5129    template argument list.  */
5130 static tree
5131 coerce_template_parameter_pack (tree parms,
5132                                 int parm_idx,
5133                                 tree args,
5134                                 tree inner_args,
5135                                 int arg_idx,
5136                                 tree new_args,
5137                                 int* lost,
5138                                 tree in_decl,
5139                                 tsubst_flags_t complain)
5140 {
5141   tree parm = TREE_VEC_ELT (parms, parm_idx);
5142   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5143   tree packed_args;
5144   tree argument_pack;
5145   tree packed_types = NULL_TREE;
5146
5147   if (arg_idx > nargs)
5148     arg_idx = nargs;
5149
5150   packed_args = make_tree_vec (nargs - arg_idx);
5151
5152   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5153       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5154     {
5155       /* When the template parameter is a non-type template
5156          parameter pack whose type uses parameter packs, we need
5157          to look at each of the template arguments
5158          separately. Build a vector of the types for these
5159          non-type template parameters in PACKED_TYPES.  */
5160       tree expansion 
5161         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5162       packed_types = tsubst_pack_expansion (expansion, args,
5163                                             complain, in_decl);
5164
5165       if (packed_types == error_mark_node)
5166         return error_mark_node;
5167
5168       /* Check that we have the right number of arguments.  */
5169       if (arg_idx < nargs
5170           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5171           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5172         {
5173           int needed_parms 
5174             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5175           error ("wrong number of template arguments (%d, should be %d)",
5176                  nargs, needed_parms);
5177           return error_mark_node;
5178         }
5179
5180       /* If we aren't able to check the actual arguments now
5181          (because they haven't been expanded yet), we can at least
5182          verify that all of the types used for the non-type
5183          template parameter pack are, in fact, valid for non-type
5184          template parameters.  */
5185       if (arg_idx < nargs 
5186           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5187         {
5188           int j, len = TREE_VEC_LENGTH (packed_types);
5189           for (j = 0; j < len; ++j)
5190             {
5191               tree t = TREE_VEC_ELT (packed_types, j);
5192               if (invalid_nontype_parm_type_p (t, complain))
5193                 return error_mark_node;
5194             }
5195         }
5196     }
5197
5198   /* Convert the remaining arguments, which will be a part of the
5199      parameter pack "parm".  */
5200   for (; arg_idx < nargs; ++arg_idx)
5201     {
5202       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5203       tree actual_parm = TREE_VALUE (parm);
5204
5205       if (packed_types && !PACK_EXPANSION_P (arg))
5206         {
5207           /* When we have a vector of types (corresponding to the
5208              non-type template parameter pack that uses parameter
5209              packs in its type, as mention above), and the
5210              argument is not an expansion (which expands to a
5211              currently unknown number of arguments), clone the
5212              parm and give it the next type in PACKED_TYPES.  */
5213           actual_parm = copy_node (actual_parm);
5214           TREE_TYPE (actual_parm) = 
5215             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5216         }
5217
5218       if (arg != error_mark_node)
5219         arg = convert_template_argument (actual_parm, 
5220                                          arg, new_args, complain, parm_idx,
5221                                          in_decl);
5222       if (arg == error_mark_node)
5223         (*lost)++;
5224       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5225     }
5226
5227   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5228       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5229     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5230   else
5231     {
5232       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5233       TREE_TYPE (argument_pack) 
5234         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5235       TREE_CONSTANT (argument_pack) = 1;
5236     }
5237
5238   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5239   return argument_pack;
5240 }
5241
5242 /* Convert all template arguments to their appropriate types, and
5243    return a vector containing the innermost resulting template
5244    arguments.  If any error occurs, return error_mark_node. Error and
5245    warning messages are issued under control of COMPLAIN.
5246
5247    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5248    for arguments not specified in ARGS.  Otherwise, if
5249    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5250    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5251    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5252    ARGS.  */
5253
5254 static tree
5255 coerce_template_parms (tree parms,
5256                        tree args,
5257                        tree in_decl,
5258                        tsubst_flags_t complain,
5259                        bool require_all_args,
5260                        bool use_default_args)
5261 {
5262   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5263   tree inner_args;
5264   tree new_args;
5265   tree new_inner_args;
5266   bool saved_skip_evaluation;
5267
5268   /* When used as a boolean value, indicates whether this is a
5269      variadic template parameter list. Since it's an int, we can also
5270      subtract it from nparms to get the number of non-variadic
5271      parameters.  */
5272   int variadic_p = 0;
5273
5274   nparms = TREE_VEC_LENGTH (parms);
5275
5276   /* Determine if there are any parameter packs.  */
5277   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5278     {
5279       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5280       if (template_parameter_pack_p (tparm))
5281         ++variadic_p;
5282     }
5283
5284   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5285   /* If there are 0 or 1 parameter packs, we need to expand any argument
5286      packs so that we can deduce a parameter pack from some non-packed args
5287      followed by an argument pack, as in variadic85.C.  If there are more
5288      than that, we need to leave argument packs intact so the arguments are
5289      assigned to the right parameter packs.  This should only happen when
5290      dealing with a nested class inside a partial specialization of a class
5291      template, as in variadic92.C.  */
5292   if (variadic_p <= 1)
5293     inner_args = expand_template_argument_pack (inner_args);
5294
5295   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5296   if ((nargs > nparms && !variadic_p)
5297       || (nargs < nparms - variadic_p
5298           && require_all_args
5299           && (!use_default_args
5300               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5301                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5302     {
5303       if (complain & tf_error)
5304         {
5305           const char *or_more = "";
5306           if (variadic_p)
5307             {
5308               or_more = " or more";
5309               --nparms;
5310             }
5311
5312           error ("wrong number of template arguments (%d, should be %d%s)",
5313                  nargs, nparms, or_more);
5314
5315           if (in_decl)
5316             error ("provided for %q+D", in_decl);
5317         }
5318
5319       return error_mark_node;
5320     }
5321
5322   /* We need to evaluate the template arguments, even though this
5323      template-id may be nested within a "sizeof".  */
5324   saved_skip_evaluation = skip_evaluation;
5325   skip_evaluation = false;
5326   new_inner_args = make_tree_vec (nparms);
5327   new_args = add_outermost_template_args (args, new_inner_args);
5328   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5329     {
5330       tree arg;
5331       tree parm;
5332
5333       /* Get the Ith template parameter.  */
5334       parm = TREE_VEC_ELT (parms, parm_idx);
5335  
5336       if (parm == error_mark_node)
5337       {
5338         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5339         continue;
5340       }
5341
5342       /* Calculate the next argument.  */
5343       if (arg_idx < nargs)
5344         arg = TREE_VEC_ELT (inner_args, arg_idx);
5345       else
5346         arg = NULL_TREE;
5347
5348       if (template_parameter_pack_p (TREE_VALUE (parm))
5349           && !(arg && ARGUMENT_PACK_P (arg)))
5350         {
5351           /* All remaining arguments will be placed in the
5352              template parameter pack PARM.  */
5353           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5354                                                 inner_args, arg_idx,
5355                                                 new_args, &lost,
5356                                                 in_decl, complain);
5357
5358           /* Store this argument.  */
5359           if (arg == error_mark_node)
5360             lost++;
5361           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5362
5363           /* We are done with all of the arguments.  */
5364           arg_idx = nargs;
5365           
5366           continue;
5367         }
5368       else if (arg)
5369         {
5370           if (PACK_EXPANSION_P (arg))
5371             {
5372               if (complain & tf_error)
5373                 {
5374                   /* FIXME this restriction was removed by N2555; see
5375                      bug 35722.  */
5376                   /* If ARG is a pack expansion, but PARM is not a
5377                      template parameter pack (if it were, we would have
5378                      handled it above), we're trying to expand into a
5379                      fixed-length argument list.  */
5380                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5381                     sorry ("cannot expand %<%E%> into a fixed-length "
5382                            "argument list", arg);
5383                   else
5384                     sorry ("cannot expand %<%T%> into a fixed-length "
5385                            "argument list", arg);
5386                 }
5387               return error_mark_node;
5388             }
5389         }
5390       else if (require_all_args)
5391         /* There must be a default arg in this case.  */
5392         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5393                                    complain, in_decl);
5394       else
5395         break;
5396
5397       if (arg == error_mark_node)
5398         {
5399           if (complain & tf_error)
5400             error ("template argument %d is invalid", arg_idx + 1);
5401         }
5402       else if (!arg)
5403         /* This only occurs if there was an error in the template
5404            parameter list itself (which we would already have
5405            reported) that we are trying to recover from, e.g., a class
5406            template with a parameter list such as
5407            template<typename..., typename>.  */
5408         return error_mark_node;
5409       else
5410         arg = convert_template_argument (TREE_VALUE (parm),
5411                                          arg, new_args, complain, 
5412                                          parm_idx, in_decl);
5413
5414       if (arg == error_mark_node)
5415         lost++;
5416       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5417     }
5418   skip_evaluation = saved_skip_evaluation;
5419
5420   if (lost)
5421     return error_mark_node;
5422
5423   return new_inner_args;
5424 }
5425
5426 /* Returns 1 if template args OT and NT are equivalent.  */
5427
5428 static int
5429 template_args_equal (tree ot, tree nt)
5430 {
5431   if (nt == ot)
5432     return 1;
5433
5434   if (TREE_CODE (nt) == TREE_VEC)
5435     /* For member templates */
5436     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5437   else if (PACK_EXPANSION_P (ot))
5438     return PACK_EXPANSION_P (nt) 
5439       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5440                               PACK_EXPANSION_PATTERN (nt));
5441   else if (ARGUMENT_PACK_P (ot))
5442     {
5443       int i, len;
5444       tree opack, npack;
5445
5446       if (!ARGUMENT_PACK_P (nt))
5447         return 0;
5448
5449       opack = ARGUMENT_PACK_ARGS (ot);
5450       npack = ARGUMENT_PACK_ARGS (nt);
5451       len = TREE_VEC_LENGTH (opack);
5452       if (TREE_VEC_LENGTH (npack) != len)
5453         return 0;
5454       for (i = 0; i < len; ++i)
5455         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5456                                   TREE_VEC_ELT (npack, i)))
5457           return 0;
5458       return 1;
5459     }
5460   else if (TYPE_P (nt))
5461     return TYPE_P (ot) && same_type_p (ot, nt);
5462   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5463     return 0;
5464   else
5465     return cp_tree_equal (ot, nt);
5466 }
5467
5468 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5469    of template arguments.  Returns 0 otherwise.  */
5470
5471 int
5472 comp_template_args (tree oldargs, tree newargs)
5473 {
5474   int i;
5475
5476   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5477     return 0;
5478
5479   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5480     {
5481       tree nt = TREE_VEC_ELT (newargs, i);
5482       tree ot = TREE_VEC_ELT (oldargs, i);
5483
5484       if (! template_args_equal (ot, nt))
5485         return 0;
5486     }
5487   return 1;
5488 }
5489
5490 static void
5491 add_pending_template (tree d)
5492 {
5493   tree ti = (TYPE_P (d)
5494              ? CLASSTYPE_TEMPLATE_INFO (d)
5495              : DECL_TEMPLATE_INFO (d));
5496   struct pending_template *pt;
5497   int level;
5498
5499   if (TI_PENDING_TEMPLATE_FLAG (ti))
5500     return;
5501
5502   /* We are called both from instantiate_decl, where we've already had a
5503      tinst_level pushed, and instantiate_template, where we haven't.
5504      Compensate.  */
5505   level = !current_tinst_level || current_tinst_level->decl != d;
5506
5507   if (level)
5508     push_tinst_level (d);
5509
5510   pt = GGC_NEW (struct pending_template);
5511   pt->next = NULL;
5512   pt->tinst = current_tinst_level;
5513   if (last_pending_template)
5514     last_pending_template->next = pt;
5515   else
5516     pending_templates = pt;
5517
5518   last_pending_template = pt;
5519
5520   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5521
5522   if (level)
5523     pop_tinst_level ();
5524 }
5525
5526
5527 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5528    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5529    documentation for TEMPLATE_ID_EXPR.  */
5530
5531 tree
5532 lookup_template_function (tree fns, tree arglist)
5533 {
5534   tree type;
5535
5536   if (fns == error_mark_node || arglist == error_mark_node)
5537     return error_mark_node;
5538
5539   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5540   gcc_assert (fns && (is_overloaded_fn (fns)
5541                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5542
5543   if (BASELINK_P (fns))
5544     {
5545       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5546                                          unknown_type_node,
5547                                          BASELINK_FUNCTIONS (fns),
5548                                          arglist);
5549       return fns;
5550     }
5551
5552   type = TREE_TYPE (fns);
5553   if (TREE_CODE (fns) == OVERLOAD || !type)
5554     type = unknown_type_node;
5555
5556   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5557 }
5558
5559 /* Within the scope of a template class S<T>, the name S gets bound
5560    (in build_self_reference) to a TYPE_DECL for the class, not a
5561    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5562    or one of its enclosing classes, and that type is a template,
5563    return the associated TEMPLATE_DECL.  Otherwise, the original
5564    DECL is returned.  */
5565
5566 tree
5567 maybe_get_template_decl_from_type_decl (tree decl)
5568 {
5569   return (decl != NULL_TREE
5570           && TREE_CODE (decl) == TYPE_DECL
5571           && DECL_ARTIFICIAL (decl)
5572           && CLASS_TYPE_P (TREE_TYPE (decl))
5573           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5574     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5575 }
5576
5577 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5578    parameters, find the desired type.
5579
5580    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5581
5582    IN_DECL, if non-NULL, is the template declaration we are trying to
5583    instantiate.
5584
5585    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5586    the class we are looking up.
5587
5588    Issue error and warning messages under control of COMPLAIN.
5589
5590    If the template class is really a local class in a template
5591    function, then the FUNCTION_CONTEXT is the function in which it is
5592    being instantiated.
5593
5594    ??? Note that this function is currently called *twice* for each
5595    template-id: the first time from the parser, while creating the
5596    incomplete type (finish_template_type), and the second type during the
5597    real instantiation (instantiate_template_class). This is surely something
5598    that we want to avoid. It also causes some problems with argument
5599    coercion (see convert_nontype_argument for more information on this).  */
5600
5601 tree
5602 lookup_template_class (tree d1,
5603                        tree arglist,
5604                        tree in_decl,
5605                        tree context,
5606                        int entering_scope,
5607                        tsubst_flags_t complain)
5608 {
5609   tree templ = NULL_TREE, parmlist;
5610   tree t;
5611
5612   timevar_push (TV_NAME_LOOKUP);
5613
5614   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5615     {
5616       tree value = innermost_non_namespace_value (d1);
5617       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5618         templ = value;
5619       else
5620         {
5621           if (context)
5622             push_decl_namespace (context);
5623           templ = lookup_name (d1);
5624           templ = maybe_get_template_decl_from_type_decl (templ);
5625           if (context)
5626             pop_decl_namespace ();
5627         }
5628       if (templ)
5629         context = DECL_CONTEXT (templ);
5630     }
5631   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
5632     {
5633       tree type = TREE_TYPE (d1);
5634
5635       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5636          an implicit typename for the second A.  Deal with it.  */
5637       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5638         type = TREE_TYPE (type);
5639
5640       if (CLASSTYPE_TEMPLATE_INFO (type))
5641         {
5642           templ = CLASSTYPE_TI_TEMPLATE (type);
5643           d1 = DECL_NAME (templ);
5644         }
5645     }
5646   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5647            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
5648     {
5649       templ = TYPE_TI_TEMPLATE (d1);
5650       d1 = DECL_NAME (templ);
5651     }
5652   else if (TREE_CODE (d1) == TEMPLATE_DECL
5653            && DECL_TEMPLATE_RESULT (d1)
5654            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5655     {
5656       templ = d1;
5657       d1 = DECL_NAME (templ);
5658       context = DECL_CONTEXT (templ);
5659     }
5660
5661   /* Issue an error message if we didn't find a template.  */
5662   if (! templ)
5663     {
5664       if (complain & tf_error)
5665         error ("%qT is not a template", d1);
5666       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5667     }
5668
5669   if (TREE_CODE (templ) != TEMPLATE_DECL
5670          /* Make sure it's a user visible template, if it was named by
5671             the user.  */
5672       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
5673           && !PRIMARY_TEMPLATE_P (templ)))
5674     {
5675       if (complain & tf_error)
5676         {
5677           error ("non-template type %qT used as a template", d1);
5678           if (in_decl)
5679             error ("for template declaration %q+D", in_decl);
5680         }
5681       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5682     }
5683
5684   complain &= ~tf_user;
5685
5686   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
5687     {
5688       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5689          template arguments */
5690
5691       tree parm;
5692       tree arglist2;
5693       tree outer;
5694
5695       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
5696
5697       /* Consider an example where a template template parameter declared as
5698
5699            template <class T, class U = std::allocator<T> > class TT
5700
5701          The template parameter level of T and U are one level larger than
5702          of TT.  To proper process the default argument of U, say when an
5703          instantiation `TT<int>' is seen, we need to build the full
5704          arguments containing {int} as the innermost level.  Outer levels,
5705          available when not appearing as default template argument, can be
5706          obtained from the arguments of the enclosing template.
5707
5708          Suppose that TT is later substituted with std::vector.  The above
5709          instantiation is `TT<int, std::allocator<T> >' with TT at
5710          level 1, and T at level 2, while the template arguments at level 1
5711          becomes {std::vector} and the inner level 2 is {int}.  */
5712
5713       outer = DECL_CONTEXT (templ);
5714       if (outer)
5715         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5716       else if (current_template_parms)
5717         /* This is an argument of the current template, so we haven't set
5718            DECL_CONTEXT yet.  */
5719         outer = current_template_args ();
5720
5721       if (outer)
5722         arglist = add_to_template_args (outer, arglist);
5723
5724       arglist2 = coerce_template_parms (parmlist, arglist, templ,
5725                                         complain,
5726                                         /*require_all_args=*/true,
5727                                         /*use_default_args=*/true);
5728       if (arglist2 == error_mark_node
5729           || (!uses_template_parms (arglist2)
5730               && check_instantiated_args (templ, arglist2, complain)))
5731         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5732
5733       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
5734       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5735     }
5736   else
5737     {
5738       tree template_type = TREE_TYPE (templ);
5739       tree gen_tmpl;
5740       tree type_decl;
5741       tree found = NULL_TREE;
5742       int arg_depth;
5743       int parm_depth;
5744       int is_partial_instantiation;
5745
5746       gen_tmpl = most_general_template (templ);
5747       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5748       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5749       arg_depth = TMPL_ARGS_DEPTH (arglist);
5750
5751       if (arg_depth == 1 && parm_depth > 1)
5752         {
5753           /* We've been given an incomplete set of template arguments.
5754              For example, given:
5755
5756                template <class T> struct S1 {
5757                  template <class U> struct S2 {};
5758                  template <class U> struct S2<U*> {};
5759                 };
5760
5761              we will be called with an ARGLIST of `U*', but the
5762              TEMPLATE will be `template <class T> template
5763              <class U> struct S1<T>::S2'.  We must fill in the missing
5764              arguments.  */
5765           arglist
5766             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
5767                                            arglist);
5768           arg_depth = TMPL_ARGS_DEPTH (arglist);
5769         }
5770
5771       /* Now we should have enough arguments.  */
5772       gcc_assert (parm_depth == arg_depth);
5773
5774       /* From here on, we're only interested in the most general
5775          template.  */
5776       templ = gen_tmpl;
5777
5778       /* Calculate the BOUND_ARGS.  These will be the args that are
5779          actually tsubst'd into the definition to create the
5780          instantiation.  */
5781       if (parm_depth > 1)
5782         {
5783           /* We have multiple levels of arguments to coerce, at once.  */
5784           int i;
5785           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5786
5787           tree bound_args = make_tree_vec (parm_depth);
5788
5789           for (i = saved_depth,
5790                  t = DECL_TEMPLATE_PARMS (templ);
5791                i > 0 && t != NULL_TREE;
5792                --i, t = TREE_CHAIN (t))
5793             {
5794               tree a = coerce_template_parms (TREE_VALUE (t),
5795                                               arglist, templ,
5796                                               complain,
5797                                               /*require_all_args=*/true,
5798                                               /*use_default_args=*/true);
5799
5800               /* Don't process further if one of the levels fails.  */
5801               if (a == error_mark_node)
5802                 {
5803                   /* Restore the ARGLIST to its full size.  */
5804                   TREE_VEC_LENGTH (arglist) = saved_depth;
5805                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5806                 }
5807
5808               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5809
5810               /* We temporarily reduce the length of the ARGLIST so
5811                  that coerce_template_parms will see only the arguments
5812                  corresponding to the template parameters it is
5813                  examining.  */
5814               TREE_VEC_LENGTH (arglist)--;
5815             }
5816
5817           /* Restore the ARGLIST to its full size.  */
5818           TREE_VEC_LENGTH (arglist) = saved_depth;
5819
5820           arglist = bound_args;
5821         }
5822       else
5823         arglist
5824           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5825                                    INNERMOST_TEMPLATE_ARGS (arglist),
5826                                    templ,
5827                                    complain,
5828                                    /*require_all_args=*/true,
5829                                    /*use_default_args=*/true);
5830
5831       if (arglist == error_mark_node)
5832         /* We were unable to bind the arguments.  */
5833         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5834
5835       /* In the scope of a template class, explicit references to the
5836          template class refer to the type of the template, not any
5837          instantiation of it.  For example, in:
5838
5839            template <class T> class C { void f(C<T>); }
5840
5841          the `C<T>' is just the same as `C'.  Outside of the
5842          class, however, such a reference is an instantiation.  */
5843       if (comp_template_args (TYPE_TI_ARGS (template_type),
5844                               arglist))
5845         {
5846           found = template_type;
5847
5848           if (!entering_scope && PRIMARY_TEMPLATE_P (templ))
5849             {
5850               tree ctx;
5851
5852               for (ctx = current_class_type;
5853                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5854                    ctx = (TYPE_P (ctx)
5855                           ? TYPE_CONTEXT (ctx)
5856                           : DECL_CONTEXT (ctx)))
5857                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5858                   goto found_ctx;
5859
5860               /* We're not in the scope of the class, so the
5861                  TEMPLATE_TYPE is not the type we want after all.  */
5862               found = NULL_TREE;
5863             found_ctx:;
5864             }
5865         }
5866       if (found)
5867         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5868
5869       /* If we already have this specialization, return it.  */
5870       found = retrieve_specialization (templ, arglist,
5871                                        /*class_specializations_p=*/false);
5872       if (found)
5873         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5874
5875       /* This type is a "partial instantiation" if any of the template
5876          arguments still involve template parameters.  Note that we set
5877          IS_PARTIAL_INSTANTIATION for partial specializations as
5878          well.  */
5879       is_partial_instantiation = uses_template_parms (arglist);
5880
5881       /* If the deduced arguments are invalid, then the binding
5882          failed.  */
5883       if (!is_partial_instantiation
5884           && check_instantiated_args (templ,
5885                                       INNERMOST_TEMPLATE_ARGS (arglist),
5886                                       complain))
5887         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5888
5889       if (!is_partial_instantiation
5890           && !PRIMARY_TEMPLATE_P (templ)
5891           && TREE_CODE (CP_DECL_CONTEXT (templ)) == NAMESPACE_DECL)
5892         {
5893           found = xref_tag_from_type (TREE_TYPE (templ),
5894                                       DECL_NAME (templ),
5895                                       /*tag_scope=*/ts_global);
5896           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5897         }
5898
5899       context = tsubst (DECL_CONTEXT (templ), arglist,
5900                         complain, in_decl);
5901       if (!context)
5902         context = global_namespace;
5903
5904       /* Create the type.  */
5905       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5906         {
5907           if (!is_partial_instantiation)
5908             {
5909               set_current_access_from_decl (TYPE_NAME (template_type));
5910               t = start_enum (TYPE_IDENTIFIER (template_type),
5911                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
5912                                       arglist, complain, in_decl),
5913                               SCOPED_ENUM_P (template_type));
5914             }
5915           else
5916             {
5917               /* We don't want to call start_enum for this type, since
5918                  the values for the enumeration constants may involve
5919                  template parameters.  And, no one should be interested
5920                  in the enumeration constants for such a type.  */
5921               t = make_node (ENUMERAL_TYPE);
5922               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
5923             }
5924         }
5925       else
5926         {
5927           t = make_class_type (TREE_CODE (template_type));
5928           CLASSTYPE_DECLARED_CLASS (t)
5929             = CLASSTYPE_DECLARED_CLASS (template_type);
5930           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5931           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5932
5933           /* A local class.  Make sure the decl gets registered properly.  */
5934           if (context == current_function_decl)
5935             pushtag (DECL_NAME (templ), t, /*tag_scope=*/ts_current);
5936
5937           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5938             /* This instantiation is another name for the primary
5939                template type. Set the TYPE_CANONICAL field
5940                appropriately. */
5941             TYPE_CANONICAL (t) = template_type;
5942           else if (any_template_arguments_need_structural_equality_p (arglist))
5943             /* Some of the template arguments require structural
5944                equality testing, so this template class requires
5945                structural equality testing. */
5946             SET_TYPE_STRUCTURAL_EQUALITY (t);
5947         }
5948
5949       /* If we called start_enum or pushtag above, this information
5950          will already be set up.  */
5951       if (!TYPE_NAME (t))
5952         {
5953           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5954
5955           type_decl = create_implicit_typedef (DECL_NAME (templ), t);
5956           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5957           TYPE_STUB_DECL (t) = type_decl;
5958           DECL_SOURCE_LOCATION (type_decl)
5959             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5960         }
5961       else
5962         type_decl = TYPE_NAME (t);
5963
5964       TREE_PRIVATE (type_decl)
5965         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5966       TREE_PROTECTED (type_decl)
5967         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5968       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5969         {
5970           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5971           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5972         }
5973
5974       /* Set up the template information.  We have to figure out which
5975          template is the immediate parent if this is a full
5976          instantiation.  */
5977       if (parm_depth == 1 || is_partial_instantiation
5978           || !PRIMARY_TEMPLATE_P (templ))
5979         /* This case is easy; there are no member templates involved.  */
5980         found = templ;
5981       else
5982         {
5983           /* This is a full instantiation of a member template.  Look
5984              for a partial instantiation of which this is an instance.  */
5985
5986           for (found = DECL_TEMPLATE_INSTANTIATIONS (templ);
5987                found; found = TREE_CHAIN (found))
5988             {
5989               int success;
5990               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5991
5992               /* We only want partial instantiations, here, not
5993                  specializations or full instantiations.  */
5994               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5995                   || !uses_template_parms (TREE_VALUE (found)))
5996                 continue;
5997
5998               /* Temporarily reduce by one the number of levels in the
5999                  ARGLIST and in FOUND so as to avoid comparing the
6000                  last set of arguments.  */
6001               TREE_VEC_LENGTH (arglist)--;
6002               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
6003
6004               /* See if the arguments match.  If they do, then TMPL is
6005                  the partial instantiation we want.  */
6006               success = comp_template_args (TREE_PURPOSE (found), arglist);
6007
6008               /* Restore the argument vectors to their full size.  */
6009               TREE_VEC_LENGTH (arglist)++;
6010               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
6011
6012               if (success)
6013                 {
6014                   found = tmpl;
6015                   break;
6016                 }
6017             }
6018
6019           if (!found)
6020             {
6021               /* There was no partial instantiation. This happens
6022                  where C<T> is a member template of A<T> and it's used
6023                  in something like
6024
6025                   template <typename T> struct B { A<T>::C<int> m; };
6026                   B<float>;
6027
6028                  Create the partial instantiation.
6029                */
6030               TREE_VEC_LENGTH (arglist)--;
6031               found = tsubst (templ, arglist, complain, NULL_TREE);
6032               TREE_VEC_LENGTH (arglist)++;
6033             }
6034         }
6035
6036       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6037       DECL_TEMPLATE_INSTANTIATIONS (templ)
6038         = tree_cons (arglist, t,
6039                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6040
6041       if (TREE_CODE (t) == ENUMERAL_TYPE
6042           && !is_partial_instantiation)
6043         /* Now that the type has been registered on the instantiations
6044            list, we set up the enumerators.  Because the enumeration
6045            constants may involve the enumeration type itself, we make
6046            sure to register the type first, and then create the
6047            constants.  That way, doing tsubst_expr for the enumeration
6048            constants won't result in recursive calls here; we'll find
6049            the instantiation and exit above.  */
6050         tsubst_enum (template_type, t, arglist);
6051
6052       if (is_partial_instantiation)
6053         /* If the type makes use of template parameters, the
6054            code that generates debugging information will crash.  */
6055         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6056
6057       /* Possibly limit visibility based on template args.  */
6058       TREE_PUBLIC (type_decl) = 1;
6059       determine_visibility (type_decl);
6060
6061       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6062     }
6063   timevar_pop (TV_NAME_LOOKUP);
6064 }
6065 \f
6066 struct pair_fn_data
6067 {
6068   tree_fn_t fn;
6069   void *data;
6070   /* True when we should also visit template parameters that occur in
6071      non-deduced contexts.  */
6072   bool include_nondeduced_p;
6073   struct pointer_set_t *visited;
6074 };
6075
6076 /* Called from for_each_template_parm via walk_tree.  */
6077
6078 static tree
6079 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6080 {
6081   tree t = *tp;
6082   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6083   tree_fn_t fn = pfd->fn;
6084   void *data = pfd->data;
6085
6086   if (TYPE_P (t)
6087       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6088       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6089                                  pfd->include_nondeduced_p))
6090     return error_mark_node;
6091
6092   switch (TREE_CODE (t))
6093     {
6094     case RECORD_TYPE:
6095       if (TYPE_PTRMEMFUNC_P (t))
6096         break;
6097       /* Fall through.  */
6098
6099     case UNION_TYPE:
6100     case ENUMERAL_TYPE:
6101       if (!TYPE_TEMPLATE_INFO (t))
6102         *walk_subtrees = 0;
6103       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6104                                        fn, data, pfd->visited, 
6105                                        pfd->include_nondeduced_p))
6106         return error_mark_node;
6107       break;
6108
6109     case INTEGER_TYPE:
6110       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6111                                   fn, data, pfd->visited, 
6112                                   pfd->include_nondeduced_p)
6113           || for_each_template_parm (TYPE_MAX_VALUE (t),
6114                                      fn, data, pfd->visited,
6115                                      pfd->include_nondeduced_p))
6116         return error_mark_node;
6117       break;
6118
6119     case METHOD_TYPE:
6120       /* Since we're not going to walk subtrees, we have to do this
6121          explicitly here.  */
6122       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6123                                   pfd->visited, pfd->include_nondeduced_p))
6124         return error_mark_node;
6125       /* Fall through.  */
6126
6127     case FUNCTION_TYPE:
6128       /* Check the return type.  */
6129       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6130                                   pfd->include_nondeduced_p))
6131         return error_mark_node;
6132
6133       /* Check the parameter types.  Since default arguments are not
6134          instantiated until they are needed, the TYPE_ARG_TYPES may
6135          contain expressions that involve template parameters.  But,
6136          no-one should be looking at them yet.  And, once they're
6137          instantiated, they don't contain template parameters, so
6138          there's no point in looking at them then, either.  */
6139       {
6140         tree parm;
6141
6142         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6143           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6144                                       pfd->visited, pfd->include_nondeduced_p))
6145             return error_mark_node;
6146
6147         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6148            want walk_tree walking into them itself.  */
6149         *walk_subtrees = 0;
6150       }
6151       break;
6152
6153     case TYPEOF_TYPE:
6154       if (pfd->include_nondeduced_p
6155           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6156                                      pfd->visited, 
6157                                      pfd->include_nondeduced_p))
6158         return error_mark_node;
6159       break;
6160
6161     case FUNCTION_DECL:
6162     case VAR_DECL:
6163       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6164           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6165                                      pfd->visited, pfd->include_nondeduced_p))
6166         return error_mark_node;
6167       /* Fall through.  */
6168
6169     case PARM_DECL:
6170     case CONST_DECL:
6171       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6172           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6173                                      pfd->visited, pfd->include_nondeduced_p))
6174         return error_mark_node;
6175       if (DECL_CONTEXT (t)
6176           && pfd->include_nondeduced_p
6177           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6178                                      pfd->visited, pfd->include_nondeduced_p))
6179         return error_mark_node;
6180       break;
6181
6182     case BOUND_TEMPLATE_TEMPLATE_PARM:
6183       /* Record template parameters such as `T' inside `TT<T>'.  */
6184       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6185                                   pfd->include_nondeduced_p))
6186         return error_mark_node;
6187       /* Fall through.  */
6188
6189     case TEMPLATE_TEMPLATE_PARM:
6190     case TEMPLATE_TYPE_PARM:
6191     case TEMPLATE_PARM_INDEX:
6192       if (fn && (*fn)(t, data))
6193         return error_mark_node;
6194       else if (!fn)
6195         return error_mark_node;
6196       break;
6197
6198     case TEMPLATE_DECL:
6199       /* A template template parameter is encountered.  */
6200       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6201           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6202                                      pfd->include_nondeduced_p))
6203         return error_mark_node;
6204
6205       /* Already substituted template template parameter */
6206       *walk_subtrees = 0;
6207       break;
6208
6209     case TYPENAME_TYPE:
6210       if (!fn
6211           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6212                                      data, pfd->visited, 
6213                                      pfd->include_nondeduced_p))
6214         return error_mark_node;
6215       break;
6216
6217     case CONSTRUCTOR:
6218       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6219           && pfd->include_nondeduced_p
6220           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6221                                      (TREE_TYPE (t)), fn, data,
6222                                      pfd->visited, pfd->include_nondeduced_p))
6223         return error_mark_node;
6224       break;
6225
6226     case INDIRECT_REF:
6227     case COMPONENT_REF:
6228       /* If there's no type, then this thing must be some expression
6229          involving template parameters.  */
6230       if (!fn && !TREE_TYPE (t))
6231         return error_mark_node;
6232       break;
6233
6234     case MODOP_EXPR:
6235     case CAST_EXPR:
6236     case REINTERPRET_CAST_EXPR:
6237     case CONST_CAST_EXPR:
6238     case STATIC_CAST_EXPR:
6239     case DYNAMIC_CAST_EXPR:
6240     case ARROW_EXPR:
6241     case DOTSTAR_EXPR:
6242     case TYPEID_EXPR:
6243     case PSEUDO_DTOR_EXPR:
6244       if (!fn)
6245         return error_mark_node;
6246       break;
6247
6248     default:
6249       break;
6250     }
6251
6252   /* We didn't find any template parameters we liked.  */
6253   return NULL_TREE;
6254 }
6255
6256 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6257    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6258    call FN with the parameter and the DATA.
6259    If FN returns nonzero, the iteration is terminated, and
6260    for_each_template_parm returns 1.  Otherwise, the iteration
6261    continues.  If FN never returns a nonzero value, the value
6262    returned by for_each_template_parm is 0.  If FN is NULL, it is
6263    considered to be the function which always returns 1.
6264
6265    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6266    parameters that occur in non-deduced contexts.  When false, only
6267    visits those template parameters that can be deduced.  */
6268
6269 static int
6270 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6271                         struct pointer_set_t *visited,
6272                         bool include_nondeduced_p)
6273 {
6274   struct pair_fn_data pfd;
6275   int result;
6276
6277   /* Set up.  */
6278   pfd.fn = fn;
6279   pfd.data = data;
6280   pfd.include_nondeduced_p = include_nondeduced_p;
6281
6282   /* Walk the tree.  (Conceptually, we would like to walk without
6283      duplicates, but for_each_template_parm_r recursively calls
6284      for_each_template_parm, so we would need to reorganize a fair
6285      bit to use walk_tree_without_duplicates, so we keep our own
6286      visited list.)  */
6287   if (visited)
6288     pfd.visited = visited;
6289   else
6290     pfd.visited = pointer_set_create ();
6291   result = cp_walk_tree (&t,
6292                          for_each_template_parm_r,
6293                          &pfd,
6294                          pfd.visited) != NULL_TREE;
6295
6296   /* Clean up.  */
6297   if (!visited)
6298     {
6299       pointer_set_destroy (pfd.visited);
6300       pfd.visited = 0;
6301     }
6302
6303   return result;
6304 }
6305
6306 /* Returns true if T depends on any template parameter.  */
6307
6308 int
6309 uses_template_parms (tree t)
6310 {
6311   bool dependent_p;
6312   int saved_processing_template_decl;
6313
6314   saved_processing_template_decl = processing_template_decl;
6315   if (!saved_processing_template_decl)
6316     processing_template_decl = 1;
6317   if (TYPE_P (t))
6318     dependent_p = dependent_type_p (t);
6319   else if (TREE_CODE (t) == TREE_VEC)
6320     dependent_p = any_dependent_template_arguments_p (t);
6321   else if (TREE_CODE (t) == TREE_LIST)
6322     dependent_p = (uses_template_parms (TREE_VALUE (t))
6323                    || uses_template_parms (TREE_CHAIN (t)));
6324   else if (TREE_CODE (t) == TYPE_DECL)
6325     dependent_p = dependent_type_p (TREE_TYPE (t));
6326   else if (DECL_P (t)
6327            || EXPR_P (t)
6328            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6329            || TREE_CODE (t) == OVERLOAD
6330            || TREE_CODE (t) == BASELINK
6331            || TREE_CODE (t) == IDENTIFIER_NODE
6332            || TREE_CODE (t) == TRAIT_EXPR
6333            || TREE_CODE (t) == CONSTRUCTOR
6334            || CONSTANT_CLASS_P (t))
6335     dependent_p = (type_dependent_expression_p (t)
6336                    || value_dependent_expression_p (t));
6337   else
6338     {
6339       gcc_assert (t == error_mark_node);
6340       dependent_p = false;
6341     }
6342
6343   processing_template_decl = saved_processing_template_decl;
6344
6345   return dependent_p;
6346 }
6347
6348 /* Returns true if T depends on any template parameter with level LEVEL.  */
6349
6350 int
6351 uses_template_parms_level (tree t, int level)
6352 {
6353   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6354                                  /*include_nondeduced_p=*/true);
6355 }
6356
6357 static int tinst_depth;
6358 extern int max_tinst_depth;
6359 #ifdef GATHER_STATISTICS
6360 int depth_reached;
6361 #endif
6362 static int tinst_level_tick;
6363 static int last_template_error_tick;
6364
6365 /* We're starting to instantiate D; record the template instantiation context
6366    for diagnostics and to restore it later.  */
6367
6368 static int
6369 push_tinst_level (tree d)
6370 {
6371   struct tinst_level *new_level;
6372
6373   if (tinst_depth >= max_tinst_depth)
6374     {
6375       /* If the instantiation in question still has unbound template parms,
6376          we don't really care if we can't instantiate it, so just return.
6377          This happens with base instantiation for implicit `typename'.  */
6378       if (uses_template_parms (d))
6379         return 0;
6380
6381       last_template_error_tick = tinst_level_tick;
6382       error ("template instantiation depth exceeds maximum of %d (use "
6383              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6384              max_tinst_depth, d);
6385
6386       print_instantiation_context ();
6387
6388       return 0;
6389     }
6390
6391   new_level = GGC_NEW (struct tinst_level);
6392   new_level->decl = d;
6393   new_level->locus = input_location;
6394   new_level->in_system_header_p = in_system_header;
6395   new_level->next = current_tinst_level;
6396   current_tinst_level = new_level;
6397
6398   ++tinst_depth;
6399 #ifdef GATHER_STATISTICS
6400   if (tinst_depth > depth_reached)
6401     depth_reached = tinst_depth;
6402 #endif
6403
6404   ++tinst_level_tick;
6405   return 1;
6406 }
6407
6408 /* We're done instantiating this template; return to the instantiation
6409    context.  */
6410
6411 static void
6412 pop_tinst_level (void)
6413 {
6414   /* Restore the filename and line number stashed away when we started
6415      this instantiation.  */
6416   input_location = current_tinst_level->locus;
6417   current_tinst_level = current_tinst_level->next;
6418   --tinst_depth;
6419   ++tinst_level_tick;
6420 }
6421
6422 /* We're instantiating a deferred template; restore the template
6423    instantiation context in which the instantiation was requested, which
6424    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6425
6426 static tree
6427 reopen_tinst_level (struct tinst_level *level)
6428 {
6429   struct tinst_level *t;
6430
6431   tinst_depth = 0;
6432   for (t = level; t; t = t->next)
6433     ++tinst_depth;
6434
6435   current_tinst_level = level;
6436   pop_tinst_level ();
6437   return level->decl;
6438 }
6439
6440 /* Returns the TINST_LEVEL which gives the original instantiation
6441    context.  */
6442
6443 struct tinst_level *
6444 outermost_tinst_level (void)
6445 {
6446   struct tinst_level *level = current_tinst_level;
6447   if (level)
6448     while (level->next)
6449       level = level->next;
6450   return level;
6451 }
6452
6453 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6454
6455 bool
6456 parameter_of_template_p (tree parm, tree templ)
6457 {
6458   tree parms;
6459   int i;
6460
6461   if (!parm || !templ)
6462     return false;
6463
6464   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6465   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6466
6467   parms = DECL_TEMPLATE_PARMS (templ);
6468   parms = INNERMOST_TEMPLATE_PARMS (parms);
6469
6470   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6471     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6472       return true;
6473
6474   return false;
6475 }
6476
6477 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6478    vector of template arguments, as for tsubst.
6479
6480    Returns an appropriate tsubst'd friend declaration.  */
6481
6482 static tree
6483 tsubst_friend_function (tree decl, tree args)
6484 {
6485   tree new_friend;
6486
6487   if (TREE_CODE (decl) == FUNCTION_DECL
6488       && DECL_TEMPLATE_INSTANTIATION (decl)
6489       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6490     /* This was a friend declared with an explicit template
6491        argument list, e.g.:
6492
6493        friend void f<>(T);
6494
6495        to indicate that f was a template instantiation, not a new
6496        function declaration.  Now, we have to figure out what
6497        instantiation of what template.  */
6498     {
6499       tree template_id, arglist, fns;
6500       tree new_args;
6501       tree tmpl;
6502       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6503
6504       /* Friend functions are looked up in the containing namespace scope.
6505          We must enter that scope, to avoid finding member functions of the
6506          current class with same name.  */
6507       push_nested_namespace (ns);
6508       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6509                          tf_warning_or_error, NULL_TREE,
6510                          /*integral_constant_expression_p=*/false);
6511       pop_nested_namespace (ns);
6512       arglist = tsubst (DECL_TI_ARGS (decl), args,
6513                         tf_warning_or_error, NULL_TREE);
6514       template_id = lookup_template_function (fns, arglist);
6515
6516       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6517       tmpl = determine_specialization (template_id, new_friend,
6518                                        &new_args,
6519                                        /*need_member_template=*/0,
6520                                        TREE_VEC_LENGTH (args),
6521                                        tsk_none);
6522       return instantiate_template (tmpl, new_args, tf_error);
6523     }
6524
6525   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6526
6527   /* The NEW_FRIEND will look like an instantiation, to the
6528      compiler, but is not an instantiation from the point of view of
6529      the language.  For example, we might have had:
6530
6531      template <class T> struct S {
6532        template <class U> friend void f(T, U);
6533      };
6534
6535      Then, in S<int>, template <class U> void f(int, U) is not an
6536      instantiation of anything.  */
6537   if (new_friend == error_mark_node)
6538     return error_mark_node;
6539
6540   DECL_USE_TEMPLATE (new_friend) = 0;
6541   if (TREE_CODE (decl) == TEMPLATE_DECL)
6542     {
6543       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6544       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6545         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6546     }
6547
6548   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6549      is not a template instantiation and should not be mangled like
6550      one.  Therefore, we forget the mangling here; we'll recompute it
6551      later if we need it.  */
6552   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6553     {
6554       SET_DECL_RTL (new_friend, NULL_RTX);
6555       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6556     }
6557
6558   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6559     {
6560       tree old_decl;
6561       tree new_friend_template_info;
6562       tree new_friend_result_template_info;
6563       tree ns;
6564       int  new_friend_is_defn;
6565
6566       /* We must save some information from NEW_FRIEND before calling
6567          duplicate decls since that function will free NEW_FRIEND if
6568          possible.  */
6569       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6570       new_friend_is_defn =
6571             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6572                            (template_for_substitution (new_friend)))
6573              != NULL_TREE);
6574       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6575         {
6576           /* This declaration is a `primary' template.  */
6577           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6578
6579           new_friend_result_template_info
6580             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6581         }
6582       else
6583         new_friend_result_template_info = NULL_TREE;
6584
6585       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6586       if (new_friend_is_defn)
6587         DECL_INITIAL (new_friend) = error_mark_node;
6588
6589       /* Inside pushdecl_namespace_level, we will push into the
6590          current namespace. However, the friend function should go
6591          into the namespace of the template.  */
6592       ns = decl_namespace_context (new_friend);
6593       push_nested_namespace (ns);
6594       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6595       pop_nested_namespace (ns);
6596
6597       if (old_decl == error_mark_node)
6598         return error_mark_node;
6599
6600       if (old_decl != new_friend)
6601         {
6602           /* This new friend declaration matched an existing
6603              declaration.  For example, given:
6604
6605                template <class T> void f(T);
6606                template <class U> class C {
6607                  template <class T> friend void f(T) {}
6608                };
6609
6610              the friend declaration actually provides the definition
6611              of `f', once C has been instantiated for some type.  So,
6612              old_decl will be the out-of-class template declaration,
6613              while new_friend is the in-class definition.
6614
6615              But, if `f' was called before this point, the
6616              instantiation of `f' will have DECL_TI_ARGS corresponding
6617              to `T' but not to `U', references to which might appear
6618              in the definition of `f'.  Previously, the most general
6619              template for an instantiation of `f' was the out-of-class
6620              version; now it is the in-class version.  Therefore, we
6621              run through all specialization of `f', adding to their
6622              DECL_TI_ARGS appropriately.  In particular, they need a
6623              new set of outer arguments, corresponding to the
6624              arguments for this class instantiation.
6625
6626              The same situation can arise with something like this:
6627
6628                friend void f(int);
6629                template <class T> class C {
6630                  friend void f(T) {}
6631                };
6632
6633              when `C<int>' is instantiated.  Now, `f(int)' is defined
6634              in the class.  */
6635
6636           if (!new_friend_is_defn)
6637             /* On the other hand, if the in-class declaration does
6638                *not* provide a definition, then we don't want to alter
6639                existing definitions.  We can just leave everything
6640                alone.  */
6641             ;
6642           else
6643             {
6644               /* Overwrite whatever template info was there before, if
6645                  any, with the new template information pertaining to
6646                  the declaration.  */
6647               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6648
6649               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6650                 reregister_specialization (new_friend,
6651                                            most_general_template (old_decl),
6652                                            old_decl);
6653               else
6654                 {
6655                   tree t;
6656                   tree new_friend_args;
6657
6658                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6659                     = new_friend_result_template_info;
6660
6661                   new_friend_args = TI_ARGS (new_friend_template_info);
6662                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6663                        t != NULL_TREE;
6664                        t = TREE_CHAIN (t))
6665                     {
6666                       tree spec = TREE_VALUE (t);
6667
6668                       DECL_TI_ARGS (spec)
6669                         = add_outermost_template_args (new_friend_args,
6670                                                        DECL_TI_ARGS (spec));
6671                     }
6672
6673                   /* Now, since specializations are always supposed to
6674                      hang off of the most general template, we must move
6675                      them.  */
6676                   t = most_general_template (old_decl);
6677                   if (t != old_decl)
6678                     {
6679                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6680                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6681                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6682                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6683                     }
6684                 }
6685             }
6686
6687           /* The information from NEW_FRIEND has been merged into OLD_DECL
6688              by duplicate_decls.  */
6689           new_friend = old_decl;
6690         }
6691     }
6692   else
6693     {
6694       tree context = DECL_CONTEXT (new_friend);
6695       bool dependent_p;
6696
6697       /* In the code
6698            template <class T> class C {
6699              template <class U> friend void C1<U>::f (); // case 1
6700              friend void C2<T>::f ();                    // case 2
6701            };
6702          we only need to make sure CONTEXT is a complete type for
6703          case 2.  To distinguish between the two cases, we note that
6704          CONTEXT of case 1 remains dependent type after tsubst while
6705          this isn't true for case 2.  */
6706       ++processing_template_decl;
6707       dependent_p = dependent_type_p (context);
6708       --processing_template_decl;
6709
6710       if (!dependent_p
6711           && !complete_type_or_else (context, NULL_TREE))
6712         return error_mark_node;
6713
6714       if (COMPLETE_TYPE_P (context))
6715         {
6716           /* Check to see that the declaration is really present, and,
6717              possibly obtain an improved declaration.  */
6718           tree fn = check_classfn (context,
6719                                    new_friend, NULL_TREE);
6720
6721           if (fn)
6722             new_friend = fn;
6723         }
6724     }
6725
6726   return new_friend;
6727 }
6728
6729 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6730    template arguments, as for tsubst.
6731
6732    Returns an appropriate tsubst'd friend type or error_mark_node on
6733    failure.  */
6734
6735 static tree
6736 tsubst_friend_class (tree friend_tmpl, tree args)
6737 {
6738   tree friend_type;
6739   tree tmpl;
6740   tree context;
6741
6742   context = DECL_CONTEXT (friend_tmpl);
6743
6744   if (context)
6745     {
6746       if (TREE_CODE (context) == NAMESPACE_DECL)
6747         push_nested_namespace (context);
6748       else
6749         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6750     }
6751
6752   /* Look for a class template declaration.  We look for hidden names
6753      because two friend declarations of the same template are the
6754      same.  For example, in:
6755
6756        struct A { 
6757          template <typename> friend class F;
6758        };
6759        template <typename> struct B { 
6760          template <typename> friend class F;
6761        };
6762
6763      both F templates are the same.  */
6764   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6765                            /*block_p=*/true, 0, 
6766                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6767
6768   /* But, if we don't find one, it might be because we're in a
6769      situation like this:
6770
6771        template <class T>
6772        struct S {
6773          template <class U>
6774          friend struct S;
6775        };
6776
6777      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6778      for `S<int>', not the TEMPLATE_DECL.  */
6779   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6780     {
6781       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6782       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6783     }
6784
6785   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6786     {
6787       /* The friend template has already been declared.  Just
6788          check to see that the declarations match, and install any new
6789          default parameters.  We must tsubst the default parameters,
6790          of course.  We only need the innermost template parameters
6791          because that is all that redeclare_class_template will look
6792          at.  */
6793       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6794           > TMPL_ARGS_DEPTH (args))
6795         {
6796           tree parms;
6797           location_t saved_input_location;
6798           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6799                                          args, tf_warning_or_error);
6800
6801           saved_input_location = input_location;
6802           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6803           redeclare_class_template (TREE_TYPE (tmpl), parms);
6804           input_location = saved_input_location;
6805           
6806         }
6807
6808       friend_type = TREE_TYPE (tmpl);
6809     }
6810   else
6811     {
6812       /* The friend template has not already been declared.  In this
6813          case, the instantiation of the template class will cause the
6814          injection of this template into the global scope.  */
6815       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6816       if (tmpl == error_mark_node)
6817         return error_mark_node;
6818
6819       /* The new TMPL is not an instantiation of anything, so we
6820          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6821          the new type because that is supposed to be the corresponding
6822          template decl, i.e., TMPL.  */
6823       DECL_USE_TEMPLATE (tmpl) = 0;
6824       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6825       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6826       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6827         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6828
6829       /* Inject this template into the global scope.  */
6830       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6831     }
6832
6833   if (context)
6834     {
6835       if (TREE_CODE (context) == NAMESPACE_DECL)
6836         pop_nested_namespace (context);
6837       else
6838         pop_nested_class ();
6839     }
6840
6841   return friend_type;
6842 }
6843
6844 /* Returns zero if TYPE cannot be completed later due to circularity.
6845    Otherwise returns one.  */
6846
6847 static int
6848 can_complete_type_without_circularity (tree type)
6849 {
6850   if (type == NULL_TREE || type == error_mark_node)
6851     return 0;
6852   else if (COMPLETE_TYPE_P (type))
6853     return 1;
6854   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6855     return can_complete_type_without_circularity (TREE_TYPE (type));
6856   else if (CLASS_TYPE_P (type)
6857            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6858     return 0;
6859   else
6860     return 1;
6861 }
6862
6863 /* Apply any attributes which had to be deferred until instantiation
6864    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6865    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6866
6867 static void
6868 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6869                                 tree args, tsubst_flags_t complain, tree in_decl)
6870 {
6871   tree last_dep = NULL_TREE;
6872   tree t;
6873   tree *p;
6874
6875   for (t = attributes; t; t = TREE_CHAIN (t))
6876     if (ATTR_IS_DEPENDENT (t))
6877       {
6878         last_dep = t;
6879         attributes = copy_list (attributes);
6880         break;
6881       }
6882
6883   if (DECL_P (*decl_p))
6884     {
6885       if (TREE_TYPE (*decl_p) == error_mark_node)
6886         return;
6887       p = &DECL_ATTRIBUTES (*decl_p);
6888     }
6889   else
6890     p = &TYPE_ATTRIBUTES (*decl_p);
6891
6892   if (last_dep)
6893     {
6894       tree late_attrs = NULL_TREE;
6895       tree *q = &late_attrs;
6896
6897       for (*p = attributes; *p; )
6898         {
6899           t = *p;
6900           if (ATTR_IS_DEPENDENT (t))
6901             {
6902               *p = TREE_CHAIN (t);
6903               TREE_CHAIN (t) = NULL_TREE;
6904               /* If the first attribute argument is an identifier, don't
6905                  pass it through tsubst.  Attributes like mode, format,
6906                  cleanup and several target specific attributes expect it
6907                  unmodified.  */
6908               if (TREE_VALUE (t)
6909                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
6910                   && TREE_VALUE (TREE_VALUE (t))
6911                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
6912                       == IDENTIFIER_NODE))
6913                 {
6914                   tree chain
6915                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
6916                                    in_decl,
6917                                    /*integral_constant_expression_p=*/false);
6918                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
6919                     TREE_VALUE (t)
6920                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
6921                                    chain);
6922                 }
6923               else
6924                 TREE_VALUE (t)
6925                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6926                                  /*integral_constant_expression_p=*/false);
6927               *q = t;
6928               q = &TREE_CHAIN (t);
6929             }
6930           else
6931             p = &TREE_CHAIN (t);
6932         }
6933
6934       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
6935     }
6936 }
6937
6938 tree
6939 instantiate_class_template (tree type)
6940 {
6941   tree templ, args, pattern, t, member;
6942   tree typedecl;
6943   tree pbinfo;
6944   tree base_list;
6945
6946   if (type == error_mark_node)
6947     return error_mark_node;
6948
6949   if (TYPE_BEING_DEFINED (type)
6950       || COMPLETE_TYPE_P (type)
6951       || dependent_type_p (type))
6952     return type;
6953
6954   /* Figure out which template is being instantiated.  */
6955   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6956   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6957
6958   /* Determine what specialization of the original template to
6959      instantiate.  */
6960   t = most_specialized_class (type, templ);
6961   if (t == error_mark_node)
6962     {
6963       TYPE_BEING_DEFINED (type) = 1;
6964       return error_mark_node;
6965     }
6966   else if (t)
6967     {
6968       /* This TYPE is actually an instantiation of a partial
6969          specialization.  We replace the innermost set of ARGS with
6970          the arguments appropriate for substitution.  For example,
6971          given:
6972
6973            template <class T> struct S {};
6974            template <class T> struct S<T*> {};
6975
6976          and supposing that we are instantiating S<int*>, ARGS will
6977          presently be {int*} -- but we need {int}.  */
6978       pattern = TREE_TYPE (t);
6979       args = TREE_PURPOSE (t);
6980     }
6981   else
6982     {
6983       pattern = TREE_TYPE (templ);
6984       args = CLASSTYPE_TI_ARGS (type);
6985     }
6986
6987   /* If the template we're instantiating is incomplete, then clearly
6988      there's nothing we can do.  */
6989   if (!COMPLETE_TYPE_P (pattern))
6990     return type;
6991
6992   /* If we've recursively instantiated too many templates, stop.  */
6993   if (! push_tinst_level (type))
6994     return type;
6995
6996   /* Now we're really doing the instantiation.  Mark the type as in
6997      the process of being defined.  */
6998   TYPE_BEING_DEFINED (type) = 1;
6999
7000   /* We may be in the middle of deferred access check.  Disable
7001      it now.  */
7002   push_deferring_access_checks (dk_no_deferred);
7003
7004   push_to_top_level ();
7005
7006   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7007
7008   /* Set the input location to the template definition. This is needed
7009      if tsubsting causes an error.  */
7010   typedecl = TYPE_MAIN_DECL (type);
7011   input_location = DECL_SOURCE_LOCATION (typedecl);
7012
7013   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7014   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7015   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7016   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7017   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7018   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7019   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7020   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7021   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7022   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7023   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7024   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7025   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7026   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7027   if (ANON_AGGR_TYPE_P (pattern))
7028     SET_ANON_AGGR_TYPE_P (type);
7029   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7030     {
7031       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7032       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7033     }
7034
7035   pbinfo = TYPE_BINFO (pattern);
7036
7037   /* We should never instantiate a nested class before its enclosing
7038      class; we need to look up the nested class by name before we can
7039      instantiate it, and that lookup should instantiate the enclosing
7040      class.  */
7041   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7042               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7043               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7044
7045   base_list = NULL_TREE;
7046   if (BINFO_N_BASE_BINFOS (pbinfo))
7047     {
7048       tree pbase_binfo;
7049       tree context = TYPE_CONTEXT (type);
7050       tree pushed_scope;
7051       int i;
7052
7053       /* We must enter the scope containing the type, as that is where
7054          the accessibility of types named in dependent bases are
7055          looked up from.  */
7056       pushed_scope = push_scope (context ? context : global_namespace);
7057
7058       /* Substitute into each of the bases to determine the actual
7059          basetypes.  */
7060       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7061         {
7062           tree base;
7063           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7064           tree expanded_bases = NULL_TREE;
7065           int idx, len = 1;
7066
7067           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7068             {
7069               expanded_bases = 
7070                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7071                                        args, tf_error, NULL_TREE);
7072               if (expanded_bases == error_mark_node)
7073                 continue;
7074
7075               len = TREE_VEC_LENGTH (expanded_bases);
7076             }
7077
7078           for (idx = 0; idx < len; idx++)
7079             {
7080               if (expanded_bases)
7081                 /* Extract the already-expanded base class.  */
7082                 base = TREE_VEC_ELT (expanded_bases, idx);
7083               else
7084                 /* Substitute to figure out the base class.  */
7085                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7086                                NULL_TREE);
7087
7088               if (base == error_mark_node)
7089                 continue;
7090
7091               base_list = tree_cons (access, base, base_list);
7092               if (BINFO_VIRTUAL_P (pbase_binfo))
7093                 TREE_TYPE (base_list) = integer_type_node;
7094             }
7095         }
7096
7097       /* The list is now in reverse order; correct that.  */
7098       base_list = nreverse (base_list);
7099
7100       if (pushed_scope)
7101         pop_scope (pushed_scope);
7102     }
7103   /* Now call xref_basetypes to set up all the base-class
7104      information.  */
7105   xref_basetypes (type, base_list);
7106
7107   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7108                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7109                                   args, tf_error, NULL_TREE);
7110
7111   /* Now that our base classes are set up, enter the scope of the
7112      class, so that name lookups into base classes, etc. will work
7113      correctly.  This is precisely analogous to what we do in
7114      begin_class_definition when defining an ordinary non-template
7115      class, except we also need to push the enclosing classes.  */
7116   push_nested_class (type);
7117
7118   /* Now members are processed in the order of declaration.  */
7119   for (member = CLASSTYPE_DECL_LIST (pattern);
7120        member; member = TREE_CHAIN (member))
7121     {
7122       tree t = TREE_VALUE (member);
7123
7124       if (TREE_PURPOSE (member))
7125         {
7126           if (TYPE_P (t))
7127             {
7128               /* Build new CLASSTYPE_NESTED_UTDS.  */
7129
7130               tree newtag;
7131               bool class_template_p;
7132
7133               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7134                                   && TYPE_LANG_SPECIFIC (t)
7135                                   && CLASSTYPE_IS_TEMPLATE (t));
7136               /* If the member is a class template, then -- even after
7137                  substitution -- there may be dependent types in the
7138                  template argument list for the class.  We increment
7139                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7140                  that function will assume that no types are dependent
7141                  when outside of a template.  */
7142               if (class_template_p)
7143                 ++processing_template_decl;
7144               newtag = tsubst (t, args, tf_error, NULL_TREE);
7145               if (class_template_p)
7146                 --processing_template_decl;
7147               if (newtag == error_mark_node)
7148                 continue;
7149
7150               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7151                 {
7152                   tree name = TYPE_IDENTIFIER (t);
7153
7154                   if (class_template_p)
7155                     /* Unfortunately, lookup_template_class sets
7156                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7157                        instantiation (i.e., for the type of a member
7158                        template class nested within a template class.)
7159                        This behavior is required for
7160                        maybe_process_partial_specialization to work
7161                        correctly, but is not accurate in this case;
7162                        the TAG is not an instantiation of anything.
7163                        (The corresponding TEMPLATE_DECL is an
7164                        instantiation, but the TYPE is not.) */
7165                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7166
7167                   /* Now, we call pushtag to put this NEWTAG into the scope of
7168                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7169                      pushtag calling push_template_decl.  We don't have to do
7170                      this for enums because it will already have been done in
7171                      tsubst_enum.  */
7172                   if (name)
7173                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7174                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7175                 }
7176             }
7177           else if (TREE_CODE (t) == FUNCTION_DECL
7178                    || DECL_FUNCTION_TEMPLATE_P (t))
7179             {
7180               /* Build new TYPE_METHODS.  */
7181               tree r;
7182
7183               if (TREE_CODE (t) == TEMPLATE_DECL)
7184                 ++processing_template_decl;
7185               r = tsubst (t, args, tf_error, NULL_TREE);
7186               if (TREE_CODE (t) == TEMPLATE_DECL)
7187                 --processing_template_decl;
7188               set_current_access_from_decl (r);
7189               finish_member_declaration (r);
7190             }
7191           else
7192             {
7193               /* Build new TYPE_FIELDS.  */
7194               if (TREE_CODE (t) == STATIC_ASSERT)
7195                 {
7196                   tree condition = 
7197                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7198                                  tf_warning_or_error, NULL_TREE,
7199                                  /*integral_constant_expression_p=*/true);
7200                   finish_static_assert (condition,
7201                                         STATIC_ASSERT_MESSAGE (t), 
7202                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7203                                         /*member_p=*/true);
7204                 }
7205               else if (TREE_CODE (t) != CONST_DECL)
7206                 {
7207                   tree r;
7208
7209                   /* The file and line for this declaration, to
7210                      assist in error message reporting.  Since we
7211                      called push_tinst_level above, we don't need to
7212                      restore these.  */
7213                   input_location = DECL_SOURCE_LOCATION (t);
7214
7215                   if (TREE_CODE (t) == TEMPLATE_DECL)
7216                     ++processing_template_decl;
7217                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7218                   if (TREE_CODE (t) == TEMPLATE_DECL)
7219                     --processing_template_decl;
7220                   if (TREE_CODE (r) == VAR_DECL)
7221                     {
7222                       /* In [temp.inst]:
7223
7224                            [t]he initialization (and any associated
7225                            side-effects) of a static data member does
7226                            not occur unless the static data member is
7227                            itself used in a way that requires the
7228                            definition of the static data member to
7229                            exist.
7230
7231                          Therefore, we do not substitute into the
7232                          initialized for the static data member here.  */
7233                       finish_static_data_member_decl
7234                         (r,
7235                          /*init=*/NULL_TREE,
7236                          /*init_const_expr_p=*/false,
7237                          /*asmspec_tree=*/NULL_TREE,
7238                          /*flags=*/0);
7239                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7240                         check_static_variable_definition (r, TREE_TYPE (r));
7241                     }
7242                   else if (TREE_CODE (r) == FIELD_DECL)
7243                     {
7244                       /* Determine whether R has a valid type and can be
7245                          completed later.  If R is invalid, then it is
7246                          replaced by error_mark_node so that it will not be
7247                          added to TYPE_FIELDS.  */
7248                       tree rtype = TREE_TYPE (r);
7249                       if (can_complete_type_without_circularity (rtype))
7250                         complete_type (rtype);
7251
7252                       if (!COMPLETE_TYPE_P (rtype))
7253                         {
7254                           cxx_incomplete_type_error (r, rtype);
7255                           r = error_mark_node;
7256                         }
7257                     }
7258
7259                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7260                      such a thing will already have been added to the field
7261                      list by tsubst_enum in finish_member_declaration in the
7262                      CLASSTYPE_NESTED_UTDS case above.  */
7263                   if (!(TREE_CODE (r) == TYPE_DECL
7264                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7265                         && DECL_ARTIFICIAL (r)))
7266                     {
7267                       set_current_access_from_decl (r);
7268                       finish_member_declaration (r);
7269                     }
7270                 }
7271             }
7272         }
7273       else
7274         {
7275           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7276             {
7277               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7278
7279               tree friend_type = t;
7280               bool adjust_processing_template_decl = false;
7281
7282               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7283                 {
7284                   /* template <class T> friend class C;  */
7285                   friend_type = tsubst_friend_class (friend_type, args);
7286                   adjust_processing_template_decl = true;
7287                 }
7288               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7289                 {
7290                   /* template <class T> friend class C::D;  */
7291                   friend_type = tsubst (friend_type, args,
7292                                         tf_warning_or_error, NULL_TREE);
7293                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7294                     friend_type = TREE_TYPE (friend_type);
7295                   adjust_processing_template_decl = true;
7296                 }
7297               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7298                 {
7299                   /* This could be either
7300
7301                        friend class T::C;
7302
7303                      when dependent_type_p is false or
7304
7305                        template <class U> friend class T::C;
7306
7307                      otherwise.  */
7308                   friend_type = tsubst (friend_type, args,
7309                                         tf_warning_or_error, NULL_TREE);
7310                   /* Bump processing_template_decl for correct
7311                      dependent_type_p calculation.  */
7312                   ++processing_template_decl;
7313                   if (dependent_type_p (friend_type))
7314                     adjust_processing_template_decl = true;
7315                   --processing_template_decl;
7316                 }
7317               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7318                        && hidden_name_p (TYPE_NAME (friend_type)))
7319                 {
7320                   /* friend class C;
7321
7322                      where C hasn't been declared yet.  Let's lookup name
7323                      from namespace scope directly, bypassing any name that
7324                      come from dependent base class.  */
7325                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7326
7327                   /* The call to xref_tag_from_type does injection for friend
7328                      classes.  */
7329                   push_nested_namespace (ns);
7330                   friend_type =
7331                     xref_tag_from_type (friend_type, NULL_TREE,
7332                                         /*tag_scope=*/ts_current);
7333                   pop_nested_namespace (ns);
7334                 }
7335               else if (uses_template_parms (friend_type))
7336                 /* friend class C<T>;  */
7337                 friend_type = tsubst (friend_type, args,
7338                                       tf_warning_or_error, NULL_TREE);
7339               /* Otherwise it's
7340
7341                    friend class C;
7342
7343                  where C is already declared or
7344
7345                    friend class C<int>;
7346
7347                  We don't have to do anything in these cases.  */
7348
7349               if (adjust_processing_template_decl)
7350                 /* Trick make_friend_class into realizing that the friend
7351                    we're adding is a template, not an ordinary class.  It's
7352                    important that we use make_friend_class since it will
7353                    perform some error-checking and output cross-reference
7354                    information.  */
7355                 ++processing_template_decl;
7356
7357               if (friend_type != error_mark_node)
7358                 make_friend_class (type, friend_type, /*complain=*/false);
7359
7360               if (adjust_processing_template_decl)
7361                 --processing_template_decl;
7362             }
7363           else
7364             {
7365               /* Build new DECL_FRIENDLIST.  */
7366               tree r;
7367
7368               /* The file and line for this declaration, to
7369                  assist in error message reporting.  Since we
7370                  called push_tinst_level above, we don't need to
7371                  restore these.  */
7372               input_location = DECL_SOURCE_LOCATION (t);
7373
7374               if (TREE_CODE (t) == TEMPLATE_DECL)
7375                 {
7376                   ++processing_template_decl;
7377                   push_deferring_access_checks (dk_no_check);
7378                 }
7379
7380               r = tsubst_friend_function (t, args);
7381               add_friend (type, r, /*complain=*/false);
7382               if (TREE_CODE (t) == TEMPLATE_DECL)
7383                 {
7384                   pop_deferring_access_checks ();
7385                   --processing_template_decl;
7386                 }
7387             }
7388         }
7389     }
7390
7391   /* Set the file and line number information to whatever is given for
7392      the class itself.  This puts error messages involving generated
7393      implicit functions at a predictable point, and the same point
7394      that would be used for non-template classes.  */
7395   input_location = DECL_SOURCE_LOCATION (typedecl);
7396
7397   unreverse_member_declarations (type);
7398   finish_struct_1 (type);
7399   TYPE_BEING_DEFINED (type) = 0;
7400
7401   /* Now that the class is complete, instantiate default arguments for
7402      any member functions.  We don't do this earlier because the
7403      default arguments may reference members of the class.  */
7404   if (!PRIMARY_TEMPLATE_P (templ))
7405     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7406       if (TREE_CODE (t) == FUNCTION_DECL
7407           /* Implicitly generated member functions will not have template
7408              information; they are not instantiations, but instead are
7409              created "fresh" for each instantiation.  */
7410           && DECL_TEMPLATE_INFO (t))
7411         tsubst_default_arguments (t);
7412
7413   pop_nested_class ();
7414   pop_from_top_level ();
7415   pop_deferring_access_checks ();
7416   pop_tinst_level ();
7417
7418   /* The vtable for a template class can be emitted in any translation
7419      unit in which the class is instantiated.  When there is no key
7420      method, however, finish_struct_1 will already have added TYPE to
7421      the keyed_classes list.  */
7422   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7423     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7424
7425   return type;
7426 }
7427
7428 static tree
7429 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7430 {
7431   tree r;
7432
7433   if (!t)
7434     r = t;
7435   else if (TYPE_P (t))
7436     r = tsubst (t, args, complain, in_decl);
7437   else
7438     {
7439       r = tsubst_expr (t, args, complain, in_decl,
7440                        /*integral_constant_expression_p=*/true);
7441       r = fold_non_dependent_expr (r);
7442     }
7443   return r;
7444 }
7445
7446 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7447    NONTYPE_ARGUMENT_PACK.  */
7448
7449 static tree
7450 make_fnparm_pack (tree spec_parm)
7451 {
7452   /* Collect all of the extra "packed" parameters into an
7453      argument pack.  */
7454   tree parmvec;
7455   tree parmtypevec;
7456   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7457   tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
7458   int i, len = list_length (spec_parm);
7459
7460   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7461   parmvec = make_tree_vec (len);
7462   parmtypevec = make_tree_vec (len);
7463   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7464     {
7465       TREE_VEC_ELT (parmvec, i) = spec_parm;
7466       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7467     }
7468
7469   /* Build the argument packs.  */
7470   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7471   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7472   TREE_TYPE (argpack) = argtypepack;
7473
7474   return argpack;
7475 }        
7476
7477 /* Substitute ARGS into T, which is an pack expansion
7478    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7479    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7480    (if only a partial substitution could be performed) or
7481    ERROR_MARK_NODE if there was an error.  */
7482 tree
7483 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7484                        tree in_decl)
7485 {
7486   tree pattern;
7487   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7488   tree first_arg_pack; int i, len = -1;
7489   tree result;
7490   int incomplete = 0;
7491   bool very_local_specializations = false;
7492
7493   gcc_assert (PACK_EXPANSION_P (t));
7494   pattern = PACK_EXPANSION_PATTERN (t);
7495
7496   /* Determine the argument packs that will instantiate the parameter
7497      packs used in the expansion expression. While we're at it,
7498      compute the number of arguments to be expanded and make sure it
7499      is consistent.  */
7500   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7501        pack = TREE_CHAIN (pack))
7502     {
7503       tree parm_pack = TREE_VALUE (pack);
7504       tree arg_pack = NULL_TREE;
7505       tree orig_arg = NULL_TREE;
7506
7507       if (TREE_CODE (parm_pack) == PARM_DECL)
7508         {
7509           arg_pack = retrieve_local_specialization (parm_pack);
7510           if (arg_pack == NULL_TREE)
7511             {
7512               /* This can happen for a parameter name used later in a function
7513                  declaration (such as in a late-specified return type).  Just
7514                  make a dummy decl, since it's only used for its type.  */
7515               gcc_assert (skip_evaluation);
7516               arg_pack = tsubst_decl (parm_pack, args, complain);
7517               arg_pack = make_fnparm_pack (arg_pack);
7518             }
7519         }
7520       else
7521         {
7522           int level, idx, levels;
7523           template_parm_level_and_index (parm_pack, &level, &idx);
7524
7525           levels = TMPL_ARGS_DEPTH (args);
7526           if (level <= levels)
7527             arg_pack = TMPL_ARG (args, level, idx);
7528         }
7529
7530       orig_arg = arg_pack;
7531       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7532         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7533       
7534       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7535         /* This can only happen if we forget to expand an argument
7536            pack somewhere else. Just return an error, silently.  */
7537         {
7538           result = make_tree_vec (1);
7539           TREE_VEC_ELT (result, 0) = error_mark_node;
7540           return result;
7541         }
7542
7543       if (arg_pack
7544           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7545           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7546         {
7547           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7548           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7549           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7550               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7551             /* The argument pack that the parameter maps to is just an
7552                expansion of the parameter itself, such as one would
7553                find in the implicit typedef of a class inside the
7554                class itself.  Consider this parameter "unsubstituted",
7555                so that we will maintain the outer pack expansion.  */
7556             arg_pack = NULL_TREE;
7557         }
7558           
7559       if (arg_pack)
7560         {
7561           int my_len = 
7562             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7563
7564           /* It's all-or-nothing with incomplete argument packs.  */
7565           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7566             return error_mark_node;
7567           
7568           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7569             incomplete = 1;
7570
7571           if (len < 0)
7572             {
7573               len = my_len;
7574               first_arg_pack = arg_pack;
7575             }
7576           else if (len != my_len)
7577             {
7578               if (incomplete)
7579                 /* We got explicit args for some packs but not others;
7580                    do nothing now and try again after deduction.  */
7581                 return t;
7582               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7583                 error ("mismatched argument pack lengths while expanding "
7584                        "%<%T%>",
7585                        pattern);
7586               else
7587                 error ("mismatched argument pack lengths while expanding "
7588                        "%<%E%>",
7589                        pattern);
7590               return error_mark_node;
7591             }
7592
7593           /* Keep track of the parameter packs and their corresponding
7594              argument packs.  */
7595           packs = tree_cons (parm_pack, arg_pack, packs);
7596           TREE_TYPE (packs) = orig_arg;
7597         }
7598       else
7599         /* We can't substitute for this parameter pack.  */
7600         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7601                                          TREE_VALUE (pack),
7602                                          unsubstituted_packs);
7603     }
7604
7605   /* We cannot expand this expansion expression, because we don't have
7606      all of the argument packs we need. Substitute into the pattern
7607      and return a PACK_EXPANSION_*. The caller will need to deal with
7608      that.  */
7609   if (unsubstituted_packs)
7610     {
7611       tree new_pat;
7612       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7613         new_pat = tsubst_expr (pattern, args, complain, in_decl,
7614                                /*integral_constant_expression_p=*/false);
7615       else
7616         new_pat = tsubst (pattern, args, complain, in_decl);
7617       return make_pack_expansion (new_pat);
7618     }
7619
7620   /* We could not find any argument packs that work.  */
7621   if (len < 0)
7622     return error_mark_node;
7623
7624   if (!local_specializations)
7625     {
7626       /* We're in a late-specified return type, so we don't have a local
7627          specializations table.  Create one for doing this expansion.  */
7628       very_local_specializations = true;
7629       local_specializations = htab_create (37,
7630                                            hash_local_specialization,
7631                                            eq_local_specializations,
7632                                            NULL);
7633     }
7634
7635   /* For each argument in each argument pack, substitute into the
7636      pattern.  */
7637   result = make_tree_vec (len + incomplete);
7638   for (i = 0; i < len + incomplete; ++i)
7639     {
7640       /* For parameter pack, change the substitution of the parameter
7641          pack to the ith argument in its argument pack, then expand
7642          the pattern.  */
7643       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7644         {
7645           tree parm = TREE_PURPOSE (pack);
7646
7647           if (TREE_CODE (parm) == PARM_DECL)
7648             {
7649               /* Select the Ith argument from the pack.  */
7650               tree arg = make_node (ARGUMENT_PACK_SELECT);
7651               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7652               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7653               mark_used (parm);
7654               register_local_specialization (arg, parm);
7655             }
7656           else
7657             {
7658               tree value = parm;
7659               int idx, level;
7660               template_parm_level_and_index (parm, &level, &idx);
7661               
7662               if (i < len) 
7663                 {
7664                   /* Select the Ith argument from the pack. */
7665                   value = make_node (ARGUMENT_PACK_SELECT);
7666                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7667                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7668                 }
7669
7670               /* Update the corresponding argument.  */
7671               TMPL_ARG (args, level, idx) = value;
7672             }
7673         }
7674
7675       /* Substitute into the PATTERN with the altered arguments.  */
7676       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7677         TREE_VEC_ELT (result, i) = 
7678           tsubst_expr (pattern, args, complain, in_decl,
7679                        /*integral_constant_expression_p=*/false);
7680       else
7681         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7682
7683       if (i == len)
7684         /* When we have incomplete argument packs, the last "expanded"
7685            result is itself a pack expansion, which allows us
7686            to deduce more arguments.  */
7687         TREE_VEC_ELT (result, i) = 
7688           make_pack_expansion (TREE_VEC_ELT (result, i));
7689
7690       if (TREE_VEC_ELT (result, i) == error_mark_node)
7691         {
7692           result = error_mark_node;
7693           break;
7694         }
7695     }
7696
7697   /* Update ARGS to restore the substitution from parameter packs to
7698      their argument packs.  */
7699   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7700     {
7701       tree parm = TREE_PURPOSE (pack);
7702
7703       if (TREE_CODE (parm) == PARM_DECL)
7704         register_local_specialization (TREE_TYPE (pack), parm);
7705       else
7706         {
7707           int idx, level;
7708           template_parm_level_and_index (parm, &level, &idx);
7709           
7710           /* Update the corresponding argument.  */
7711           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7712             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7713               TREE_TYPE (pack);
7714           else
7715             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7716         }
7717     }
7718
7719   if (very_local_specializations)
7720     {
7721       htab_delete (local_specializations);
7722       local_specializations = NULL;
7723     }
7724   
7725   return result;
7726 }
7727
7728 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
7729    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
7730    parameter packs; all parms generated from a function parameter pack will
7731    have the same DECL_PARM_INDEX.  */
7732
7733 tree
7734 get_pattern_parm (tree parm, tree tmpl)
7735 {
7736   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
7737   tree patparm;
7738
7739   if (DECL_ARTIFICIAL (parm))
7740     {
7741       for (patparm = DECL_ARGUMENTS (pattern);
7742            patparm; patparm = TREE_CHAIN (patparm))
7743         if (DECL_ARTIFICIAL (patparm)
7744             && DECL_NAME (parm) == DECL_NAME (patparm))
7745           break;
7746     }
7747   else
7748     {
7749       for (patparm = FUNCTION_FIRST_USER_PARM (pattern);
7750            patparm; patparm = TREE_CHAIN (patparm))
7751         {
7752           if (DECL_NAME (patparm) == DECL_NAME (parm))
7753             break;
7754           if (FUNCTION_PARAMETER_PACK_P (patparm)
7755               /* OK, this is a hack. We know that if PARAM_DECL is expanded
7756                  from PACK, its name (built with make_ith_pack_parameter_name)
7757                  is the string "<foo>#N" where <foo> is the name of PACK
7758                  and N is a number.
7759                  So we just check that naming pattern.  */
7760               && (IDENTIFIER_LENGTH (DECL_NAME (patparm))
7761                   < IDENTIFIER_LENGTH (DECL_NAME (parm)))
7762               && ! strncmp (IDENTIFIER_POINTER (DECL_NAME (parm)),
7763                             IDENTIFIER_POINTER (DECL_NAME (patparm)),
7764                             IDENTIFIER_LENGTH (DECL_NAME (patparm)))
7765               && (IDENTIFIER_POINTER (DECL_NAME (parm))
7766                   [IDENTIFIER_LENGTH (DECL_NAME (patparm))]
7767                   == '#'))
7768             break;
7769         }
7770     }
7771
7772   return patparm;
7773 }
7774
7775 /* Substitute ARGS into the vector or list of template arguments T.  */
7776
7777 static tree
7778 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7779 {
7780   tree orig_t = t;
7781   int len = TREE_VEC_LENGTH (t);
7782   int need_new = 0, i, expanded_len_adjust = 0, out;
7783   tree *elts = (tree *) alloca (len * sizeof (tree));
7784
7785   for (i = 0; i < len; i++)
7786     {
7787       tree orig_arg = TREE_VEC_ELT (t, i);
7788       tree new_arg;
7789
7790       if (TREE_CODE (orig_arg) == TREE_VEC)
7791         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7792       else if (PACK_EXPANSION_P (orig_arg))
7793         {
7794           /* Substitute into an expansion expression.  */
7795           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7796
7797           if (TREE_CODE (new_arg) == TREE_VEC)
7798             /* Add to the expanded length adjustment the number of
7799                expanded arguments. We subtract one from this
7800                measurement, because the argument pack expression
7801                itself is already counted as 1 in
7802                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7803                the argument pack is empty.  */
7804             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7805         }
7806       else if (ARGUMENT_PACK_P (orig_arg))
7807         {
7808           /* Substitute into each of the arguments.  */
7809           new_arg = make_node (TREE_CODE (orig_arg));
7810           
7811           SET_ARGUMENT_PACK_ARGS (
7812             new_arg,
7813             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7814                                   args, complain, in_decl));
7815
7816           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7817             new_arg = error_mark_node;
7818
7819           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7820             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7821                                           complain, in_decl);
7822             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7823
7824             if (TREE_TYPE (new_arg) == error_mark_node)
7825               new_arg = error_mark_node;
7826           }
7827         }
7828       else
7829         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7830
7831       if (new_arg == error_mark_node)
7832         return error_mark_node;
7833
7834       elts[i] = new_arg;
7835       if (new_arg != orig_arg)
7836         need_new = 1;
7837     }
7838
7839   if (!need_new)
7840     return t;
7841
7842   /* Make space for the expanded arguments coming from template
7843      argument packs.  */
7844   t = make_tree_vec (len + expanded_len_adjust);
7845   for (i = 0, out = 0; i < len; i++)
7846     {
7847       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7848            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7849           && TREE_CODE (elts[i]) == TREE_VEC)
7850         {
7851           int idx;
7852
7853           /* Now expand the template argument pack "in place".  */
7854           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7855             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7856         }
7857       else
7858         {
7859           TREE_VEC_ELT (t, out) = elts[i];
7860           out++;
7861         }
7862     }
7863
7864   return t;
7865 }
7866
7867 /* Return the result of substituting ARGS into the template parameters
7868    given by PARMS.  If there are m levels of ARGS and m + n levels of
7869    PARMS, then the result will contain n levels of PARMS.  For
7870    example, if PARMS is `template <class T> template <class U>
7871    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7872    result will be `template <int*, double, class V>'.  */
7873
7874 static tree
7875 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7876 {
7877   tree r = NULL_TREE;
7878   tree* new_parms;
7879
7880   /* When substituting into a template, we must set
7881      PROCESSING_TEMPLATE_DECL as the template parameters may be
7882      dependent if they are based on one-another, and the dependency
7883      predicates are short-circuit outside of templates.  */
7884   ++processing_template_decl;
7885
7886   for (new_parms = &r;
7887        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7888        new_parms = &(TREE_CHAIN (*new_parms)),
7889          parms = TREE_CHAIN (parms))
7890     {
7891       tree new_vec =
7892         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7893       int i;
7894
7895       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7896         {
7897           tree tuple;
7898           tree default_value;
7899           tree parm_decl;
7900
7901           if (parms == error_mark_node)
7902             continue;
7903
7904           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7905
7906           if (tuple == error_mark_node)
7907             continue;
7908
7909           default_value = TREE_PURPOSE (tuple);
7910           parm_decl = TREE_VALUE (tuple);
7911
7912           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7913           if (TREE_CODE (parm_decl) == PARM_DECL
7914               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7915             parm_decl = error_mark_node;
7916           default_value = tsubst_template_arg (default_value, args,
7917                                                complain, NULL_TREE);
7918
7919           tuple = build_tree_list (default_value, parm_decl);
7920           TREE_VEC_ELT (new_vec, i) = tuple;
7921         }
7922
7923       *new_parms =
7924         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7925                              - TMPL_ARGS_DEPTH (args)),
7926                    new_vec, NULL_TREE);
7927     }
7928
7929   --processing_template_decl;
7930
7931   return r;
7932 }
7933
7934 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7935    type T.  If T is not an aggregate or enumeration type, it is
7936    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7937    ENTERING_SCOPE is nonzero, T is the context for a template which
7938    we are presently tsubst'ing.  Return the substituted value.  */
7939
7940 static tree
7941 tsubst_aggr_type (tree t,
7942                   tree args,
7943                   tsubst_flags_t complain,
7944                   tree in_decl,
7945                   int entering_scope)
7946 {
7947   if (t == NULL_TREE)
7948     return NULL_TREE;
7949
7950   switch (TREE_CODE (t))
7951     {
7952     case RECORD_TYPE:
7953       if (TYPE_PTRMEMFUNC_P (t))
7954         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7955
7956       /* Else fall through.  */
7957     case ENUMERAL_TYPE:
7958     case UNION_TYPE:
7959       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
7960         {
7961           tree argvec;
7962           tree context;
7963           tree r;
7964           bool saved_skip_evaluation;
7965
7966           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7967           saved_skip_evaluation = skip_evaluation;
7968           skip_evaluation = false;
7969
7970           /* First, determine the context for the type we are looking
7971              up.  */
7972           context = TYPE_CONTEXT (t);
7973           if (context)
7974             {
7975               context = tsubst_aggr_type (context, args, complain,
7976                                           in_decl, /*entering_scope=*/1);
7977               /* If context is a nested class inside a class template,
7978                  it may still need to be instantiated (c++/33959).  */
7979               if (TYPE_P (context))
7980                 context = complete_type (context);
7981             }
7982
7983           /* Then, figure out what arguments are appropriate for the
7984              type we are trying to find.  For example, given:
7985
7986                template <class T> struct S;
7987                template <class T, class U> void f(T, U) { S<U> su; }
7988
7989              and supposing that we are instantiating f<int, double>,
7990              then our ARGS will be {int, double}, but, when looking up
7991              S we only want {double}.  */
7992           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7993                                          complain, in_decl);
7994           if (argvec == error_mark_node)
7995             r = error_mark_node;
7996           else
7997             {
7998               r = lookup_template_class (t, argvec, in_decl, context,
7999                                          entering_scope, complain);
8000               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8001             }
8002
8003           skip_evaluation = saved_skip_evaluation;
8004
8005           return r;
8006         }
8007       else
8008         /* This is not a template type, so there's nothing to do.  */
8009         return t;
8010
8011     default:
8012       return tsubst (t, args, complain, in_decl);
8013     }
8014 }
8015
8016 /* Substitute into the default argument ARG (a default argument for
8017    FN), which has the indicated TYPE.  */
8018
8019 tree
8020 tsubst_default_argument (tree fn, tree type, tree arg)
8021 {
8022   tree saved_class_ptr = NULL_TREE;
8023   tree saved_class_ref = NULL_TREE;
8024
8025   /* This default argument came from a template.  Instantiate the
8026      default argument here, not in tsubst.  In the case of
8027      something like:
8028
8029        template <class T>
8030        struct S {
8031          static T t();
8032          void f(T = t());
8033        };
8034
8035      we must be careful to do name lookup in the scope of S<T>,
8036      rather than in the current class.  */
8037   push_access_scope (fn);
8038   /* The "this" pointer is not valid in a default argument.  */
8039   if (cfun)
8040     {
8041       saved_class_ptr = current_class_ptr;
8042       cp_function_chain->x_current_class_ptr = NULL_TREE;
8043       saved_class_ref = current_class_ref;
8044       cp_function_chain->x_current_class_ref = NULL_TREE;
8045     }
8046
8047   push_deferring_access_checks(dk_no_deferred);
8048   /* The default argument expression may cause implicitly defined
8049      member functions to be synthesized, which will result in garbage
8050      collection.  We must treat this situation as if we were within
8051      the body of function so as to avoid collecting live data on the
8052      stack.  */
8053   ++function_depth;
8054   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8055                      tf_warning_or_error, NULL_TREE,
8056                      /*integral_constant_expression_p=*/false);
8057   --function_depth;
8058   pop_deferring_access_checks();
8059
8060   /* Restore the "this" pointer.  */
8061   if (cfun)
8062     {
8063       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8064       cp_function_chain->x_current_class_ref = saved_class_ref;
8065     }
8066
8067   /* Make sure the default argument is reasonable.  */
8068   arg = check_default_argument (type, arg);
8069
8070   pop_access_scope (fn);
8071
8072   return arg;
8073 }
8074
8075 /* Substitute into all the default arguments for FN.  */
8076
8077 static void
8078 tsubst_default_arguments (tree fn)
8079 {
8080   tree arg;
8081   tree tmpl_args;
8082
8083   tmpl_args = DECL_TI_ARGS (fn);
8084
8085   /* If this function is not yet instantiated, we certainly don't need
8086      its default arguments.  */
8087   if (uses_template_parms (tmpl_args))
8088     return;
8089
8090   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8091        arg;
8092        arg = TREE_CHAIN (arg))
8093     if (TREE_PURPOSE (arg))
8094       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8095                                                     TREE_VALUE (arg),
8096                                                     TREE_PURPOSE (arg));
8097 }
8098
8099 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8100    result of the substitution.  Issue error and warning messages under
8101    control of COMPLAIN.  */
8102
8103 static tree
8104 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8105 {
8106   location_t saved_loc;
8107   tree r = NULL_TREE;
8108   tree in_decl = t;
8109
8110   /* Set the filename and linenumber to improve error-reporting.  */
8111   saved_loc = input_location;
8112   input_location = DECL_SOURCE_LOCATION (t);
8113
8114   switch (TREE_CODE (t))
8115     {
8116     case TEMPLATE_DECL:
8117       {
8118         /* We can get here when processing a member function template,
8119            member class template, or template template parameter.  */
8120         tree decl = DECL_TEMPLATE_RESULT (t);
8121         tree spec;
8122         tree tmpl_args;
8123         tree full_args;
8124
8125         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8126           {
8127             /* Template template parameter is treated here.  */
8128             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8129             if (new_type == error_mark_node)
8130               return error_mark_node;
8131
8132             r = copy_decl (t);
8133             TREE_CHAIN (r) = NULL_TREE;
8134             TREE_TYPE (r) = new_type;
8135             DECL_TEMPLATE_RESULT (r)
8136               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
8137             DECL_TEMPLATE_PARMS (r)
8138               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8139                                        complain);
8140             TYPE_NAME (new_type) = r;
8141             break;
8142           }
8143
8144         /* We might already have an instance of this template.
8145            The ARGS are for the surrounding class type, so the
8146            full args contain the tsubst'd args for the context,
8147            plus the innermost args from the template decl.  */
8148         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8149           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8150           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8151         /* Because this is a template, the arguments will still be
8152            dependent, even after substitution.  If
8153            PROCESSING_TEMPLATE_DECL is not set, the dependency
8154            predicates will short-circuit.  */
8155         ++processing_template_decl;
8156         full_args = tsubst_template_args (tmpl_args, args,
8157                                           complain, in_decl);
8158         --processing_template_decl;
8159         if (full_args == error_mark_node)
8160           return error_mark_node;
8161
8162         /* If this is a default template template argument,
8163            tsubst might not have changed anything.  */
8164         if (full_args == tmpl_args)
8165           return t;
8166
8167         spec = retrieve_specialization (t, full_args,
8168                                         /*class_specializations_p=*/true);
8169         if (spec != NULL_TREE)
8170           {
8171             r = spec;
8172             break;
8173           }
8174
8175         /* Make a new template decl.  It will be similar to the
8176            original, but will record the current template arguments.
8177            We also create a new function declaration, which is just
8178            like the old one, but points to this new template, rather
8179            than the old one.  */
8180         r = copy_decl (t);
8181         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8182         TREE_CHAIN (r) = NULL_TREE;
8183
8184         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8185
8186         if (TREE_CODE (decl) == TYPE_DECL)
8187           {
8188             tree new_type;
8189             ++processing_template_decl;
8190             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8191             --processing_template_decl;
8192             if (new_type == error_mark_node)
8193               return error_mark_node;
8194
8195             TREE_TYPE (r) = new_type;
8196             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8197             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8198             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8199             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8200           }
8201         else
8202           {
8203             tree new_decl;
8204             ++processing_template_decl;
8205             new_decl = tsubst (decl, args, complain, in_decl);
8206             --processing_template_decl;
8207             if (new_decl == error_mark_node)
8208               return error_mark_node;
8209
8210             DECL_TEMPLATE_RESULT (r) = new_decl;
8211             DECL_TI_TEMPLATE (new_decl) = r;
8212             TREE_TYPE (r) = TREE_TYPE (new_decl);
8213             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8214             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8215           }
8216
8217         SET_DECL_IMPLICIT_INSTANTIATION (r);
8218         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8219         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8220
8221         /* The template parameters for this new template are all the
8222            template parameters for the old template, except the
8223            outermost level of parameters.  */
8224         DECL_TEMPLATE_PARMS (r)
8225           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8226                                    complain);
8227
8228         if (PRIMARY_TEMPLATE_P (t))
8229           DECL_PRIMARY_TEMPLATE (r) = r;
8230
8231         if (TREE_CODE (decl) != TYPE_DECL)
8232           /* Record this non-type partial instantiation.  */
8233           register_specialization (r, t,
8234                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8235                                    false);
8236       }
8237       break;
8238
8239     case FUNCTION_DECL:
8240       {
8241         tree ctx;
8242         tree argvec = NULL_TREE;
8243         tree *friends;
8244         tree gen_tmpl;
8245         tree type;
8246         int member;
8247         int args_depth;
8248         int parms_depth;
8249
8250         /* Nobody should be tsubst'ing into non-template functions.  */
8251         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8252
8253         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8254           {
8255             tree spec;
8256             bool dependent_p;
8257
8258             /* If T is not dependent, just return it.  We have to
8259                increment PROCESSING_TEMPLATE_DECL because
8260                value_dependent_expression_p assumes that nothing is
8261                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8262             ++processing_template_decl;
8263             dependent_p = value_dependent_expression_p (t);
8264             --processing_template_decl;
8265             if (!dependent_p)
8266               return t;
8267
8268             /* Calculate the most general template of which R is a
8269                specialization, and the complete set of arguments used to
8270                specialize R.  */
8271             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8272             argvec = tsubst_template_args (DECL_TI_ARGS
8273                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8274                                            args, complain, in_decl);
8275
8276             /* Check to see if we already have this specialization.  */
8277             spec = retrieve_specialization (gen_tmpl, argvec,
8278                                             /*class_specializations_p=*/false);
8279
8280             if (spec)
8281               {
8282                 r = spec;
8283                 break;
8284               }
8285
8286             /* We can see more levels of arguments than parameters if
8287                there was a specialization of a member template, like
8288                this:
8289
8290                  template <class T> struct S { template <class U> void f(); }
8291                  template <> template <class U> void S<int>::f(U);
8292
8293                Here, we'll be substituting into the specialization,
8294                because that's where we can find the code we actually
8295                want to generate, but we'll have enough arguments for
8296                the most general template.
8297
8298                We also deal with the peculiar case:
8299
8300                  template <class T> struct S {
8301                    template <class U> friend void f();
8302                  };
8303                  template <class U> void f() {}
8304                  template S<int>;
8305                  template void f<double>();
8306
8307                Here, the ARGS for the instantiation of will be {int,
8308                double}.  But, we only need as many ARGS as there are
8309                levels of template parameters in CODE_PATTERN.  We are
8310                careful not to get fooled into reducing the ARGS in
8311                situations like:
8312
8313                  template <class T> struct S { template <class U> void f(U); }
8314                  template <class T> template <> void S<T>::f(int) {}
8315
8316                which we can spot because the pattern will be a
8317                specialization in this case.  */
8318             args_depth = TMPL_ARGS_DEPTH (args);
8319             parms_depth =
8320               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8321             if (args_depth > parms_depth
8322                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8323               args = get_innermost_template_args (args, parms_depth);
8324           }
8325         else
8326           {
8327             /* This special case arises when we have something like this:
8328
8329                  template <class T> struct S {
8330                    friend void f<int>(int, double);
8331                  };
8332
8333                Here, the DECL_TI_TEMPLATE for the friend declaration
8334                will be an IDENTIFIER_NODE.  We are being called from
8335                tsubst_friend_function, and we want only to create a
8336                new decl (R) with appropriate types so that we can call
8337                determine_specialization.  */
8338             gen_tmpl = NULL_TREE;
8339           }
8340
8341         if (DECL_CLASS_SCOPE_P (t))
8342           {
8343             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8344               member = 2;
8345             else
8346               member = 1;
8347             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8348                                     complain, t, /*entering_scope=*/1);
8349           }
8350         else
8351           {
8352             member = 0;
8353             ctx = DECL_CONTEXT (t);
8354           }
8355         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8356         if (type == error_mark_node)
8357           return error_mark_node;
8358
8359         /* We do NOT check for matching decls pushed separately at this
8360            point, as they may not represent instantiations of this
8361            template, and in any case are considered separate under the
8362            discrete model.  */
8363         r = copy_decl (t);
8364         DECL_USE_TEMPLATE (r) = 0;
8365         TREE_TYPE (r) = type;
8366         /* Clear out the mangled name and RTL for the instantiation.  */
8367         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8368         SET_DECL_RTL (r, NULL_RTX);
8369         /* Leave DECL_INITIAL set on deleted instantiations.  */
8370         if (!DECL_DELETED_FN (r))
8371           DECL_INITIAL (r) = NULL_TREE;
8372         DECL_CONTEXT (r) = ctx;
8373
8374         if (member && DECL_CONV_FN_P (r))
8375           /* Type-conversion operator.  Reconstruct the name, in
8376              case it's the name of one of the template's parameters.  */
8377           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8378
8379         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8380                                      complain, t);
8381         DECL_RESULT (r) = NULL_TREE;
8382
8383         TREE_STATIC (r) = 0;
8384         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8385         DECL_EXTERNAL (r) = 1;
8386         /* If this is an instantiation of a function with internal
8387            linkage, we already know what object file linkage will be
8388            assigned to the instantiation.  */
8389         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8390         DECL_DEFER_OUTPUT (r) = 0;
8391         TREE_CHAIN (r) = NULL_TREE;
8392         DECL_PENDING_INLINE_INFO (r) = 0;
8393         DECL_PENDING_INLINE_P (r) = 0;
8394         DECL_SAVED_TREE (r) = NULL_TREE;
8395         DECL_STRUCT_FUNCTION (r) = NULL;
8396         TREE_USED (r) = 0;
8397         if (DECL_CLONED_FUNCTION (r))
8398           {
8399             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
8400                                                args, complain, t);
8401             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
8402             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
8403           }
8404
8405         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8406            this in the special friend case mentioned above where
8407            GEN_TMPL is NULL.  */
8408         if (gen_tmpl)
8409           {
8410             DECL_TEMPLATE_INFO (r)
8411               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8412             SET_DECL_IMPLICIT_INSTANTIATION (r);
8413             register_specialization (r, gen_tmpl, argvec, false);
8414
8415             /* We're not supposed to instantiate default arguments
8416                until they are called, for a template.  But, for a
8417                declaration like:
8418
8419                  template <class T> void f ()
8420                  { extern void g(int i = T()); }
8421
8422                we should do the substitution when the template is
8423                instantiated.  We handle the member function case in
8424                instantiate_class_template since the default arguments
8425                might refer to other members of the class.  */
8426             if (!member
8427                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8428                 && !uses_template_parms (argvec))
8429               tsubst_default_arguments (r);
8430           }
8431         else
8432           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8433
8434         /* Copy the list of befriending classes.  */
8435         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8436              *friends;
8437              friends = &TREE_CHAIN (*friends))
8438           {
8439             *friends = copy_node (*friends);
8440             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8441                                             args, complain,
8442                                             in_decl);
8443           }
8444
8445         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8446           {
8447             maybe_retrofit_in_chrg (r);
8448             if (DECL_CONSTRUCTOR_P (r))
8449               grok_ctor_properties (ctx, r);
8450             /* If this is an instantiation of a member template, clone it.
8451                If it isn't, that'll be handled by
8452                clone_constructors_and_destructors.  */
8453             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8454               clone_function_decl (r, /*update_method_vec_p=*/0);
8455           }
8456         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8457                  && !grok_op_properties (r, (complain & tf_error) != 0))
8458           return error_mark_node;
8459
8460         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8461           SET_DECL_FRIEND_CONTEXT (r,
8462                                    tsubst (DECL_FRIEND_CONTEXT (t),
8463                                             args, complain, in_decl));
8464
8465         /* Possibly limit visibility based on template args.  */
8466         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8467         if (DECL_VISIBILITY_SPECIFIED (t))
8468           {
8469             DECL_VISIBILITY_SPECIFIED (r) = 0;
8470             DECL_ATTRIBUTES (r)
8471               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8472           }
8473         determine_visibility (r);
8474
8475         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8476                                         args, complain, in_decl);
8477       }
8478       break;
8479
8480     case PARM_DECL:
8481       {
8482         tree type = NULL_TREE;
8483         int i, len = 1;
8484         tree expanded_types = NULL_TREE;
8485         tree prev_r = NULL_TREE;
8486         tree first_r = NULL_TREE;
8487
8488         if (FUNCTION_PARAMETER_PACK_P (t))
8489           {
8490             /* If there is a local specialization that isn't a
8491                parameter pack, it means that we're doing a "simple"
8492                substitution from inside tsubst_pack_expansion. Just
8493                return the local specialization (which will be a single
8494                parm).  */
8495             tree spec = retrieve_local_specialization (t);
8496             if (spec 
8497                 && TREE_CODE (spec) == PARM_DECL
8498                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8499               return spec;
8500
8501             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8502                the parameters in this function parameter pack.  */
8503             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8504                                                     complain, in_decl);
8505             if (TREE_CODE (expanded_types) == TREE_VEC)
8506               {
8507                 len = TREE_VEC_LENGTH (expanded_types);
8508
8509                 /* Zero-length parameter packs are boring. Just substitute
8510                    into the chain.  */
8511                 if (len == 0)
8512                   return tsubst (TREE_CHAIN (t), args, complain, 
8513                                  TREE_CHAIN (t));
8514               }
8515             else
8516               {
8517                 /* All we did was update the type. Make a note of that.  */
8518                 type = expanded_types;
8519                 expanded_types = NULL_TREE;
8520               }
8521           }
8522
8523         /* Loop through all of the parameter's we'll build. When T is
8524            a function parameter pack, LEN is the number of expanded
8525            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8526         r = NULL_TREE;
8527         for (i = 0; i < len; ++i)
8528           {
8529             prev_r = r;
8530             r = copy_node (t);
8531             if (DECL_TEMPLATE_PARM_P (t))
8532               SET_DECL_TEMPLATE_PARM_P (r);
8533
8534             if (expanded_types)
8535               /* We're on the Ith parameter of the function parameter
8536                  pack.  */
8537               {
8538                 /* Get the Ith type.  */
8539                 type = TREE_VEC_ELT (expanded_types, i);
8540
8541                 if (DECL_NAME (r))
8542                   /* Rename the parameter to include the index.  */
8543                   DECL_NAME (r) =
8544                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8545               }
8546             else if (!type)
8547               /* We're dealing with a normal parameter.  */
8548               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8549
8550             type = type_decays_to (type);
8551             TREE_TYPE (r) = type;
8552             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8553
8554             if (DECL_INITIAL (r))
8555               {
8556                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8557                   DECL_INITIAL (r) = TREE_TYPE (r);
8558                 else
8559                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8560                                              complain, in_decl);
8561               }
8562
8563             DECL_CONTEXT (r) = NULL_TREE;
8564
8565             if (!DECL_TEMPLATE_PARM_P (r))
8566               DECL_ARG_TYPE (r) = type_passed_as (type);
8567
8568             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8569                                             args, complain, in_decl);
8570
8571             /* Keep track of the first new parameter we
8572                generate. That's what will be returned to the
8573                caller.  */
8574             if (!first_r)
8575               first_r = r;
8576
8577             /* Build a proper chain of parameters when substituting
8578                into a function parameter pack.  */
8579             if (prev_r)
8580               TREE_CHAIN (prev_r) = r;
8581           }
8582
8583         if (TREE_CHAIN (t))
8584           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8585                                    complain, TREE_CHAIN (t));
8586
8587         /* FIRST_R contains the start of the chain we've built.  */
8588         r = first_r;
8589       }
8590       break;
8591
8592     case FIELD_DECL:
8593       {
8594         tree type;
8595
8596         r = copy_decl (t);
8597         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8598         if (type == error_mark_node)
8599           return error_mark_node;
8600         TREE_TYPE (r) = type;
8601         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8602
8603         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8604         DECL_INITIAL (r)
8605           = tsubst_expr (DECL_INITIAL (t), args,
8606                          complain, in_decl,
8607                          /*integral_constant_expression_p=*/true);
8608         /* We don't have to set DECL_CONTEXT here; it is set by
8609            finish_member_declaration.  */
8610         TREE_CHAIN (r) = NULL_TREE;
8611         if (VOID_TYPE_P (type))
8612           error ("instantiation of %q+D as type %qT", r, type);
8613
8614         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8615                                         args, complain, in_decl);
8616       }
8617       break;
8618
8619     case USING_DECL:
8620       /* We reach here only for member using decls.  */
8621       if (DECL_DEPENDENT_P (t))
8622         {
8623           r = do_class_using_decl
8624             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8625              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8626           if (!r)
8627             r = error_mark_node;
8628           else
8629             {
8630               TREE_PROTECTED (r) = TREE_PROTECTED (t);
8631               TREE_PRIVATE (r) = TREE_PRIVATE (t);
8632             }
8633         }
8634       else
8635         {
8636           r = copy_node (t);
8637           TREE_CHAIN (r) = NULL_TREE;
8638         }
8639       break;
8640
8641     case TYPE_DECL:
8642     case VAR_DECL:
8643       {
8644         tree argvec = NULL_TREE;
8645         tree gen_tmpl = NULL_TREE;
8646         tree spec;
8647         tree tmpl = NULL_TREE;
8648         tree ctx;
8649         tree type = NULL_TREE;
8650         bool local_p;
8651
8652         if (TREE_CODE (t) == TYPE_DECL
8653             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8654           {
8655             /* If this is the canonical decl, we don't have to
8656                mess with instantiations, and often we can't (for
8657                typename, template type parms and such).  Note that
8658                TYPE_NAME is not correct for the above test if
8659                we've copied the type for a typedef.  */
8660             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8661             if (type == error_mark_node)
8662               return error_mark_node;
8663             r = TYPE_NAME (type);
8664             break;
8665           }
8666
8667         /* Check to see if we already have the specialization we
8668            need.  */
8669         spec = NULL_TREE;
8670         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8671           {
8672             /* T is a static data member or namespace-scope entity.
8673                We have to substitute into namespace-scope variables
8674                (even though such entities are never templates) because
8675                of cases like:
8676                
8677                  template <class T> void f() { extern T t; }
8678
8679                where the entity referenced is not known until
8680                instantiation time.  */
8681             local_p = false;
8682             ctx = DECL_CONTEXT (t);
8683             if (DECL_CLASS_SCOPE_P (t))
8684               {
8685                 ctx = tsubst_aggr_type (ctx, args,
8686                                         complain,
8687                                         in_decl, /*entering_scope=*/1);
8688                 /* If CTX is unchanged, then T is in fact the
8689                    specialization we want.  That situation occurs when
8690                    referencing a static data member within in its own
8691                    class.  We can use pointer equality, rather than
8692                    same_type_p, because DECL_CONTEXT is always
8693                    canonical.  */
8694                 if (ctx == DECL_CONTEXT (t))
8695                   spec = t;
8696               }
8697
8698             if (!spec)
8699               {
8700                 tmpl = DECL_TI_TEMPLATE (t);
8701                 gen_tmpl = most_general_template (tmpl);
8702                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8703                 spec = (retrieve_specialization 
8704                         (gen_tmpl, argvec,
8705                          /*class_specializations_p=*/false));
8706               }
8707           }
8708         else
8709           {
8710             /* A local variable.  */
8711             local_p = true;
8712             /* Subsequent calls to pushdecl will fill this in.  */
8713             ctx = NULL_TREE;
8714             spec = retrieve_local_specialization (t);
8715           }
8716         /* If we already have the specialization we need, there is
8717            nothing more to do.  */ 
8718         if (spec)
8719           {
8720             r = spec;
8721             break;
8722           }
8723
8724         /* Create a new node for the specialization we need.  */
8725         r = copy_decl (t);
8726         if (type == NULL_TREE)
8727           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8728         if (TREE_CODE (r) == VAR_DECL)
8729           {
8730             /* Even if the original location is out of scope, the
8731                newly substituted one is not.  */
8732             DECL_DEAD_FOR_LOCAL (r) = 0;
8733             DECL_INITIALIZED_P (r) = 0;
8734             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8735             if (type == error_mark_node)
8736               return error_mark_node;
8737             if (TREE_CODE (type) == FUNCTION_TYPE)
8738               {
8739                 /* It may seem that this case cannot occur, since:
8740
8741                      typedef void f();
8742                      void g() { f x; }
8743
8744                    declares a function, not a variable.  However:
8745       
8746                      typedef void f();
8747                      template <typename T> void g() { T t; }
8748                      template void g<f>();
8749
8750                    is an attempt to declare a variable with function
8751                    type.  */
8752                 error ("variable %qD has function type",
8753                        /* R is not yet sufficiently initialized, so we
8754                           just use its name.  */
8755                        DECL_NAME (r));
8756                 return error_mark_node;
8757               }
8758             type = complete_type (type);
8759             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8760               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8761             type = check_var_type (DECL_NAME (r), type);
8762
8763             if (DECL_HAS_VALUE_EXPR_P (t))
8764               {
8765                 tree ve = DECL_VALUE_EXPR (t);
8766                 ve = tsubst_expr (ve, args, complain, in_decl,
8767                                   /*constant_expression_p=*/false);
8768                 SET_DECL_VALUE_EXPR (r, ve);
8769               }
8770           }
8771         else if (DECL_SELF_REFERENCE_P (t))
8772           SET_DECL_SELF_REFERENCE_P (r);
8773         TREE_TYPE (r) = type;
8774         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8775         DECL_CONTEXT (r) = ctx;
8776         /* Clear out the mangled name and RTL for the instantiation.  */
8777         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8778         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8779           SET_DECL_RTL (r, NULL_RTX);
8780         /* The initializer must not be expanded until it is required;
8781            see [temp.inst].  */
8782         DECL_INITIAL (r) = NULL_TREE;
8783         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8784           SET_DECL_RTL (r, NULL_RTX);
8785         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8786         if (TREE_CODE (r) == VAR_DECL)
8787           {
8788             /* Possibly limit visibility based on template args.  */
8789             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8790             if (DECL_VISIBILITY_SPECIFIED (t))
8791               {
8792                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8793                 DECL_ATTRIBUTES (r)
8794                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8795               }
8796             determine_visibility (r);
8797           }
8798         /* Preserve a typedef that names a type.  */
8799         else if (TREE_CODE (r) == TYPE_DECL
8800                  && DECL_ORIGINAL_TYPE (t)
8801                  && type != error_mark_node)
8802           {
8803             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8804                                              args, complain, in_decl);
8805             TREE_TYPE (r) = type = build_variant_type_copy (type);
8806             TYPE_NAME (type) = r;
8807           }
8808
8809         if (!local_p)
8810           {
8811             /* A static data member declaration is always marked
8812                external when it is declared in-class, even if an
8813                initializer is present.  We mimic the non-template
8814                processing here.  */
8815             DECL_EXTERNAL (r) = 1;
8816
8817             register_specialization (r, gen_tmpl, argvec, false);
8818             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8819             SET_DECL_IMPLICIT_INSTANTIATION (r);
8820           }
8821         else
8822           register_local_specialization (r, t);
8823
8824         TREE_CHAIN (r) = NULL_TREE;
8825
8826         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
8827                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
8828                                         args, complain, in_decl);
8829         layout_decl (r, 0);
8830       }
8831       break;
8832
8833     default:
8834       gcc_unreachable ();
8835     }
8836
8837   /* Restore the file and line information.  */
8838   input_location = saved_loc;
8839
8840   return r;
8841 }
8842
8843 /* Substitute into the ARG_TYPES of a function type.  */
8844
8845 static tree
8846 tsubst_arg_types (tree arg_types,
8847                   tree args,
8848                   tsubst_flags_t complain,
8849                   tree in_decl)
8850 {
8851   tree remaining_arg_types;
8852   tree type = NULL_TREE;
8853   int i = 1;
8854   tree expanded_args = NULL_TREE;
8855   tree default_arg;
8856
8857   if (!arg_types || arg_types == void_list_node)
8858     return arg_types;
8859
8860   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8861                                           args, complain, in_decl);
8862   if (remaining_arg_types == error_mark_node)
8863     return error_mark_node;
8864
8865   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8866     {
8867       /* For a pack expansion, perform substitution on the
8868          entire expression. Later on, we'll handle the arguments
8869          one-by-one.  */
8870       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8871                                             args, complain, in_decl);
8872
8873       if (TREE_CODE (expanded_args) == TREE_VEC)
8874         /* So that we'll spin through the parameters, one by one.  */
8875         i = TREE_VEC_LENGTH (expanded_args);
8876       else
8877         {
8878           /* We only partially substituted into the parameter
8879              pack. Our type is TYPE_PACK_EXPANSION.  */
8880           type = expanded_args;
8881           expanded_args = NULL_TREE;
8882         }
8883     }
8884
8885   while (i > 0) {
8886     --i;
8887     
8888     if (expanded_args)
8889       type = TREE_VEC_ELT (expanded_args, i);
8890     else if (!type)
8891       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8892
8893     if (type == error_mark_node)
8894       return error_mark_node;
8895     if (VOID_TYPE_P (type))
8896       {
8897         if (complain & tf_error)
8898           {
8899             error ("invalid parameter type %qT", type);
8900             if (in_decl)
8901               error ("in declaration %q+D", in_decl);
8902           }
8903         return error_mark_node;
8904     }
8905     
8906     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8907        top-level qualifiers as required.  */
8908     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8909
8910     /* We do not substitute into default arguments here.  The standard
8911        mandates that they be instantiated only when needed, which is
8912        done in build_over_call.  */
8913     default_arg = TREE_PURPOSE (arg_types);
8914
8915     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8916       {
8917         /* We've instantiated a template before its default arguments
8918            have been parsed.  This can happen for a nested template
8919            class, and is not an error unless we require the default
8920            argument in a call of this function.  */
8921         remaining_arg_types = 
8922           tree_cons (default_arg, type, remaining_arg_types);
8923         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8924                        remaining_arg_types);
8925       }
8926     else
8927       remaining_arg_types = 
8928         hash_tree_cons (default_arg, type, remaining_arg_types);
8929   }
8930         
8931   return remaining_arg_types;
8932 }
8933
8934 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8935    *not* handle the exception-specification for FNTYPE, because the
8936    initial substitution of explicitly provided template parameters
8937    during argument deduction forbids substitution into the
8938    exception-specification:
8939
8940      [temp.deduct]
8941
8942      All references in the function type of the function template to  the
8943      corresponding template parameters are replaced by the specified tem-
8944      plate argument values.  If a substitution in a template parameter or
8945      in  the function type of the function template results in an invalid
8946      type, type deduction fails.  [Note: The equivalent  substitution  in
8947      exception specifications is done only when the function is instanti-
8948      ated, at which point a program is  ill-formed  if  the  substitution
8949      results in an invalid type.]  */
8950
8951 static tree
8952 tsubst_function_type (tree t,
8953                       tree args,
8954                       tsubst_flags_t complain,
8955                       tree in_decl)
8956 {
8957   tree return_type;
8958   tree arg_types;
8959   tree fntype;
8960
8961   /* The TYPE_CONTEXT is not used for function/method types.  */
8962   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8963
8964   /* Substitute the return type.  */
8965   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8966   if (return_type == error_mark_node)
8967     return error_mark_node;
8968   /* The standard does not presently indicate that creation of a
8969      function type with an invalid return type is a deduction failure.
8970      However, that is clearly analogous to creating an array of "void"
8971      or a reference to a reference.  This is core issue #486.  */
8972   if (TREE_CODE (return_type) == ARRAY_TYPE
8973       || TREE_CODE (return_type) == FUNCTION_TYPE)
8974     {
8975       if (complain & tf_error)
8976         {
8977           if (TREE_CODE (return_type) == ARRAY_TYPE)
8978             error ("function returning an array");
8979           else
8980             error ("function returning a function");
8981         }
8982       return error_mark_node;
8983     }
8984
8985   /* Substitute the argument types.  */
8986   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8987                                 complain, in_decl);
8988   if (arg_types == error_mark_node)
8989     return error_mark_node;
8990
8991   /* Construct a new type node and return it.  */
8992   if (TREE_CODE (t) == FUNCTION_TYPE)
8993     fntype = build_function_type (return_type, arg_types);
8994   else
8995     {
8996       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8997       if (! MAYBE_CLASS_TYPE_P (r))
8998         {
8999           /* [temp.deduct]
9000
9001              Type deduction may fail for any of the following
9002              reasons:
9003
9004              -- Attempting to create "pointer to member of T" when T
9005              is not a class type.  */
9006           if (complain & tf_error)
9007             error ("creating pointer to member function of non-class type %qT",
9008                       r);
9009           return error_mark_node;
9010         }
9011
9012       fntype = build_method_type_directly (r, return_type,
9013                                            TREE_CHAIN (arg_types));
9014     }
9015   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9016   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9017
9018   return fntype;
9019 }
9020
9021 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9022    ARGS into that specification, and return the substituted
9023    specification.  If there is no specification, return NULL_TREE.  */
9024
9025 static tree
9026 tsubst_exception_specification (tree fntype,
9027                                 tree args,
9028                                 tsubst_flags_t complain,
9029                                 tree in_decl)
9030 {
9031   tree specs;
9032   tree new_specs;
9033
9034   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9035   new_specs = NULL_TREE;
9036   if (specs)
9037     {
9038       if (! TREE_VALUE (specs))
9039         new_specs = specs;
9040       else
9041         while (specs)
9042           {
9043             tree spec;
9044             int i, len = 1;
9045             tree expanded_specs = NULL_TREE;
9046
9047             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9048               {
9049                 /* Expand the pack expansion type.  */
9050                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9051                                                        args, complain,
9052                                                        in_decl);
9053
9054                 if (expanded_specs == error_mark_node)
9055                   return error_mark_node;
9056                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9057                   len = TREE_VEC_LENGTH (expanded_specs);
9058                 else
9059                   {
9060                     /* We're substituting into a member template, so
9061                        we got a TYPE_PACK_EXPANSION back.  Add that
9062                        expansion and move on.  */
9063                     gcc_assert (TREE_CODE (expanded_specs) 
9064                                 == TYPE_PACK_EXPANSION);
9065                     new_specs = add_exception_specifier (new_specs,
9066                                                          expanded_specs,
9067                                                          complain);
9068                     specs = TREE_CHAIN (specs);
9069                     continue;
9070                   }
9071               }
9072
9073             for (i = 0; i < len; ++i)
9074               {
9075                 if (expanded_specs)
9076                   spec = TREE_VEC_ELT (expanded_specs, i);
9077                 else
9078                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9079                 if (spec == error_mark_node)
9080                   return spec;
9081                 new_specs = add_exception_specifier (new_specs, spec, 
9082                                                      complain);
9083               }
9084
9085             specs = TREE_CHAIN (specs);
9086           }
9087     }
9088   return new_specs;
9089 }
9090
9091 /* Take the tree structure T and replace template parameters used
9092    therein with the argument vector ARGS.  IN_DECL is an associated
9093    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9094    Issue error and warning messages under control of COMPLAIN.  Note
9095    that we must be relatively non-tolerant of extensions here, in
9096    order to preserve conformance; if we allow substitutions that
9097    should not be allowed, we may allow argument deductions that should
9098    not succeed, and therefore report ambiguous overload situations
9099    where there are none.  In theory, we could allow the substitution,
9100    but indicate that it should have failed, and allow our caller to
9101    make sure that the right thing happens, but we don't try to do this
9102    yet.
9103
9104    This function is used for dealing with types, decls and the like;
9105    for expressions, use tsubst_expr or tsubst_copy.  */
9106
9107 static tree
9108 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9109 {
9110   tree type, r;
9111
9112   if (t == NULL_TREE || t == error_mark_node
9113       || t == integer_type_node
9114       || t == void_type_node
9115       || t == char_type_node
9116       || t == unknown_type_node
9117       || TREE_CODE (t) == NAMESPACE_DECL)
9118     return t;
9119
9120   if (DECL_P (t))
9121     return tsubst_decl (t, args, complain);
9122
9123   if (args == NULL_TREE)
9124     return t;
9125
9126   if (TREE_CODE (t) == IDENTIFIER_NODE)
9127     type = IDENTIFIER_TYPE_VALUE (t);
9128   else
9129     type = TREE_TYPE (t);
9130
9131   gcc_assert (type != unknown_type_node);
9132
9133   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9134      such as attribute aligned.  */
9135   if (TYPE_P (t)
9136       && TYPE_NAME (t)
9137       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9138     {
9139       tree decl = TYPE_NAME (t);
9140       
9141       if (DECL_CLASS_SCOPE_P (decl)
9142           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9143           && uses_template_parms (DECL_CONTEXT (decl)))
9144         {
9145           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9146           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9147           r = retrieve_specialization (tmpl, gen_args, false);
9148         }
9149       else if (DECL_FUNCTION_SCOPE_P (decl)
9150                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9151                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9152         r = retrieve_local_specialization (decl);
9153       else
9154         /* The typedef is from a non-template context.  */
9155         return t;
9156
9157       if (r)
9158         {
9159           r = TREE_TYPE (r);
9160           r = cp_build_qualified_type_real
9161             (r, cp_type_quals (t) | cp_type_quals (r),
9162              complain | tf_ignore_bad_quals);
9163           return r;
9164         }
9165       /* Else we must be instantiating the typedef, so fall through.  */
9166     }
9167
9168   if (type
9169       && TREE_CODE (t) != TYPENAME_TYPE
9170       && TREE_CODE (t) != IDENTIFIER_NODE
9171       && TREE_CODE (t) != FUNCTION_TYPE
9172       && TREE_CODE (t) != METHOD_TYPE)
9173     type = tsubst (type, args, complain, in_decl);
9174   if (type == error_mark_node)
9175     return error_mark_node;
9176
9177   switch (TREE_CODE (t))
9178     {
9179     case RECORD_TYPE:
9180     case UNION_TYPE:
9181     case ENUMERAL_TYPE:
9182       return tsubst_aggr_type (t, args, complain, in_decl,
9183                                /*entering_scope=*/0);
9184
9185     case ERROR_MARK:
9186     case IDENTIFIER_NODE:
9187     case VOID_TYPE:
9188     case REAL_TYPE:
9189     case COMPLEX_TYPE:
9190     case VECTOR_TYPE:
9191     case BOOLEAN_TYPE:
9192     case INTEGER_CST:
9193     case REAL_CST:
9194     case STRING_CST:
9195       return t;
9196
9197     case INTEGER_TYPE:
9198       if (t == integer_type_node)
9199         return t;
9200
9201       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9202           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9203         return t;
9204
9205       {
9206         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9207
9208         max = tsubst_expr (omax, args, complain, in_decl,
9209                            /*integral_constant_expression_p=*/false);
9210
9211         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9212            needed.  */
9213         if (TREE_CODE (max) == NOP_EXPR
9214             && TREE_SIDE_EFFECTS (omax)
9215             && !TREE_TYPE (max))
9216           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9217
9218         max = fold_decl_constant_value (max);
9219
9220         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9221            with TREE_SIDE_EFFECTS that indicates this is not an integral
9222            constant expression.  */
9223         if (processing_template_decl
9224             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9225           {
9226             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9227             TREE_SIDE_EFFECTS (max) = 1;
9228           }
9229
9230         if (TREE_CODE (max) != INTEGER_CST
9231             && !at_function_scope_p ()
9232             && !TREE_SIDE_EFFECTS (max)
9233             && !value_dependent_expression_p (max))
9234           {
9235             if (complain & tf_error)
9236               error ("array bound is not an integer constant");
9237             return error_mark_node;
9238           }
9239
9240         /* [temp.deduct]
9241
9242            Type deduction may fail for any of the following
9243            reasons:
9244
9245              Attempting to create an array with a size that is
9246              zero or negative.  */
9247         if (integer_zerop (max) && !(complain & tf_error))
9248           /* We must fail if performing argument deduction (as
9249              indicated by the state of complain), so that
9250              another substitution can be found.  */
9251           return error_mark_node;
9252         else if (TREE_CODE (max) == INTEGER_CST
9253                  && INT_CST_LT (max, integer_zero_node))
9254           {
9255             if (complain & tf_error)
9256               error ("creating array with negative size (%qE)", max);
9257
9258             return error_mark_node;
9259           }
9260
9261         return compute_array_index_type (NULL_TREE, max);
9262       }
9263
9264     case TEMPLATE_TYPE_PARM:
9265     case TEMPLATE_TEMPLATE_PARM:
9266     case BOUND_TEMPLATE_TEMPLATE_PARM:
9267     case TEMPLATE_PARM_INDEX:
9268       {
9269         int idx;
9270         int level;
9271         int levels;
9272         tree arg = NULL_TREE;
9273
9274         r = NULL_TREE;
9275
9276         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9277         template_parm_level_and_index (t, &level, &idx); 
9278
9279         levels = TMPL_ARGS_DEPTH (args);
9280         if (level <= levels)
9281           {
9282             arg = TMPL_ARG (args, level, idx);
9283
9284             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9285               /* See through ARGUMENT_PACK_SELECT arguments. */
9286               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9287           }
9288
9289         if (arg == error_mark_node)
9290           return error_mark_node;
9291         else if (arg != NULL_TREE)
9292           {
9293             if (ARGUMENT_PACK_P (arg))
9294               /* If ARG is an argument pack, we don't actually want to
9295                  perform a substitution here, because substitutions
9296                  for argument packs are only done
9297                  element-by-element. We can get to this point when
9298                  substituting the type of a non-type template
9299                  parameter pack, when that type actually contains
9300                  template parameter packs from an outer template, e.g.,
9301
9302                  template<typename... Types> struct A {
9303                    template<Types... Values> struct B { };
9304                  };  */
9305               return t;
9306
9307             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9308               {
9309                 int quals;
9310                 gcc_assert (TYPE_P (arg));
9311
9312                 /* cv-quals from the template are discarded when
9313                    substituting in a function or reference type.  */
9314                 if (TREE_CODE (arg) == FUNCTION_TYPE
9315                     || TREE_CODE (arg) == METHOD_TYPE
9316                     || TREE_CODE (arg) == REFERENCE_TYPE)
9317                   quals = cp_type_quals (arg);
9318                 else
9319                   quals = cp_type_quals (arg) | cp_type_quals (t);
9320                   
9321                 return cp_build_qualified_type_real
9322                   (arg, quals, complain | tf_ignore_bad_quals);
9323               }
9324             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9325               {
9326                 /* We are processing a type constructed from a
9327                    template template parameter.  */
9328                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9329                                       args, complain, in_decl);
9330                 if (argvec == error_mark_node)
9331                   return error_mark_node;
9332
9333                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9334                    are resolving nested-types in the signature of a
9335                    member function templates.  Otherwise ARG is a
9336                    TEMPLATE_DECL and is the real template to be
9337                    instantiated.  */
9338                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9339                   arg = TYPE_NAME (arg);
9340
9341                 r = lookup_template_class (arg,
9342                                            argvec, in_decl,
9343                                            DECL_CONTEXT (arg),
9344                                             /*entering_scope=*/0,
9345                                            complain);
9346                 return cp_build_qualified_type_real
9347                   (r, TYPE_QUALS (t), complain);
9348               }
9349             else
9350               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9351               return arg;
9352           }
9353
9354         if (level == 1)
9355           /* This can happen during the attempted tsubst'ing in
9356              unify.  This means that we don't yet have any information
9357              about the template parameter in question.  */
9358           return t;
9359
9360         /* If we get here, we must have been looking at a parm for a
9361            more deeply nested template.  Make a new version of this
9362            template parameter, but with a lower level.  */
9363         switch (TREE_CODE (t))
9364           {
9365           case TEMPLATE_TYPE_PARM:
9366           case TEMPLATE_TEMPLATE_PARM:
9367           case BOUND_TEMPLATE_TEMPLATE_PARM:
9368             if (cp_type_quals (t))
9369               {
9370                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9371                 r = cp_build_qualified_type_real
9372                   (r, cp_type_quals (t),
9373                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9374                                ? tf_ignore_bad_quals : 0));
9375               }
9376             else
9377               {
9378                 r = copy_type (t);
9379                 TEMPLATE_TYPE_PARM_INDEX (r)
9380                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9381                                                 r, levels, args, complain);
9382                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9383                 TYPE_MAIN_VARIANT (r) = r;
9384                 TYPE_POINTER_TO (r) = NULL_TREE;
9385                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9386
9387                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9388                   /* We have reduced the level of the template
9389                      template parameter, but not the levels of its
9390                      template parameters, so canonical_type_parameter
9391                      will not be able to find the canonical template
9392                      template parameter for this level. Thus, we
9393                      require structural equality checking to compare
9394                      TEMPLATE_TEMPLATE_PARMs. */
9395                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9396                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9397                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9398                 else
9399                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9400
9401                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9402                   {
9403                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9404                                           complain, in_decl);
9405                     if (argvec == error_mark_node)
9406                       return error_mark_node;
9407
9408                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9409                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9410                   }
9411               }
9412             break;
9413
9414           case TEMPLATE_PARM_INDEX:
9415             r = reduce_template_parm_level (t, type, levels, args, complain);
9416             break;
9417
9418           default:
9419             gcc_unreachable ();
9420           }
9421
9422         return r;
9423       }
9424
9425     case TREE_LIST:
9426       {
9427         tree purpose, value, chain;
9428
9429         if (t == void_list_node)
9430           return t;
9431
9432         purpose = TREE_PURPOSE (t);
9433         if (purpose)
9434           {
9435             purpose = tsubst (purpose, args, complain, in_decl);
9436             if (purpose == error_mark_node)
9437               return error_mark_node;
9438           }
9439         value = TREE_VALUE (t);
9440         if (value)
9441           {
9442             value = tsubst (value, args, complain, in_decl);
9443             if (value == error_mark_node)
9444               return error_mark_node;
9445           }
9446         chain = TREE_CHAIN (t);
9447         if (chain && chain != void_type_node)
9448           {
9449             chain = tsubst (chain, args, complain, in_decl);
9450             if (chain == error_mark_node)
9451               return error_mark_node;
9452           }
9453         if (purpose == TREE_PURPOSE (t)
9454             && value == TREE_VALUE (t)
9455             && chain == TREE_CHAIN (t))
9456           return t;
9457         return hash_tree_cons (purpose, value, chain);
9458       }
9459
9460     case TREE_BINFO:
9461       /* We should never be tsubsting a binfo.  */
9462       gcc_unreachable ();
9463
9464     case TREE_VEC:
9465       /* A vector of template arguments.  */
9466       gcc_assert (!type);
9467       return tsubst_template_args (t, args, complain, in_decl);
9468
9469     case POINTER_TYPE:
9470     case REFERENCE_TYPE:
9471       {
9472         enum tree_code code;
9473
9474         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9475           return t;
9476
9477         code = TREE_CODE (t);
9478
9479
9480         /* [temp.deduct]
9481
9482            Type deduction may fail for any of the following
9483            reasons:
9484
9485            -- Attempting to create a pointer to reference type.
9486            -- Attempting to create a reference to a reference type or
9487               a reference to void.
9488
9489           Core issue 106 says that creating a reference to a reference
9490           during instantiation is no longer a cause for failure. We
9491           only enforce this check in strict C++98 mode.  */
9492         if ((TREE_CODE (type) == REFERENCE_TYPE
9493              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9494             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9495           {
9496             static location_t last_loc;
9497
9498             /* We keep track of the last time we issued this error
9499                message to avoid spewing a ton of messages during a
9500                single bad template instantiation.  */
9501             if (complain & tf_error
9502                 && last_loc != input_location)
9503               {
9504                 if (TREE_CODE (type) == VOID_TYPE)
9505                   error ("forming reference to void");
9506                 else
9507                   error ("forming %s to reference type %qT",
9508                          (code == POINTER_TYPE) ? "pointer" : "reference",
9509                          type);
9510                 last_loc = input_location;
9511               }
9512
9513             return error_mark_node;
9514           }
9515         else if (code == POINTER_TYPE)
9516           {
9517             r = build_pointer_type (type);
9518             if (TREE_CODE (type) == METHOD_TYPE)
9519               r = build_ptrmemfunc_type (r);
9520           }
9521         else if (TREE_CODE (type) == REFERENCE_TYPE)
9522           /* In C++0x, during template argument substitution, when there is an
9523              attempt to create a reference to a reference type, reference
9524              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9525
9526              "If a template-argument for a template-parameter T names a type
9527              that is a reference to a type A, an attempt to create the type
9528              'lvalue reference to cv T' creates the type 'lvalue reference to
9529              A,' while an attempt to create the type type rvalue reference to
9530              cv T' creates the type T"
9531           */
9532           r = cp_build_reference_type
9533               (TREE_TYPE (type),
9534                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9535         else
9536           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9537         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9538
9539         if (r != error_mark_node)
9540           /* Will this ever be needed for TYPE_..._TO values?  */
9541           layout_type (r);
9542
9543         return r;
9544       }
9545     case OFFSET_TYPE:
9546       {
9547         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9548         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9549           {
9550             /* [temp.deduct]
9551
9552                Type deduction may fail for any of the following
9553                reasons:
9554
9555                -- Attempting to create "pointer to member of T" when T
9556                   is not a class type.  */
9557             if (complain & tf_error)
9558               error ("creating pointer to member of non-class type %qT", r);
9559             return error_mark_node;
9560           }
9561         if (TREE_CODE (type) == REFERENCE_TYPE)
9562           {
9563             if (complain & tf_error)
9564               error ("creating pointer to member reference type %qT", type);
9565             return error_mark_node;
9566           }
9567         if (TREE_CODE (type) == VOID_TYPE)
9568           {
9569             if (complain & tf_error)
9570               error ("creating pointer to member of type void");
9571             return error_mark_node;
9572           }
9573         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9574         if (TREE_CODE (type) == FUNCTION_TYPE)
9575           {
9576             /* The type of the implicit object parameter gets its
9577                cv-qualifiers from the FUNCTION_TYPE. */
9578             tree method_type;
9579             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9580                                                       cp_type_quals (type));
9581             tree memptr;
9582             method_type = build_method_type_directly (this_type,
9583                                                       TREE_TYPE (type),
9584                                                       TYPE_ARG_TYPES (type));
9585             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9586             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9587                                                  complain);
9588           }
9589         else
9590           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9591                                                TYPE_QUALS (t),
9592                                                complain);
9593       }
9594     case FUNCTION_TYPE:
9595     case METHOD_TYPE:
9596       {
9597         tree fntype;
9598         tree specs;
9599         fntype = tsubst_function_type (t, args, complain, in_decl);
9600         if (fntype == error_mark_node)
9601           return error_mark_node;
9602
9603         /* Substitute the exception specification.  */
9604         specs = tsubst_exception_specification (t, args, complain,
9605                                                 in_decl);
9606         if (specs == error_mark_node)
9607           return error_mark_node;
9608         if (specs)
9609           fntype = build_exception_variant (fntype, specs);
9610         return fntype;
9611       }
9612     case ARRAY_TYPE:
9613       {
9614         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9615         if (domain == error_mark_node)
9616           return error_mark_node;
9617
9618         /* As an optimization, we avoid regenerating the array type if
9619            it will obviously be the same as T.  */
9620         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9621           return t;
9622
9623         /* These checks should match the ones in grokdeclarator.
9624
9625            [temp.deduct]
9626
9627            The deduction may fail for any of the following reasons:
9628
9629            -- Attempting to create an array with an element type that
9630               is void, a function type, or a reference type, or [DR337]
9631               an abstract class type.  */
9632         if (TREE_CODE (type) == VOID_TYPE
9633             || TREE_CODE (type) == FUNCTION_TYPE
9634             || TREE_CODE (type) == REFERENCE_TYPE)
9635           {
9636             if (complain & tf_error)
9637               error ("creating array of %qT", type);
9638             return error_mark_node;
9639           }
9640         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9641           {
9642             if (complain & tf_error)
9643               error ("creating array of %qT, which is an abstract class type",
9644                      type);
9645             return error_mark_node;
9646           }
9647
9648         r = build_cplus_array_type (type, domain);
9649
9650         if (TYPE_USER_ALIGN (t))
9651           {
9652             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9653             TYPE_USER_ALIGN (r) = 1;
9654           }
9655
9656         return r;
9657       }
9658
9659     case PLUS_EXPR:
9660     case MINUS_EXPR:
9661       {
9662         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9663         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9664
9665         if (e1 == error_mark_node || e2 == error_mark_node)
9666           return error_mark_node;
9667
9668         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9669       }
9670
9671     case NEGATE_EXPR:
9672     case NOP_EXPR:
9673       {
9674         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9675         if (e == error_mark_node)
9676           return error_mark_node;
9677
9678         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9679       }
9680
9681     case TYPENAME_TYPE:
9682       {
9683         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9684                                      in_decl, /*entering_scope=*/1);
9685         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9686                               complain, in_decl);
9687
9688         if (ctx == error_mark_node || f == error_mark_node)
9689           return error_mark_node;
9690
9691         if (!MAYBE_CLASS_TYPE_P (ctx))
9692           {
9693             if (complain & tf_error)
9694               error ("%qT is not a class, struct, or union type", ctx);
9695             return error_mark_node;
9696           }
9697         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9698           {
9699             /* Normally, make_typename_type does not require that the CTX
9700                have complete type in order to allow things like:
9701
9702                  template <class T> struct S { typename S<T>::X Y; };
9703
9704                But, such constructs have already been resolved by this
9705                point, so here CTX really should have complete type, unless
9706                it's a partial instantiation.  */
9707             ctx = complete_type (ctx);
9708             if (!COMPLETE_TYPE_P (ctx))
9709               {
9710                 if (complain & tf_error)
9711                   cxx_incomplete_type_error (NULL_TREE, ctx);
9712                 return error_mark_node;
9713               }
9714           }
9715
9716         f = make_typename_type (ctx, f, typename_type,
9717                                 (complain & tf_error) | tf_keep_type_decl);
9718         if (f == error_mark_node)
9719           return f;
9720         if (TREE_CODE (f) == TYPE_DECL)
9721           {
9722             complain |= tf_ignore_bad_quals;
9723             f = TREE_TYPE (f);
9724           }
9725
9726         if (TREE_CODE (f) != TYPENAME_TYPE)
9727           {
9728             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9729               error ("%qT resolves to %qT, which is not an enumeration type",
9730                      t, f);
9731             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9732               error ("%qT resolves to %qT, which is is not a class type",
9733                      t, f);
9734           }
9735
9736         return cp_build_qualified_type_real
9737           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9738       }
9739
9740     case UNBOUND_CLASS_TEMPLATE:
9741       {
9742         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9743                                      in_decl, /*entering_scope=*/1);
9744         tree name = TYPE_IDENTIFIER (t);
9745         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9746
9747         if (ctx == error_mark_node || name == error_mark_node)
9748           return error_mark_node;
9749
9750         if (parm_list)
9751           parm_list = tsubst_template_parms (parm_list, args, complain);
9752         return make_unbound_class_template (ctx, name, parm_list, complain);
9753       }
9754
9755     case INDIRECT_REF:
9756     case ADDR_EXPR:
9757     case CALL_EXPR:
9758       gcc_unreachable ();
9759
9760     case ARRAY_REF:
9761       {
9762         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9763         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9764                                /*integral_constant_expression_p=*/false);
9765         if (e1 == error_mark_node || e2 == error_mark_node)
9766           return error_mark_node;
9767
9768         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9769       }
9770
9771     case SCOPE_REF:
9772       {
9773         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9774         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9775         if (e1 == error_mark_node || e2 == error_mark_node)
9776           return error_mark_node;
9777
9778         return build_qualified_name (/*type=*/NULL_TREE,
9779                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9780       }
9781
9782     case TYPEOF_TYPE:
9783       {
9784         tree type;
9785
9786         type = finish_typeof (tsubst_expr 
9787                               (TYPEOF_TYPE_EXPR (t), args,
9788                                complain, in_decl,
9789                                /*integral_constant_expression_p=*/false));
9790         return cp_build_qualified_type_real (type,
9791                                              cp_type_quals (t)
9792                                              | cp_type_quals (type),
9793                                              complain);
9794       }
9795
9796     case DECLTYPE_TYPE:
9797       {
9798         tree type;
9799
9800         ++skip_evaluation;
9801
9802         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
9803                             complain, in_decl,
9804                             /*integral_constant_expression_p=*/false);
9805
9806         --skip_evaluation;
9807
9808         type =
9809           finish_decltype_type (type,
9810                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9811         return cp_build_qualified_type_real (type,
9812                                              cp_type_quals (t)
9813                                              | cp_type_quals (type),
9814                                              complain);
9815       }
9816
9817     case TYPE_ARGUMENT_PACK:
9818     case NONTYPE_ARGUMENT_PACK:
9819       {
9820         tree r = make_node (TREE_CODE (t));
9821         tree packed_out = 
9822           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9823                                 args,
9824                                 complain,
9825                                 in_decl);
9826         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9827
9828         /* For template nontype argument packs, also substitute into
9829            the type.  */
9830         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9831           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9832
9833         return r;
9834       }
9835       break;
9836
9837     default:
9838       sorry ("use of %qs in template",
9839              tree_code_name [(int) TREE_CODE (t)]);
9840       return error_mark_node;
9841     }
9842 }
9843
9844 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9845    type of the expression on the left-hand side of the "." or "->"
9846    operator.  */
9847
9848 static tree
9849 tsubst_baselink (tree baselink, tree object_type,
9850                  tree args, tsubst_flags_t complain, tree in_decl)
9851 {
9852     tree name;
9853     tree qualifying_scope;
9854     tree fns;
9855     tree optype;
9856     tree template_args = 0;
9857     bool template_id_p = false;
9858
9859     /* A baselink indicates a function from a base class.  Both the
9860        BASELINK_ACCESS_BINFO and the base class referenced may
9861        indicate bases of the template class, rather than the
9862        instantiated class.  In addition, lookups that were not
9863        ambiguous before may be ambiguous now.  Therefore, we perform
9864        the lookup again.  */
9865     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9866     qualifying_scope = tsubst (qualifying_scope, args,
9867                                complain, in_decl);
9868     fns = BASELINK_FUNCTIONS (baselink);
9869     optype = BASELINK_OPTYPE (baselink);
9870     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9871       {
9872         template_id_p = true;
9873         template_args = TREE_OPERAND (fns, 1);
9874         fns = TREE_OPERAND (fns, 0);
9875         if (template_args)
9876           template_args = tsubst_template_args (template_args, args,
9877                                                 complain, in_decl);
9878       }
9879     name = DECL_NAME (get_first_fn (fns));
9880     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9881
9882     /* If lookup found a single function, mark it as used at this
9883        point.  (If it lookup found multiple functions the one selected
9884        later by overload resolution will be marked as used at that
9885        point.)  */
9886     if (BASELINK_P (baselink))
9887       fns = BASELINK_FUNCTIONS (baselink);
9888     if (!template_id_p && !really_overloaded_fn (fns))
9889       mark_used (OVL_CURRENT (fns));
9890
9891     /* Add back the template arguments, if present.  */
9892     if (BASELINK_P (baselink) && template_id_p)
9893       BASELINK_FUNCTIONS (baselink)
9894         = build_nt (TEMPLATE_ID_EXPR,
9895                     BASELINK_FUNCTIONS (baselink),
9896                     template_args);
9897     /* Update the conversion operator type.  */
9898     BASELINK_OPTYPE (baselink) 
9899       = tsubst (optype, args, complain, in_decl);
9900
9901     if (!object_type)
9902       object_type = current_class_type;
9903     return adjust_result_of_qualified_name_lookup (baselink,
9904                                                    qualifying_scope,
9905                                                    object_type);
9906 }
9907
9908 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9909    true if the qualified-id will be a postfix-expression in-and-of
9910    itself; false if more of the postfix-expression follows the
9911    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9912    of "&".  */
9913
9914 static tree
9915 tsubst_qualified_id (tree qualified_id, tree args,
9916                      tsubst_flags_t complain, tree in_decl,
9917                      bool done, bool address_p)
9918 {
9919   tree expr;
9920   tree scope;
9921   tree name;
9922   bool is_template;
9923   tree template_args;
9924
9925   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9926
9927   /* Figure out what name to look up.  */
9928   name = TREE_OPERAND (qualified_id, 1);
9929   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9930     {
9931       is_template = true;
9932       template_args = TREE_OPERAND (name, 1);
9933       if (template_args)
9934         template_args = tsubst_template_args (template_args, args,
9935                                               complain, in_decl);
9936       name = TREE_OPERAND (name, 0);
9937     }
9938   else
9939     {
9940       is_template = false;
9941       template_args = NULL_TREE;
9942     }
9943
9944   /* Substitute into the qualifying scope.  When there are no ARGS, we
9945      are just trying to simplify a non-dependent expression.  In that
9946      case the qualifying scope may be dependent, and, in any case,
9947      substituting will not help.  */
9948   scope = TREE_OPERAND (qualified_id, 0);
9949   if (args)
9950     {
9951       scope = tsubst (scope, args, complain, in_decl);
9952       expr = tsubst_copy (name, args, complain, in_decl);
9953     }
9954   else
9955     expr = name;
9956
9957   if (dependent_type_p (scope))
9958     return build_qualified_name (/*type=*/NULL_TREE,
9959                                  scope, expr,
9960                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9961
9962   if (!BASELINK_P (name) && !DECL_P (expr))
9963     {
9964       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9965         /* If this were actually a destructor call, it would have been
9966            parsed as such by the parser.  */
9967         expr = error_mark_node;
9968       else
9969         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9970       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9971                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9972         {
9973           if (complain & tf_error)
9974             {
9975               error ("dependent-name %qE is parsed as a non-type, but "
9976                      "instantiation yields a type", qualified_id);
9977               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
9978             }
9979           return error_mark_node;
9980         }
9981     }
9982
9983   if (DECL_P (expr))
9984     {
9985       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9986                                            scope);
9987       /* Remember that there was a reference to this entity.  */
9988       mark_used (expr);
9989     }
9990
9991   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9992     {
9993       if (complain & tf_error)
9994         qualified_name_lookup_error (scope,
9995                                      TREE_OPERAND (qualified_id, 1),
9996                                      expr, input_location);
9997       return error_mark_node;
9998     }
9999
10000   if (is_template)
10001     expr = lookup_template_function (expr, template_args);
10002
10003   if (expr == error_mark_node && complain & tf_error)
10004     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10005                                  expr, input_location);
10006   else if (TYPE_P (scope))
10007     {
10008       expr = (adjust_result_of_qualified_name_lookup
10009               (expr, scope, current_class_type));
10010       expr = (finish_qualified_id_expr
10011               (scope, expr, done, address_p,
10012                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10013                /*template_arg_p=*/false));
10014     }
10015
10016   /* Expressions do not generally have reference type.  */
10017   if (TREE_CODE (expr) != SCOPE_REF
10018       /* However, if we're about to form a pointer-to-member, we just
10019          want the referenced member referenced.  */
10020       && TREE_CODE (expr) != OFFSET_REF)
10021     expr = convert_from_reference (expr);
10022
10023   return expr;
10024 }
10025
10026 /* Like tsubst, but deals with expressions.  This function just replaces
10027    template parms; to finish processing the resultant expression, use
10028    tsubst_expr.  */
10029
10030 static tree
10031 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10032 {
10033   enum tree_code code;
10034   tree r;
10035
10036   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10037     return t;
10038
10039   code = TREE_CODE (t);
10040
10041   switch (code)
10042     {
10043     case PARM_DECL:
10044       r = retrieve_local_specialization (t);
10045
10046       if (r == NULL)
10047         {
10048           tree c;
10049           /* This can happen for a parameter name used later in a function
10050              declaration (such as in a late-specified return type).  Just
10051              make a dummy decl, since it's only used for its type.  */
10052           gcc_assert (skip_evaluation);   
10053           /* We copy T because want to tsubst the PARM_DECL only,
10054              not the following PARM_DECLs that are chained to T.  */
10055           c = copy_node (t);
10056           r = tsubst_decl (c, args, complain);
10057           /* Give it the template pattern as its context; its true context
10058              hasn't been instantiated yet and this is good enough for
10059              mangling.  */
10060           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10061         }
10062       
10063       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10064         r = ARGUMENT_PACK_SELECT_ARG (r);
10065       mark_used (r);
10066       return r;
10067
10068     case CONST_DECL:
10069       {
10070         tree enum_type;
10071         tree v;
10072
10073         if (DECL_TEMPLATE_PARM_P (t))
10074           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10075         /* There is no need to substitute into namespace-scope
10076            enumerators.  */
10077         if (DECL_NAMESPACE_SCOPE_P (t))
10078           return t;
10079         /* If ARGS is NULL, then T is known to be non-dependent.  */
10080         if (args == NULL_TREE)
10081           return integral_constant_value (t);
10082
10083         /* Unfortunately, we cannot just call lookup_name here.
10084            Consider:
10085
10086              template <int I> int f() {
10087              enum E { a = I };
10088              struct S { void g() { E e = a; } };
10089              };
10090
10091            When we instantiate f<7>::S::g(), say, lookup_name is not
10092            clever enough to find f<7>::a.  */
10093         enum_type
10094           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10095                               /*entering_scope=*/0);
10096
10097         for (v = TYPE_VALUES (enum_type);
10098              v != NULL_TREE;
10099              v = TREE_CHAIN (v))
10100           if (TREE_PURPOSE (v) == DECL_NAME (t))
10101             return TREE_VALUE (v);
10102
10103           /* We didn't find the name.  That should never happen; if
10104              name-lookup found it during preliminary parsing, we
10105              should find it again here during instantiation.  */
10106         gcc_unreachable ();
10107       }
10108       return t;
10109
10110     case FIELD_DECL:
10111       if (DECL_CONTEXT (t))
10112         {
10113           tree ctx;
10114
10115           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10116                                   /*entering_scope=*/1);
10117           if (ctx != DECL_CONTEXT (t))
10118             {
10119               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10120               if (!r)
10121                 {
10122                   if (complain & tf_error)
10123                     error ("using invalid field %qD", t);
10124                   return error_mark_node;
10125                 }
10126               return r;
10127             }
10128         }
10129
10130       return t;
10131
10132     case VAR_DECL:
10133     case FUNCTION_DECL:
10134       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10135           || local_variable_p (t))
10136         t = tsubst (t, args, complain, in_decl);
10137       mark_used (t);
10138       return t;
10139
10140     case BASELINK:
10141       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10142
10143     case TEMPLATE_DECL:
10144       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10145         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10146                        args, complain, in_decl);
10147       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10148         return tsubst (t, args, complain, in_decl);
10149       else if (DECL_CLASS_SCOPE_P (t)
10150                && uses_template_parms (DECL_CONTEXT (t)))
10151         {
10152           /* Template template argument like the following example need
10153              special treatment:
10154
10155                template <template <class> class TT> struct C {};
10156                template <class T> struct D {
10157                  template <class U> struct E {};
10158                  C<E> c;                                // #1
10159                };
10160                D<int> d;                                // #2
10161
10162              We are processing the template argument `E' in #1 for
10163              the template instantiation #2.  Originally, `E' is a
10164              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10165              have to substitute this with one having context `D<int>'.  */
10166
10167           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10168           return lookup_field (context, DECL_NAME(t), 0, false);
10169         }
10170       else
10171         /* Ordinary template template argument.  */
10172         return t;
10173
10174     case CAST_EXPR:
10175     case REINTERPRET_CAST_EXPR:
10176     case CONST_CAST_EXPR:
10177     case STATIC_CAST_EXPR:
10178     case DYNAMIC_CAST_EXPR:
10179     case NOP_EXPR:
10180       return build1
10181         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10182          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10183
10184     case SIZEOF_EXPR:
10185       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10186         {
10187           /* We only want to compute the number of arguments.  */
10188           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10189                                                 complain, in_decl);
10190           int len = 0;
10191
10192           if (TREE_CODE (expanded) == TREE_VEC)
10193             len = TREE_VEC_LENGTH (expanded);
10194
10195           if (expanded == error_mark_node)
10196             return error_mark_node;
10197           else if (PACK_EXPANSION_P (expanded)
10198                    || (TREE_CODE (expanded) == TREE_VEC
10199                        && len > 0
10200                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10201             {
10202               if (TREE_CODE (expanded) == TREE_VEC)
10203                 expanded = TREE_VEC_ELT (expanded, len - 1);
10204
10205               if (TYPE_P (expanded))
10206                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10207                                                    complain & tf_error);
10208               else
10209                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10210                                                    complain & tf_error);
10211             }
10212           else
10213             return build_int_cst (size_type_node, len);
10214         }
10215       /* Fall through */
10216
10217     case INDIRECT_REF:
10218     case NEGATE_EXPR:
10219     case TRUTH_NOT_EXPR:
10220     case BIT_NOT_EXPR:
10221     case ADDR_EXPR:
10222     case UNARY_PLUS_EXPR:      /* Unary + */
10223     case ALIGNOF_EXPR:
10224     case ARROW_EXPR:
10225     case THROW_EXPR:
10226     case TYPEID_EXPR:
10227     case REALPART_EXPR:
10228     case IMAGPART_EXPR:
10229       return build1
10230         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10231          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10232
10233     case COMPONENT_REF:
10234       {
10235         tree object;
10236         tree name;
10237
10238         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10239         name = TREE_OPERAND (t, 1);
10240         if (TREE_CODE (name) == BIT_NOT_EXPR)
10241           {
10242             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10243                                 complain, in_decl);
10244             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10245           }
10246         else if (TREE_CODE (name) == SCOPE_REF
10247                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10248           {
10249             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10250                                      complain, in_decl);
10251             name = TREE_OPERAND (name, 1);
10252             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10253                                 complain, in_decl);
10254             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10255             name = build_qualified_name (/*type=*/NULL_TREE,
10256                                          base, name,
10257                                          /*template_p=*/false);
10258           }
10259         else if (TREE_CODE (name) == BASELINK)
10260           name = tsubst_baselink (name,
10261                                   non_reference (TREE_TYPE (object)),
10262                                   args, complain,
10263                                   in_decl);
10264         else
10265           name = tsubst_copy (name, args, complain, in_decl);
10266         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10267       }
10268
10269     case PLUS_EXPR:
10270     case MINUS_EXPR:
10271     case MULT_EXPR:
10272     case TRUNC_DIV_EXPR:
10273     case CEIL_DIV_EXPR:
10274     case FLOOR_DIV_EXPR:
10275     case ROUND_DIV_EXPR:
10276     case EXACT_DIV_EXPR:
10277     case BIT_AND_EXPR:
10278     case BIT_IOR_EXPR:
10279     case BIT_XOR_EXPR:
10280     case TRUNC_MOD_EXPR:
10281     case FLOOR_MOD_EXPR:
10282     case TRUTH_ANDIF_EXPR:
10283     case TRUTH_ORIF_EXPR:
10284     case TRUTH_AND_EXPR:
10285     case TRUTH_OR_EXPR:
10286     case RSHIFT_EXPR:
10287     case LSHIFT_EXPR:
10288     case RROTATE_EXPR:
10289     case LROTATE_EXPR:
10290     case EQ_EXPR:
10291     case NE_EXPR:
10292     case MAX_EXPR:
10293     case MIN_EXPR:
10294     case LE_EXPR:
10295     case GE_EXPR:
10296     case LT_EXPR:
10297     case GT_EXPR:
10298     case COMPOUND_EXPR:
10299     case DOTSTAR_EXPR:
10300     case MEMBER_REF:
10301     case PREDECREMENT_EXPR:
10302     case PREINCREMENT_EXPR:
10303     case POSTDECREMENT_EXPR:
10304     case POSTINCREMENT_EXPR:
10305       return build_nt
10306         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10307          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10308
10309     case SCOPE_REF:
10310       return build_qualified_name (/*type=*/NULL_TREE,
10311                                    tsubst_copy (TREE_OPERAND (t, 0),
10312                                                 args, complain, in_decl),
10313                                    tsubst_copy (TREE_OPERAND (t, 1),
10314                                                 args, complain, in_decl),
10315                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10316
10317     case ARRAY_REF:
10318       return build_nt
10319         (ARRAY_REF,
10320          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10321          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10322          NULL_TREE, NULL_TREE);
10323
10324     case CALL_EXPR:
10325       {
10326         int n = VL_EXP_OPERAND_LENGTH (t);
10327         tree result = build_vl_exp (CALL_EXPR, n);
10328         int i;
10329         for (i = 0; i < n; i++)
10330           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10331                                              complain, in_decl);
10332         return result;
10333       }
10334
10335     case COND_EXPR:
10336     case MODOP_EXPR:
10337     case PSEUDO_DTOR_EXPR:
10338       {
10339         r = build_nt
10340           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10341            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10342            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10343         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10344         return r;
10345       }
10346
10347     case NEW_EXPR:
10348       {
10349         r = build_nt
10350         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10351          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10352          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10353         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10354         return r;
10355       }
10356
10357     case DELETE_EXPR:
10358       {
10359         r = build_nt
10360         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10361          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10362         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10363         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10364         return r;
10365       }
10366
10367     case TEMPLATE_ID_EXPR:
10368       {
10369         /* Substituted template arguments */
10370         tree fn = TREE_OPERAND (t, 0);
10371         tree targs = TREE_OPERAND (t, 1);
10372
10373         fn = tsubst_copy (fn, args, complain, in_decl);
10374         if (targs)
10375           targs = tsubst_template_args (targs, args, complain, in_decl);
10376
10377         return lookup_template_function (fn, targs);
10378       }
10379
10380     case TREE_LIST:
10381       {
10382         tree purpose, value, chain;
10383
10384         if (t == void_list_node)
10385           return t;
10386
10387         purpose = TREE_PURPOSE (t);
10388         if (purpose)
10389           purpose = tsubst_copy (purpose, args, complain, in_decl);
10390         value = TREE_VALUE (t);
10391         if (value)
10392           value = tsubst_copy (value, args, complain, in_decl);
10393         chain = TREE_CHAIN (t);
10394         if (chain && chain != void_type_node)
10395           chain = tsubst_copy (chain, args, complain, in_decl);
10396         if (purpose == TREE_PURPOSE (t)
10397             && value == TREE_VALUE (t)
10398             && chain == TREE_CHAIN (t))
10399           return t;
10400         return tree_cons (purpose, value, chain);
10401       }
10402
10403     case RECORD_TYPE:
10404     case UNION_TYPE:
10405     case ENUMERAL_TYPE:
10406     case INTEGER_TYPE:
10407     case TEMPLATE_TYPE_PARM:
10408     case TEMPLATE_TEMPLATE_PARM:
10409     case BOUND_TEMPLATE_TEMPLATE_PARM:
10410     case TEMPLATE_PARM_INDEX:
10411     case POINTER_TYPE:
10412     case REFERENCE_TYPE:
10413     case OFFSET_TYPE:
10414     case FUNCTION_TYPE:
10415     case METHOD_TYPE:
10416     case ARRAY_TYPE:
10417     case TYPENAME_TYPE:
10418     case UNBOUND_CLASS_TEMPLATE:
10419     case TYPEOF_TYPE:
10420     case DECLTYPE_TYPE:
10421     case TYPE_DECL:
10422       return tsubst (t, args, complain, in_decl);
10423
10424     case IDENTIFIER_NODE:
10425       if (IDENTIFIER_TYPENAME_P (t))
10426         {
10427           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10428           return mangle_conv_op_name_for_type (new_type);
10429         }
10430       else
10431         return t;
10432
10433     case CONSTRUCTOR:
10434       /* This is handled by tsubst_copy_and_build.  */
10435       gcc_unreachable ();
10436
10437     case VA_ARG_EXPR:
10438       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10439                                           in_decl),
10440                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10441
10442     case CLEANUP_POINT_EXPR:
10443       /* We shouldn't have built any of these during initial template
10444          generation.  Instead, they should be built during instantiation
10445          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10446       gcc_unreachable ();
10447
10448     case OFFSET_REF:
10449       mark_used (TREE_OPERAND (t, 1));
10450       return t;
10451
10452     case EXPR_PACK_EXPANSION:
10453       error ("invalid use of pack expansion expression");
10454       return error_mark_node;
10455
10456     case NONTYPE_ARGUMENT_PACK:
10457       error ("use %<...%> to expand argument pack");
10458       return error_mark_node;
10459
10460     default:
10461       return t;
10462     }
10463 }
10464
10465 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10466
10467 static tree
10468 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10469                     tree in_decl)
10470 {
10471   tree new_clauses = NULL, nc, oc;
10472
10473   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10474     {
10475       nc = copy_node (oc);
10476       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10477       new_clauses = nc;
10478
10479       switch (OMP_CLAUSE_CODE (nc))
10480         {
10481         case OMP_CLAUSE_LASTPRIVATE:
10482           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10483             {
10484               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10485               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10486                            in_decl, /*integral_constant_expression_p=*/false);
10487               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10488                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10489             }
10490           /* FALLTHRU */
10491         case OMP_CLAUSE_PRIVATE:
10492         case OMP_CLAUSE_SHARED:
10493         case OMP_CLAUSE_FIRSTPRIVATE:
10494         case OMP_CLAUSE_REDUCTION:
10495         case OMP_CLAUSE_COPYIN:
10496         case OMP_CLAUSE_COPYPRIVATE:
10497         case OMP_CLAUSE_IF:
10498         case OMP_CLAUSE_NUM_THREADS:
10499         case OMP_CLAUSE_SCHEDULE:
10500         case OMP_CLAUSE_COLLAPSE:
10501           OMP_CLAUSE_OPERAND (nc, 0)
10502             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10503                            in_decl, /*integral_constant_expression_p=*/false);
10504           break;
10505         case OMP_CLAUSE_NOWAIT:
10506         case OMP_CLAUSE_ORDERED:
10507         case OMP_CLAUSE_DEFAULT:
10508         case OMP_CLAUSE_UNTIED:
10509           break;
10510         default:
10511           gcc_unreachable ();
10512         }
10513     }
10514
10515   return finish_omp_clauses (nreverse (new_clauses));
10516 }
10517
10518 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10519
10520 static tree
10521 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10522                           tree in_decl)
10523 {
10524 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10525
10526   tree purpose, value, chain;
10527
10528   if (t == NULL)
10529     return t;
10530
10531   if (TREE_CODE (t) != TREE_LIST)
10532     return tsubst_copy_and_build (t, args, complain, in_decl,
10533                                   /*function_p=*/false,
10534                                   /*integral_constant_expression_p=*/false);
10535
10536   if (t == void_list_node)
10537     return t;
10538
10539   purpose = TREE_PURPOSE (t);
10540   if (purpose)
10541     purpose = RECUR (purpose);
10542   value = TREE_VALUE (t);
10543   if (value)
10544     value = RECUR (value);
10545   chain = TREE_CHAIN (t);
10546   if (chain && chain != void_type_node)
10547     chain = RECUR (chain);
10548   return tree_cons (purpose, value, chain);
10549 #undef RECUR
10550 }
10551
10552 /* Substitute one OMP_FOR iterator.  */
10553
10554 static void
10555 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
10556                          tree condv, tree incrv, tree *clauses,
10557                          tree args, tsubst_flags_t complain, tree in_decl,
10558                          bool integral_constant_expression_p)
10559 {
10560 #define RECUR(NODE)                             \
10561   tsubst_expr ((NODE), args, complain, in_decl, \
10562                integral_constant_expression_p)
10563   tree decl, init, cond, incr, auto_node;
10564
10565   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
10566   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10567   decl = RECUR (TREE_OPERAND (init, 0));
10568   init = TREE_OPERAND (init, 1);
10569   auto_node = type_uses_auto (TREE_TYPE (decl));
10570   if (auto_node && init)
10571     {
10572       tree init_expr = init;
10573       if (TREE_CODE (init_expr) == DECL_EXPR)
10574         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
10575       init_expr = RECUR (init_expr);
10576       TREE_TYPE (decl)
10577         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
10578     }
10579   gcc_assert (!type_dependent_expression_p (decl));
10580
10581   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
10582     {
10583       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
10584       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10585       if (TREE_CODE (incr) == MODIFY_EXPR)
10586         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
10587                                     RECUR (TREE_OPERAND (incr, 1)),
10588                                     complain);
10589       else
10590         incr = RECUR (incr);
10591       TREE_VEC_ELT (declv, i) = decl;
10592       TREE_VEC_ELT (initv, i) = init;
10593       TREE_VEC_ELT (condv, i) = cond;
10594       TREE_VEC_ELT (incrv, i) = incr;
10595       return;
10596     }
10597
10598   if (init && TREE_CODE (init) != DECL_EXPR)
10599     {
10600       tree c;
10601       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
10602         {
10603           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
10604                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
10605               && OMP_CLAUSE_DECL (c) == decl)
10606             break;
10607           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
10608                    && OMP_CLAUSE_DECL (c) == decl)
10609             error ("iteration variable %qD should not be firstprivate", decl);
10610           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
10611                    && OMP_CLAUSE_DECL (c) == decl)
10612             error ("iteration variable %qD should not be reduction", decl);
10613         }
10614       if (c == NULL)
10615         {
10616           c = build_omp_clause (OMP_CLAUSE_PRIVATE);
10617           OMP_CLAUSE_DECL (c) = decl;
10618           c = finish_omp_clauses (c);
10619           if (c)
10620             {
10621               OMP_CLAUSE_CHAIN (c) = *clauses;
10622               *clauses = c;
10623             }
10624         }
10625     }
10626   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
10627   if (COMPARISON_CLASS_P (cond))
10628     cond = build2 (TREE_CODE (cond), boolean_type_node,
10629                    RECUR (TREE_OPERAND (cond, 0)),
10630                    RECUR (TREE_OPERAND (cond, 1)));
10631   else
10632     cond = RECUR (cond);
10633   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10634   switch (TREE_CODE (incr))
10635     {
10636     case PREINCREMENT_EXPR:
10637     case PREDECREMENT_EXPR:
10638     case POSTINCREMENT_EXPR:
10639     case POSTDECREMENT_EXPR:
10640       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
10641                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
10642       break;
10643     case MODIFY_EXPR:
10644       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10645           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10646         {
10647           tree rhs = TREE_OPERAND (incr, 1);
10648           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10649                          RECUR (TREE_OPERAND (incr, 0)),
10650                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10651                                  RECUR (TREE_OPERAND (rhs, 0)),
10652                                  RECUR (TREE_OPERAND (rhs, 1))));
10653         }
10654       else
10655         incr = RECUR (incr);
10656       break;
10657     case MODOP_EXPR:
10658       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10659           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10660         {
10661           tree lhs = RECUR (TREE_OPERAND (incr, 0));
10662           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
10663                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
10664                                  TREE_TYPE (decl), lhs,
10665                                  RECUR (TREE_OPERAND (incr, 2))));
10666         }
10667       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
10668                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
10669                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
10670         {
10671           tree rhs = TREE_OPERAND (incr, 2);
10672           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10673                          RECUR (TREE_OPERAND (incr, 0)),
10674                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10675                                  RECUR (TREE_OPERAND (rhs, 0)),
10676                                  RECUR (TREE_OPERAND (rhs, 1))));
10677         }
10678       else
10679         incr = RECUR (incr);
10680       break;
10681     default:
10682       incr = RECUR (incr);
10683       break;
10684     }
10685
10686   TREE_VEC_ELT (declv, i) = decl;
10687   TREE_VEC_ELT (initv, i) = init;
10688   TREE_VEC_ELT (condv, i) = cond;
10689   TREE_VEC_ELT (incrv, i) = incr;
10690 #undef RECUR
10691 }
10692
10693 /* Like tsubst_copy for expressions, etc. but also does semantic
10694    processing.  */
10695
10696 static tree
10697 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10698              bool integral_constant_expression_p)
10699 {
10700 #define RECUR(NODE)                             \
10701   tsubst_expr ((NODE), args, complain, in_decl, \
10702                integral_constant_expression_p)
10703
10704   tree stmt, tmp;
10705
10706   if (t == NULL_TREE || t == error_mark_node)
10707     return t;
10708
10709   if (EXPR_HAS_LOCATION (t))
10710     input_location = EXPR_LOCATION (t);
10711   if (STATEMENT_CODE_P (TREE_CODE (t)))
10712     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10713
10714   switch (TREE_CODE (t))
10715     {
10716     case STATEMENT_LIST:
10717       {
10718         tree_stmt_iterator i;
10719         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10720           RECUR (tsi_stmt (i));
10721         break;
10722       }
10723
10724     case CTOR_INITIALIZER:
10725       finish_mem_initializers (tsubst_initializer_list
10726                                (TREE_OPERAND (t, 0), args));
10727       break;
10728
10729     case RETURN_EXPR:
10730       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10731       break;
10732
10733     case EXPR_STMT:
10734       tmp = RECUR (EXPR_STMT_EXPR (t));
10735       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10736         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10737       else
10738         finish_expr_stmt (tmp);
10739       break;
10740
10741     case USING_STMT:
10742       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10743       break;
10744
10745     case DECL_EXPR:
10746       {
10747         tree decl;
10748         tree init;
10749
10750         decl = DECL_EXPR_DECL (t);
10751         if (TREE_CODE (decl) == LABEL_DECL)
10752           finish_label_decl (DECL_NAME (decl));
10753         else if (TREE_CODE (decl) == USING_DECL)
10754           {
10755             tree scope = USING_DECL_SCOPE (decl);
10756             tree name = DECL_NAME (decl);
10757             tree decl;
10758
10759             scope = RECUR (scope);
10760             decl = lookup_qualified_name (scope, name,
10761                                           /*is_type_p=*/false,
10762                                           /*complain=*/false);
10763             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10764               qualified_name_lookup_error (scope, name, decl, input_location);
10765             else
10766               do_local_using_decl (decl, scope, name);
10767           }
10768         else
10769           {
10770             init = DECL_INITIAL (decl);
10771             decl = tsubst (decl, args, complain, in_decl);
10772             if (decl != error_mark_node)
10773               {
10774                 /* By marking the declaration as instantiated, we avoid
10775                    trying to instantiate it.  Since instantiate_decl can't
10776                    handle local variables, and since we've already done
10777                    all that needs to be done, that's the right thing to
10778                    do.  */
10779                 if (TREE_CODE (decl) == VAR_DECL)
10780                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10781                 if (TREE_CODE (decl) == VAR_DECL
10782                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10783                   /* Anonymous aggregates are a special case.  */
10784                   finish_anon_union (decl);
10785                 else
10786                   {
10787                     maybe_push_decl (decl);
10788                     if (TREE_CODE (decl) == VAR_DECL
10789                         && DECL_PRETTY_FUNCTION_P (decl))
10790                       {
10791                         /* For __PRETTY_FUNCTION__ we have to adjust the
10792                            initializer.  */
10793                         const char *const name
10794                           = cxx_printable_name (current_function_decl, 2);
10795                         init = cp_fname_init (name, &TREE_TYPE (decl));
10796                       }
10797                     else
10798                       {
10799                         tree t = RECUR (init);
10800
10801                         if (init && !t)
10802                           /* If we had an initializer but it
10803                              instantiated to nothing,
10804                              value-initialize the object.  This will
10805                              only occur when the initializer was a
10806                              pack expansion where the parameter packs
10807                              used in that expansion were of length
10808                              zero.  */
10809                           init = build_value_init (TREE_TYPE (decl));
10810                         else
10811                           init = t;
10812                       }
10813
10814                     finish_decl (decl, init, NULL_TREE);
10815                   }
10816               }
10817           }
10818
10819         /* A DECL_EXPR can also be used as an expression, in the condition
10820            clause of an if/for/while construct.  */
10821         return decl;
10822       }
10823
10824     case FOR_STMT:
10825       stmt = begin_for_stmt ();
10826                           RECUR (FOR_INIT_STMT (t));
10827       finish_for_init_stmt (stmt);
10828       tmp = RECUR (FOR_COND (t));
10829       finish_for_cond (tmp, stmt);
10830       tmp = RECUR (FOR_EXPR (t));
10831       finish_for_expr (tmp, stmt);
10832       RECUR (FOR_BODY (t));
10833       finish_for_stmt (stmt);
10834       break;
10835
10836     case WHILE_STMT:
10837       stmt = begin_while_stmt ();
10838       tmp = RECUR (WHILE_COND (t));
10839       finish_while_stmt_cond (tmp, stmt);
10840       RECUR (WHILE_BODY (t));
10841       finish_while_stmt (stmt);
10842       break;
10843
10844     case DO_STMT:
10845       stmt = begin_do_stmt ();
10846       RECUR (DO_BODY (t));
10847       finish_do_body (stmt);
10848       tmp = RECUR (DO_COND (t));
10849       finish_do_stmt (tmp, stmt);
10850       break;
10851
10852     case IF_STMT:
10853       stmt = begin_if_stmt ();
10854       tmp = RECUR (IF_COND (t));
10855       finish_if_stmt_cond (tmp, stmt);
10856       RECUR (THEN_CLAUSE (t));
10857       finish_then_clause (stmt);
10858
10859       if (ELSE_CLAUSE (t))
10860         {
10861           begin_else_clause (stmt);
10862           RECUR (ELSE_CLAUSE (t));
10863           finish_else_clause (stmt);
10864         }
10865
10866       finish_if_stmt (stmt);
10867       break;
10868
10869     case BIND_EXPR:
10870       if (BIND_EXPR_BODY_BLOCK (t))
10871         stmt = begin_function_body ();
10872       else
10873         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10874                                     ? BCS_TRY_BLOCK : 0);
10875
10876       RECUR (BIND_EXPR_BODY (t));
10877
10878       if (BIND_EXPR_BODY_BLOCK (t))
10879         finish_function_body (stmt);
10880       else
10881         finish_compound_stmt (stmt);
10882       break;
10883
10884     case BREAK_STMT:
10885       finish_break_stmt ();
10886       break;
10887
10888     case CONTINUE_STMT:
10889       finish_continue_stmt ();
10890       break;
10891
10892     case SWITCH_STMT:
10893       stmt = begin_switch_stmt ();
10894       tmp = RECUR (SWITCH_STMT_COND (t));
10895       finish_switch_cond (tmp, stmt);
10896       RECUR (SWITCH_STMT_BODY (t));
10897       finish_switch_stmt (stmt);
10898       break;
10899
10900     case CASE_LABEL_EXPR:
10901       finish_case_label (RECUR (CASE_LOW (t)),
10902                          RECUR (CASE_HIGH (t)));
10903       break;
10904
10905     case LABEL_EXPR:
10906       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10907       break;
10908
10909     case GOTO_EXPR:
10910       tmp = GOTO_DESTINATION (t);
10911       if (TREE_CODE (tmp) != LABEL_DECL)
10912         /* Computed goto's must be tsubst'd into.  On the other hand,
10913            non-computed gotos must not be; the identifier in question
10914            will have no binding.  */
10915         tmp = RECUR (tmp);
10916       else
10917         tmp = DECL_NAME (tmp);
10918       finish_goto_stmt (tmp);
10919       break;
10920
10921     case ASM_EXPR:
10922       tmp = finish_asm_stmt
10923         (ASM_VOLATILE_P (t),
10924          RECUR (ASM_STRING (t)),
10925          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10926          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10927          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10928       {
10929         tree asm_expr = tmp;
10930         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10931           asm_expr = TREE_OPERAND (asm_expr, 0);
10932         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10933       }
10934       break;
10935
10936     case TRY_BLOCK:
10937       if (CLEANUP_P (t))
10938         {
10939           stmt = begin_try_block ();
10940           RECUR (TRY_STMTS (t));
10941           finish_cleanup_try_block (stmt);
10942           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10943         }
10944       else
10945         {
10946           tree compound_stmt = NULL_TREE;
10947
10948           if (FN_TRY_BLOCK_P (t))
10949             stmt = begin_function_try_block (&compound_stmt);
10950           else
10951             stmt = begin_try_block ();
10952
10953           RECUR (TRY_STMTS (t));
10954
10955           if (FN_TRY_BLOCK_P (t))
10956             finish_function_try_block (stmt);
10957           else
10958             finish_try_block (stmt);
10959
10960           RECUR (TRY_HANDLERS (t));
10961           if (FN_TRY_BLOCK_P (t))
10962             finish_function_handler_sequence (stmt, compound_stmt);
10963           else
10964             finish_handler_sequence (stmt);
10965         }
10966       break;
10967
10968     case HANDLER:
10969       {
10970         tree decl = HANDLER_PARMS (t);
10971
10972         if (decl)
10973           {
10974             decl = tsubst (decl, args, complain, in_decl);
10975             /* Prevent instantiate_decl from trying to instantiate
10976                this variable.  We've already done all that needs to be
10977                done.  */
10978             if (decl != error_mark_node)
10979               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10980           }
10981         stmt = begin_handler ();
10982         finish_handler_parms (decl, stmt);
10983         RECUR (HANDLER_BODY (t));
10984         finish_handler (stmt);
10985       }
10986       break;
10987
10988     case TAG_DEFN:
10989       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10990       break;
10991
10992     case STATIC_ASSERT:
10993       {
10994         tree condition = 
10995           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10996                        args,
10997                        complain, in_decl,
10998                        /*integral_constant_expression_p=*/true);
10999         finish_static_assert (condition,
11000                               STATIC_ASSERT_MESSAGE (t),
11001                               STATIC_ASSERT_SOURCE_LOCATION (t),
11002                               /*member_p=*/false);
11003       }
11004       break;
11005
11006     case OMP_PARALLEL:
11007       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11008                                 args, complain, in_decl);
11009       stmt = begin_omp_parallel ();
11010       RECUR (OMP_PARALLEL_BODY (t));
11011       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11012         = OMP_PARALLEL_COMBINED (t);
11013       break;
11014
11015     case OMP_TASK:
11016       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11017                                 args, complain, in_decl);
11018       stmt = begin_omp_task ();
11019       RECUR (OMP_TASK_BODY (t));
11020       finish_omp_task (tmp, stmt);
11021       break;
11022
11023     case OMP_FOR:
11024       {
11025         tree clauses, body, pre_body;
11026         tree declv, initv, condv, incrv;
11027         int i;
11028
11029         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11030                                       args, complain, in_decl);
11031         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11032         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11033         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11034         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11035
11036         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11037           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11038                                    &clauses, args, complain, in_decl,
11039                                    integral_constant_expression_p);
11040
11041         stmt = begin_omp_structured_block ();
11042
11043         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11044           if (TREE_VEC_ELT (initv, i) == NULL
11045               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11046             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11047           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11048             {
11049               tree init = RECUR (TREE_VEC_ELT (initv, i));
11050               gcc_assert (init == TREE_VEC_ELT (declv, i));
11051               TREE_VEC_ELT (initv, i) = NULL_TREE;
11052             }
11053           else
11054             {
11055               tree decl_expr = TREE_VEC_ELT (initv, i);
11056               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11057               gcc_assert (init != NULL);
11058               TREE_VEC_ELT (initv, i) = RECUR (init);
11059               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11060               RECUR (decl_expr);
11061               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11062             }
11063
11064         pre_body = push_stmt_list ();
11065         RECUR (OMP_FOR_PRE_BODY (t));
11066         pre_body = pop_stmt_list (pre_body);
11067
11068         body = push_stmt_list ();
11069         RECUR (OMP_FOR_BODY (t));
11070         body = pop_stmt_list (body);
11071
11072         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11073                             body, pre_body, clauses);
11074
11075         add_stmt (finish_omp_structured_block (stmt));
11076       }
11077       break;
11078
11079     case OMP_SECTIONS:
11080     case OMP_SINGLE:
11081       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11082       stmt = push_stmt_list ();
11083       RECUR (OMP_BODY (t));
11084       stmt = pop_stmt_list (stmt);
11085
11086       t = copy_node (t);
11087       OMP_BODY (t) = stmt;
11088       OMP_CLAUSES (t) = tmp;
11089       add_stmt (t);
11090       break;
11091
11092     case OMP_SECTION:
11093     case OMP_CRITICAL:
11094     case OMP_MASTER:
11095     case OMP_ORDERED:
11096       stmt = push_stmt_list ();
11097       RECUR (OMP_BODY (t));
11098       stmt = pop_stmt_list (stmt);
11099
11100       t = copy_node (t);
11101       OMP_BODY (t) = stmt;
11102       add_stmt (t);
11103       break;
11104
11105     case OMP_ATOMIC:
11106       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11107       {
11108         tree op1 = TREE_OPERAND (t, 1);
11109         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11110         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11111         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11112       }
11113       break;
11114
11115     case EXPR_PACK_EXPANSION:
11116       error ("invalid use of pack expansion expression");
11117       return error_mark_node;
11118
11119     case NONTYPE_ARGUMENT_PACK:
11120       error ("use %<...%> to expand argument pack");
11121       return error_mark_node;
11122
11123     default:
11124       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11125
11126       return tsubst_copy_and_build (t, args, complain, in_decl,
11127                                     /*function_p=*/false,
11128                                     integral_constant_expression_p);
11129     }
11130
11131   return NULL_TREE;
11132 #undef RECUR
11133 }
11134
11135 /* T is a postfix-expression that is not being used in a function
11136    call.  Return the substituted version of T.  */
11137
11138 static tree
11139 tsubst_non_call_postfix_expression (tree t, tree args,
11140                                     tsubst_flags_t complain,
11141                                     tree in_decl)
11142 {
11143   if (TREE_CODE (t) == SCOPE_REF)
11144     t = tsubst_qualified_id (t, args, complain, in_decl,
11145                              /*done=*/false, /*address_p=*/false);
11146   else
11147     t = tsubst_copy_and_build (t, args, complain, in_decl,
11148                                /*function_p=*/false,
11149                                /*integral_constant_expression_p=*/false);
11150
11151   return t;
11152 }
11153
11154 /* Like tsubst but deals with expressions and performs semantic
11155    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11156
11157 tree
11158 tsubst_copy_and_build (tree t,
11159                        tree args,
11160                        tsubst_flags_t complain,
11161                        tree in_decl,
11162                        bool function_p,
11163                        bool integral_constant_expression_p)
11164 {
11165 #define RECUR(NODE)                                             \
11166   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11167                          /*function_p=*/false,                  \
11168                          integral_constant_expression_p)
11169
11170   tree op1;
11171
11172   if (t == NULL_TREE || t == error_mark_node)
11173     return t;
11174
11175   switch (TREE_CODE (t))
11176     {
11177     case USING_DECL:
11178       t = DECL_NAME (t);
11179       /* Fall through.  */
11180     case IDENTIFIER_NODE:
11181       {
11182         tree decl;
11183         cp_id_kind idk;
11184         bool non_integral_constant_expression_p;
11185         const char *error_msg;
11186
11187         if (IDENTIFIER_TYPENAME_P (t))
11188           {
11189             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11190             t = mangle_conv_op_name_for_type (new_type);
11191           }
11192
11193         /* Look up the name.  */
11194         decl = lookup_name (t);
11195
11196         /* By convention, expressions use ERROR_MARK_NODE to indicate
11197            failure, not NULL_TREE.  */
11198         if (decl == NULL_TREE)
11199           decl = error_mark_node;
11200
11201         decl = finish_id_expression (t, decl, NULL_TREE,
11202                                      &idk,
11203                                      integral_constant_expression_p,
11204                                      /*allow_non_integral_constant_expression_p=*/false,
11205                                      &non_integral_constant_expression_p,
11206                                      /*template_p=*/false,
11207                                      /*done=*/true,
11208                                      /*address_p=*/false,
11209                                      /*template_arg_p=*/false,
11210                                      &error_msg,
11211                                      input_location);
11212         if (error_msg)
11213           error (error_msg);
11214         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11215           decl = unqualified_name_lookup_error (decl);
11216         return decl;
11217       }
11218
11219     case TEMPLATE_ID_EXPR:
11220       {
11221         tree object;
11222         tree templ = RECUR (TREE_OPERAND (t, 0));
11223         tree targs = TREE_OPERAND (t, 1);
11224
11225         if (targs)
11226           targs = tsubst_template_args (targs, args, complain, in_decl);
11227
11228         if (TREE_CODE (templ) == COMPONENT_REF)
11229           {
11230             object = TREE_OPERAND (templ, 0);
11231             templ = TREE_OPERAND (templ, 1);
11232           }
11233         else
11234           object = NULL_TREE;
11235         templ = lookup_template_function (templ, targs);
11236
11237         if (object)
11238           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11239                          object, templ, NULL_TREE);
11240         else
11241           return baselink_for_fns (templ);
11242       }
11243
11244     case INDIRECT_REF:
11245       {
11246         tree r = RECUR (TREE_OPERAND (t, 0));
11247
11248         if (REFERENCE_REF_P (t))
11249           {
11250             /* A type conversion to reference type will be enclosed in
11251                such an indirect ref, but the substitution of the cast
11252                will have also added such an indirect ref.  */
11253             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11254               r = convert_from_reference (r);
11255           }
11256         else
11257           r = build_x_indirect_ref (r, "unary *", complain);
11258         return r;
11259       }
11260
11261     case NOP_EXPR:
11262       return build_nop
11263         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11264          RECUR (TREE_OPERAND (t, 0)));
11265
11266     case CAST_EXPR:
11267     case REINTERPRET_CAST_EXPR:
11268     case CONST_CAST_EXPR:
11269     case DYNAMIC_CAST_EXPR:
11270     case STATIC_CAST_EXPR:
11271       {
11272         tree type;
11273         tree op;
11274
11275         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11276         if (integral_constant_expression_p
11277             && !cast_valid_in_integral_constant_expression_p (type))
11278           {
11279             if (complain & tf_error)
11280               error ("a cast to a type other than an integral or "
11281                      "enumeration type cannot appear in a constant-expression");
11282             return error_mark_node; 
11283           }
11284
11285         op = RECUR (TREE_OPERAND (t, 0));
11286
11287         switch (TREE_CODE (t))
11288           {
11289           case CAST_EXPR:
11290             return build_functional_cast (type, op, complain);
11291           case REINTERPRET_CAST_EXPR:
11292             return build_reinterpret_cast (type, op, complain);
11293           case CONST_CAST_EXPR:
11294             return build_const_cast (type, op, complain);
11295           case DYNAMIC_CAST_EXPR:
11296             return build_dynamic_cast (type, op, complain);
11297           case STATIC_CAST_EXPR:
11298             return build_static_cast (type, op, complain);
11299           default:
11300             gcc_unreachable ();
11301           }
11302       }
11303
11304     case POSTDECREMENT_EXPR:
11305     case POSTINCREMENT_EXPR:
11306       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11307                                                 args, complain, in_decl);
11308       return build_x_unary_op (TREE_CODE (t), op1, complain);
11309
11310     case PREDECREMENT_EXPR:
11311     case PREINCREMENT_EXPR:
11312     case NEGATE_EXPR:
11313     case BIT_NOT_EXPR:
11314     case ABS_EXPR:
11315     case TRUTH_NOT_EXPR:
11316     case UNARY_PLUS_EXPR:  /* Unary + */
11317     case REALPART_EXPR:
11318     case IMAGPART_EXPR:
11319       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11320                                complain);
11321
11322     case ADDR_EXPR:
11323       op1 = TREE_OPERAND (t, 0);
11324       if (TREE_CODE (op1) == SCOPE_REF)
11325         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11326                                    /*done=*/true, /*address_p=*/true);
11327       else
11328         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11329                                                   in_decl);
11330       if (TREE_CODE (op1) == LABEL_DECL)
11331         return finish_label_address_expr (DECL_NAME (op1),
11332                                           EXPR_LOCATION (op1));
11333       return build_x_unary_op (ADDR_EXPR, op1, complain);
11334
11335     case PLUS_EXPR:
11336     case MINUS_EXPR:
11337     case MULT_EXPR:
11338     case TRUNC_DIV_EXPR:
11339     case CEIL_DIV_EXPR:
11340     case FLOOR_DIV_EXPR:
11341     case ROUND_DIV_EXPR:
11342     case EXACT_DIV_EXPR:
11343     case BIT_AND_EXPR:
11344     case BIT_IOR_EXPR:
11345     case BIT_XOR_EXPR:
11346     case TRUNC_MOD_EXPR:
11347     case FLOOR_MOD_EXPR:
11348     case TRUTH_ANDIF_EXPR:
11349     case TRUTH_ORIF_EXPR:
11350     case TRUTH_AND_EXPR:
11351     case TRUTH_OR_EXPR:
11352     case RSHIFT_EXPR:
11353     case LSHIFT_EXPR:
11354     case RROTATE_EXPR:
11355     case LROTATE_EXPR:
11356     case EQ_EXPR:
11357     case NE_EXPR:
11358     case MAX_EXPR:
11359     case MIN_EXPR:
11360     case LE_EXPR:
11361     case GE_EXPR:
11362     case LT_EXPR:
11363     case GT_EXPR:
11364     case MEMBER_REF:
11365     case DOTSTAR_EXPR:
11366       return build_x_binary_op
11367         (TREE_CODE (t),
11368          RECUR (TREE_OPERAND (t, 0)),
11369          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11370           ? ERROR_MARK
11371           : TREE_CODE (TREE_OPERAND (t, 0))),
11372          RECUR (TREE_OPERAND (t, 1)),
11373          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11374           ? ERROR_MARK
11375           : TREE_CODE (TREE_OPERAND (t, 1))),
11376          /*overloaded_p=*/NULL,
11377          complain);
11378
11379     case SCOPE_REF:
11380       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11381                                   /*address_p=*/false);
11382     case ARRAY_REF:
11383       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11384                                                 args, complain, in_decl);
11385       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11386
11387     case SIZEOF_EXPR:
11388       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11389         return tsubst_copy (t, args, complain, in_decl);
11390       /* Fall through */
11391       
11392     case ALIGNOF_EXPR:
11393       op1 = TREE_OPERAND (t, 0);
11394       if (!args)
11395         {
11396           /* When there are no ARGS, we are trying to evaluate a
11397              non-dependent expression from the parser.  Trying to do
11398              the substitutions may not work.  */
11399           if (!TYPE_P (op1))
11400             op1 = TREE_TYPE (op1);
11401         }
11402       else
11403         {
11404           ++skip_evaluation;
11405           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11406                                        /*function_p=*/false,
11407                                        /*integral_constant_expression_p=*/false);
11408           --skip_evaluation;
11409         }
11410       if (TYPE_P (op1))
11411         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11412                                            complain & tf_error);
11413       else
11414         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11415                                            complain & tf_error);
11416
11417     case MODOP_EXPR:
11418       {
11419         tree r = build_x_modify_expr
11420           (RECUR (TREE_OPERAND (t, 0)),
11421            TREE_CODE (TREE_OPERAND (t, 1)),
11422            RECUR (TREE_OPERAND (t, 2)),
11423            complain);
11424         /* TREE_NO_WARNING must be set if either the expression was
11425            parenthesized or it uses an operator such as >>= rather
11426            than plain assignment.  In the former case, it was already
11427            set and must be copied.  In the latter case,
11428            build_x_modify_expr sets it and it must not be reset
11429            here.  */
11430         if (TREE_NO_WARNING (t))
11431           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11432         return r;
11433       }
11434
11435     case ARROW_EXPR:
11436       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11437                                                 args, complain, in_decl);
11438       /* Remember that there was a reference to this entity.  */
11439       if (DECL_P (op1))
11440         mark_used (op1);
11441       return build_x_arrow (op1);
11442
11443     case NEW_EXPR:
11444       {
11445         tree init = RECUR (TREE_OPERAND (t, 3));
11446
11447         if (TREE_OPERAND (t, 3) && !init)
11448           /* If there was an initializer in the original tree, but
11449              it instantiated to an empty list, then we should pass on
11450              VOID_ZERO_NODE to tell build_new that it was an empty
11451              initializer () rather than no initializer.  This can only
11452              happen when the initializer is a pack expansion whose
11453              parameter packs are of length zero.  */
11454           init = void_zero_node;
11455
11456         return build_new
11457           (RECUR (TREE_OPERAND (t, 0)),
11458            RECUR (TREE_OPERAND (t, 1)),
11459            RECUR (TREE_OPERAND (t, 2)),
11460            init,
11461            NEW_EXPR_USE_GLOBAL (t),
11462            complain);
11463       }
11464
11465     case DELETE_EXPR:
11466      return delete_sanity
11467        (RECUR (TREE_OPERAND (t, 0)),
11468         RECUR (TREE_OPERAND (t, 1)),
11469         DELETE_EXPR_USE_VEC (t),
11470         DELETE_EXPR_USE_GLOBAL (t));
11471
11472     case COMPOUND_EXPR:
11473       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11474                                     RECUR (TREE_OPERAND (t, 1)),
11475                                     complain);
11476
11477     case CALL_EXPR:
11478       {
11479         tree function;
11480         tree call_args;
11481         bool qualified_p;
11482         bool koenig_p;
11483
11484         function = CALL_EXPR_FN (t);
11485         /* When we parsed the expression,  we determined whether or
11486            not Koenig lookup should be performed.  */
11487         koenig_p = KOENIG_LOOKUP_P (t);
11488         if (TREE_CODE (function) == SCOPE_REF)
11489           {
11490             qualified_p = true;
11491             function = tsubst_qualified_id (function, args, complain, in_decl,
11492                                             /*done=*/false,
11493                                             /*address_p=*/false);
11494           }
11495         else
11496           {
11497             if (TREE_CODE (function) == COMPONENT_REF)
11498               {
11499                 tree op = TREE_OPERAND (function, 1);
11500
11501                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11502                                || (BASELINK_P (op)
11503                                    && BASELINK_QUALIFIED_P (op)));
11504               }
11505             else
11506               qualified_p = false;
11507
11508             function = tsubst_copy_and_build (function, args, complain,
11509                                               in_decl,
11510                                               !qualified_p,
11511                                               integral_constant_expression_p);
11512
11513             if (BASELINK_P (function))
11514               qualified_p = true;
11515           }
11516
11517         /* FIXME:  Rewrite this so as not to construct an arglist.  */
11518         call_args = RECUR (CALL_EXPR_ARGS (t));
11519
11520         /* We do not perform argument-dependent lookup if normal
11521            lookup finds a non-function, in accordance with the
11522            expected resolution of DR 218.  */
11523         if (koenig_p
11524             && ((is_overloaded_fn (function)
11525                  /* If lookup found a member function, the Koenig lookup is
11526                     not appropriate, even if an unqualified-name was used
11527                     to denote the function.  */
11528                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11529                 || TREE_CODE (function) == IDENTIFIER_NODE)
11530             /* Only do this when substitution turns a dependent call
11531                into a non-dependent call.  */
11532             && type_dependent_expression_p_push (t)
11533             && !any_type_dependent_arguments_p (call_args))
11534           function = perform_koenig_lookup (function, call_args);
11535
11536         if (TREE_CODE (function) == IDENTIFIER_NODE)
11537           {
11538             unqualified_name_lookup_error (function);
11539             return error_mark_node;
11540           }
11541
11542         /* Remember that there was a reference to this entity.  */
11543         if (DECL_P (function))
11544           mark_used (function);
11545
11546         if (TREE_CODE (function) == OFFSET_REF)
11547           return build_offset_ref_call_from_tree (function, call_args);
11548         if (TREE_CODE (function) == COMPONENT_REF)
11549           {
11550             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11551               return finish_call_expr (function, call_args,
11552                                        /*disallow_virtual=*/false,
11553                                        /*koenig_p=*/false,
11554                                        complain);
11555             else
11556               return (build_new_method_call
11557                       (TREE_OPERAND (function, 0),
11558                        TREE_OPERAND (function, 1),
11559                        call_args, NULL_TREE,
11560                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11561                        /*fn_p=*/NULL,
11562                        complain));
11563           }
11564         return finish_call_expr (function, call_args,
11565                                  /*disallow_virtual=*/qualified_p,
11566                                  koenig_p,
11567                                  complain);
11568       }
11569
11570     case COND_EXPR:
11571       return build_x_conditional_expr
11572         (RECUR (TREE_OPERAND (t, 0)),
11573          RECUR (TREE_OPERAND (t, 1)),
11574          RECUR (TREE_OPERAND (t, 2)),
11575          complain);
11576
11577     case PSEUDO_DTOR_EXPR:
11578       return finish_pseudo_destructor_expr
11579         (RECUR (TREE_OPERAND (t, 0)),
11580          RECUR (TREE_OPERAND (t, 1)),
11581          RECUR (TREE_OPERAND (t, 2)));
11582
11583     case TREE_LIST:
11584       {
11585         tree purpose, value, chain;
11586
11587         if (t == void_list_node)
11588           return t;
11589
11590         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11591             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11592           {
11593             /* We have pack expansions, so expand those and
11594                create a new list out of it.  */
11595             tree purposevec = NULL_TREE;
11596             tree valuevec = NULL_TREE;
11597             tree chain;
11598             int i, len = -1;
11599
11600             /* Expand the argument expressions.  */
11601             if (TREE_PURPOSE (t))
11602               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11603                                                  complain, in_decl);
11604             if (TREE_VALUE (t))
11605               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11606                                                complain, in_decl);
11607
11608             /* Build the rest of the list.  */
11609             chain = TREE_CHAIN (t);
11610             if (chain && chain != void_type_node)
11611               chain = RECUR (chain);
11612
11613             /* Determine the number of arguments.  */
11614             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11615               {
11616                 len = TREE_VEC_LENGTH (purposevec);
11617                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11618               }
11619             else if (TREE_CODE (valuevec) == TREE_VEC)
11620               len = TREE_VEC_LENGTH (valuevec);
11621             else
11622               {
11623                 /* Since we only performed a partial substitution into
11624                    the argument pack, we only return a single list
11625                    node.  */
11626                 if (purposevec == TREE_PURPOSE (t)
11627                     && valuevec == TREE_VALUE (t)
11628                     && chain == TREE_CHAIN (t))
11629                   return t;
11630
11631                 return tree_cons (purposevec, valuevec, chain);
11632               }
11633             
11634             /* Convert the argument vectors into a TREE_LIST */
11635             i = len;
11636             while (i > 0)
11637               {
11638                 /* Grab the Ith values.  */
11639                 i--;
11640                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11641                                      : NULL_TREE;
11642                 value 
11643                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11644                              : NULL_TREE;
11645
11646                 /* Build the list (backwards).  */
11647                 chain = tree_cons (purpose, value, chain);
11648               }
11649
11650             return chain;
11651           }
11652
11653         purpose = TREE_PURPOSE (t);
11654         if (purpose)
11655           purpose = RECUR (purpose);
11656         value = TREE_VALUE (t);
11657         if (value)
11658           value = RECUR (value);
11659         chain = TREE_CHAIN (t);
11660         if (chain && chain != void_type_node)
11661           chain = RECUR (chain);
11662         if (purpose == TREE_PURPOSE (t)
11663             && value == TREE_VALUE (t)
11664             && chain == TREE_CHAIN (t))
11665           return t;
11666         return tree_cons (purpose, value, chain);
11667       }
11668
11669     case COMPONENT_REF:
11670       {
11671         tree object;
11672         tree object_type;
11673         tree member;
11674
11675         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11676                                                      args, complain, in_decl);
11677         /* Remember that there was a reference to this entity.  */
11678         if (DECL_P (object))
11679           mark_used (object);
11680         object_type = TREE_TYPE (object);
11681
11682         member = TREE_OPERAND (t, 1);
11683         if (BASELINK_P (member))
11684           member = tsubst_baselink (member,
11685                                     non_reference (TREE_TYPE (object)),
11686                                     args, complain, in_decl);
11687         else
11688           member = tsubst_copy (member, args, complain, in_decl);
11689         if (member == error_mark_node)
11690           return error_mark_node;
11691
11692         if (object_type && !CLASS_TYPE_P (object_type))
11693           {
11694             if (SCALAR_TYPE_P (object_type))
11695               {
11696                 tree s = NULL_TREE;
11697                 tree dtor = member;
11698
11699                 if (TREE_CODE (dtor) == SCOPE_REF)
11700                   {
11701                     s = TREE_OPERAND (dtor, 0);
11702                     dtor = TREE_OPERAND (dtor, 1);
11703                   }
11704                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11705                   {
11706                     dtor = TREE_OPERAND (dtor, 0);
11707                     if (TYPE_P (dtor))
11708                       return finish_pseudo_destructor_expr (object, s, dtor);
11709                   }
11710               }
11711           }
11712         else if (TREE_CODE (member) == SCOPE_REF
11713                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11714           {
11715             tree tmpl;
11716             tree args;
11717
11718             /* Lookup the template functions now that we know what the
11719                scope is.  */
11720             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11721             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11722             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11723                                             /*is_type_p=*/false,
11724                                             /*complain=*/false);
11725             if (BASELINK_P (member))
11726               {
11727                 BASELINK_FUNCTIONS (member)
11728                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11729                               args);
11730                 member = (adjust_result_of_qualified_name_lookup
11731                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11732                            object_type));
11733               }
11734             else
11735               {
11736                 qualified_name_lookup_error (object_type, tmpl, member,
11737                                              input_location);
11738                 return error_mark_node;
11739               }
11740           }
11741         else if (TREE_CODE (member) == SCOPE_REF
11742                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11743                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11744           {
11745             if (complain & tf_error)
11746               {
11747                 if (TYPE_P (TREE_OPERAND (member, 0)))
11748                   error ("%qT is not a class or namespace",
11749                          TREE_OPERAND (member, 0));
11750                 else
11751                   error ("%qD is not a class or namespace",
11752                          TREE_OPERAND (member, 0));
11753               }
11754             return error_mark_node;
11755           }
11756         else if (TREE_CODE (member) == FIELD_DECL)
11757           return finish_non_static_data_member (member, object, NULL_TREE);
11758
11759         return finish_class_member_access_expr (object, member,
11760                                                 /*template_p=*/false,
11761                                                 complain);
11762       }
11763
11764     case THROW_EXPR:
11765       return build_throw
11766         (RECUR (TREE_OPERAND (t, 0)));
11767
11768     case CONSTRUCTOR:
11769       {
11770         VEC(constructor_elt,gc) *n;
11771         constructor_elt *ce;
11772         unsigned HOST_WIDE_INT idx;
11773         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11774         bool process_index_p;
11775         int newlen;
11776         bool need_copy_p = false;
11777         tree r;
11778
11779         if (type == error_mark_node)
11780           return error_mark_node;
11781
11782         /* digest_init will do the wrong thing if we let it.  */
11783         if (type && TYPE_PTRMEMFUNC_P (type))
11784           return t;
11785
11786         /* We do not want to process the index of aggregate
11787            initializers as they are identifier nodes which will be
11788            looked up by digest_init.  */
11789         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
11790
11791         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11792         newlen = VEC_length (constructor_elt, n);
11793         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11794           {
11795             if (ce->index && process_index_p)
11796               ce->index = RECUR (ce->index);
11797
11798             if (PACK_EXPANSION_P (ce->value))
11799               {
11800                 /* Substitute into the pack expansion.  */
11801                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11802                                                   in_decl);
11803
11804                 if (ce->value == error_mark_node)
11805                   ;
11806                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11807                   /* Just move the argument into place.  */
11808                   ce->value = TREE_VEC_ELT (ce->value, 0);
11809                 else
11810                   {
11811                     /* Update the length of the final CONSTRUCTOR
11812                        arguments vector, and note that we will need to
11813                        copy.*/
11814                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11815                     need_copy_p = true;
11816                   }
11817               }
11818             else
11819               ce->value = RECUR (ce->value);
11820           }
11821
11822         if (need_copy_p)
11823           {
11824             VEC(constructor_elt,gc) *old_n = n;
11825
11826             n = VEC_alloc (constructor_elt, gc, newlen);
11827             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11828                  idx++)
11829               {
11830                 if (TREE_CODE (ce->value) == TREE_VEC)
11831                   {
11832                     int i, len = TREE_VEC_LENGTH (ce->value);
11833                     for (i = 0; i < len; ++i)
11834                       CONSTRUCTOR_APPEND_ELT (n, 0,
11835                                               TREE_VEC_ELT (ce->value, i));
11836                   }
11837                 else
11838                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11839               }
11840           }
11841
11842         r = build_constructor (init_list_type_node, n);
11843         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
11844
11845         if (TREE_HAS_CONSTRUCTOR (t))
11846           return finish_compound_literal (type, r);
11847
11848         return r;
11849       }
11850
11851     case TYPEID_EXPR:
11852       {
11853         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11854         if (TYPE_P (operand_0))
11855           return get_typeid (operand_0);
11856         return build_typeid (operand_0);
11857       }
11858
11859     case VAR_DECL:
11860       if (!args)
11861         return t;
11862       /* Fall through */
11863
11864     case PARM_DECL:
11865       {
11866         tree r = tsubst_copy (t, args, complain, in_decl);
11867
11868         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11869           /* If the original type was a reference, we'll be wrapped in
11870              the appropriate INDIRECT_REF.  */
11871           r = convert_from_reference (r);
11872         return r;
11873       }
11874
11875     case VA_ARG_EXPR:
11876       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11877                              tsubst_copy (TREE_TYPE (t), args, complain,
11878                                           in_decl));
11879
11880     case OFFSETOF_EXPR:
11881       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11882
11883     case TRAIT_EXPR:
11884       {
11885         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11886                                   complain, in_decl);
11887
11888         tree type2 = TRAIT_EXPR_TYPE2 (t);
11889         if (type2)
11890           type2 = tsubst_copy (type2, args, complain, in_decl);
11891         
11892         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11893       }
11894
11895     case STMT_EXPR:
11896       {
11897         tree old_stmt_expr = cur_stmt_expr;
11898         tree stmt_expr = begin_stmt_expr ();
11899
11900         cur_stmt_expr = stmt_expr;
11901         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11902                      integral_constant_expression_p);
11903         stmt_expr = finish_stmt_expr (stmt_expr, false);
11904         cur_stmt_expr = old_stmt_expr;
11905
11906         return stmt_expr;
11907       }
11908
11909     case CONST_DECL:
11910       t = tsubst_copy (t, args, complain, in_decl);
11911       /* As in finish_id_expression, we resolve enumeration constants
11912          to their underlying values.  */
11913       if (TREE_CODE (t) == CONST_DECL)
11914         {
11915           used_types_insert (TREE_TYPE (t));
11916           return DECL_INITIAL (t);
11917         }
11918       return t;
11919
11920     default:
11921       /* Handle Objective-C++ constructs, if appropriate.  */
11922       {
11923         tree subst
11924           = objcp_tsubst_copy_and_build (t, args, complain,
11925                                          in_decl, /*function_p=*/false);
11926         if (subst)
11927           return subst;
11928       }
11929       return tsubst_copy (t, args, complain, in_decl);
11930     }
11931
11932 #undef RECUR
11933 }
11934
11935 /* Verify that the instantiated ARGS are valid. For type arguments,
11936    make sure that the type's linkage is ok. For non-type arguments,
11937    make sure they are constants if they are integral or enumerations.
11938    Emit an error under control of COMPLAIN, and return TRUE on error.  */
11939
11940 static bool
11941 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
11942 {
11943   if (ARGUMENT_PACK_P (t))
11944     {
11945       tree vec = ARGUMENT_PACK_ARGS (t);
11946       int len = TREE_VEC_LENGTH (vec);
11947       bool result = false;
11948       int i;
11949
11950       for (i = 0; i < len; ++i)
11951         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
11952           result = true;
11953       return result;
11954     }
11955   else if (TYPE_P (t))
11956     {
11957       /* [basic.link]: A name with no linkage (notably, the name
11958          of a class or enumeration declared in a local scope)
11959          shall not be used to declare an entity with linkage.
11960          This implies that names with no linkage cannot be used as
11961          template arguments.  */
11962       tree nt = no_linkage_check (t, /*relaxed_p=*/false);
11963
11964       if (nt)
11965         {
11966           /* DR 488 makes use of a type with no linkage cause
11967              type deduction to fail.  */
11968           if (complain & tf_error)
11969             {
11970               if (TYPE_ANONYMOUS_P (nt))
11971                 error ("%qT is/uses anonymous type", t);
11972               else
11973                 error ("template argument for %qD uses local type %qT",
11974                        tmpl, t);
11975             }
11976           return true;
11977         }
11978       /* In order to avoid all sorts of complications, we do not
11979          allow variably-modified types as template arguments.  */
11980       else if (variably_modified_type_p (t, NULL_TREE))
11981         {
11982           if (complain & tf_error)
11983             error ("%qT is a variably modified type", t);
11984           return true;
11985         }
11986     }
11987   /* A non-type argument of integral or enumerated type must be a
11988      constant.  */
11989   else if (TREE_TYPE (t)
11990            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
11991            && !TREE_CONSTANT (t))
11992     {
11993       if (complain & tf_error)
11994         error ("integral expression %qE is not constant", t);
11995       return true;
11996     }
11997   return false;
11998 }
11999
12000 static bool
12001 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12002 {
12003   int ix, len = DECL_NTPARMS (tmpl);
12004   bool result = false;
12005
12006   for (ix = 0; ix != len; ix++)
12007     {
12008       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12009         result = true;
12010     }
12011   if (result && (complain & tf_error))
12012     error ("  trying to instantiate %qD", tmpl);
12013   return result;
12014 }
12015
12016 /* Instantiate the indicated variable or function template TMPL with
12017    the template arguments in TARG_PTR.  */
12018
12019 tree
12020 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
12021 {
12022   tree fndecl;
12023   tree gen_tmpl;
12024   tree spec;
12025   HOST_WIDE_INT saved_processing_template_decl;
12026
12027   if (tmpl == error_mark_node)
12028     return error_mark_node;
12029
12030   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12031
12032   /* If this function is a clone, handle it specially.  */
12033   if (DECL_CLONED_FUNCTION_P (tmpl))
12034     {
12035       tree spec;
12036       tree clone;
12037
12038       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
12039                                    complain);
12040       if (spec == error_mark_node)
12041         return error_mark_node;
12042
12043       /* Look for the clone.  */
12044       FOR_EACH_CLONE (clone, spec)
12045         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12046           return clone;
12047       /* We should always have found the clone by now.  */
12048       gcc_unreachable ();
12049       return NULL_TREE;
12050     }
12051
12052   /* Check to see if we already have this specialization.  */
12053   spec = retrieve_specialization (tmpl, targ_ptr,
12054                                   /*class_specializations_p=*/false);
12055   if (spec != NULL_TREE)
12056     return spec;
12057
12058   gen_tmpl = most_general_template (tmpl);
12059   if (tmpl != gen_tmpl)
12060     {
12061       /* The TMPL is a partial instantiation.  To get a full set of
12062          arguments we must add the arguments used to perform the
12063          partial instantiation.  */
12064       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12065                                               targ_ptr);
12066
12067       /* Check to see if we already have this specialization.  */
12068       spec = retrieve_specialization (gen_tmpl, targ_ptr,
12069                                       /*class_specializations_p=*/false);
12070       if (spec != NULL_TREE)
12071         return spec;
12072     }
12073
12074   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12075                                complain))
12076     return error_mark_node;
12077
12078   /* We are building a FUNCTION_DECL, during which the access of its
12079      parameters and return types have to be checked.  However this
12080      FUNCTION_DECL which is the desired context for access checking
12081      is not built yet.  We solve this chicken-and-egg problem by
12082      deferring all checks until we have the FUNCTION_DECL.  */
12083   push_deferring_access_checks (dk_deferred);
12084
12085   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12086      (because, for example, we have encountered a non-dependent
12087      function call in the body of a template function and must now
12088      determine which of several overloaded functions will be called),
12089      within the instantiation itself we are not processing a
12090      template.  */  
12091   saved_processing_template_decl = processing_template_decl;
12092   processing_template_decl = 0;
12093   /* Substitute template parameters to obtain the specialization.  */
12094   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12095                    targ_ptr, complain, gen_tmpl);
12096   processing_template_decl = saved_processing_template_decl;
12097   if (fndecl == error_mark_node)
12098     return error_mark_node;
12099
12100   /* Now we know the specialization, compute access previously
12101      deferred.  */
12102   push_access_scope (fndecl);
12103   perform_deferred_access_checks ();
12104   pop_access_scope (fndecl);
12105   pop_deferring_access_checks ();
12106
12107   /* The DECL_TI_TEMPLATE should always be the immediate parent
12108      template, not the most general template.  */
12109   DECL_TI_TEMPLATE (fndecl) = tmpl;
12110
12111   /* If we've just instantiated the main entry point for a function,
12112      instantiate all the alternate entry points as well.  We do this
12113      by cloning the instantiation of the main entry point, not by
12114      instantiating the template clones.  */
12115   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12116     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12117
12118   return fndecl;
12119 }
12120
12121 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
12122    arguments that are being used when calling it.  TARGS is a vector
12123    into which the deduced template arguments are placed.
12124
12125    Return zero for success, 2 for an incomplete match that doesn't resolve
12126    all the types, and 1 for complete failure.  An error message will be
12127    printed only for an incomplete match.
12128
12129    If FN is a conversion operator, or we are trying to produce a specific
12130    specialization, RETURN_TYPE is the return type desired.
12131
12132    The EXPLICIT_TARGS are explicit template arguments provided via a
12133    template-id.
12134
12135    The parameter STRICT is one of:
12136
12137    DEDUCE_CALL:
12138      We are deducing arguments for a function call, as in
12139      [temp.deduct.call].
12140
12141    DEDUCE_CONV:
12142      We are deducing arguments for a conversion function, as in
12143      [temp.deduct.conv].
12144
12145    DEDUCE_EXACT:
12146      We are deducing arguments when doing an explicit instantiation
12147      as in [temp.explicit], when determining an explicit specialization
12148      as in [temp.expl.spec], or when taking the address of a function
12149      template, as in [temp.deduct.funcaddr].  */
12150
12151 int
12152 fn_type_unification (tree fn,
12153                      tree explicit_targs,
12154                      tree targs,
12155                      tree args,
12156                      tree return_type,
12157                      unification_kind_t strict,
12158                      int flags)
12159 {
12160   tree parms;
12161   tree fntype;
12162   int result;
12163   bool incomplete_argument_packs_p = false;
12164
12165   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12166
12167   fntype = TREE_TYPE (fn);
12168   if (explicit_targs)
12169     {
12170       /* [temp.deduct]
12171
12172          The specified template arguments must match the template
12173          parameters in kind (i.e., type, nontype, template), and there
12174          must not be more arguments than there are parameters;
12175          otherwise type deduction fails.
12176
12177          Nontype arguments must match the types of the corresponding
12178          nontype template parameters, or must be convertible to the
12179          types of the corresponding nontype parameters as specified in
12180          _temp.arg.nontype_, otherwise type deduction fails.
12181
12182          All references in the function type of the function template
12183          to the corresponding template parameters are replaced by the
12184          specified template argument values.  If a substitution in a
12185          template parameter or in the function type of the function
12186          template results in an invalid type, type deduction fails.  */
12187       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12188       int i, len = TREE_VEC_LENGTH (tparms);
12189       tree converted_args;
12190       bool incomplete = false;
12191
12192       if (explicit_targs == error_mark_node)
12193         return 1;
12194
12195       converted_args
12196         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12197                                   /*require_all_args=*/false,
12198                                   /*use_default_args=*/false));
12199       if (converted_args == error_mark_node)
12200         return 1;
12201
12202       /* Substitute the explicit args into the function type.  This is
12203          necessary so that, for instance, explicitly declared function
12204          arguments can match null pointed constants.  If we were given
12205          an incomplete set of explicit args, we must not do semantic
12206          processing during substitution as we could create partial
12207          instantiations.  */
12208       for (i = 0; i < len; i++)
12209         {
12210           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12211           bool parameter_pack = false;
12212
12213           /* Dig out the actual parm.  */
12214           if (TREE_CODE (parm) == TYPE_DECL
12215               || TREE_CODE (parm) == TEMPLATE_DECL)
12216             {
12217               parm = TREE_TYPE (parm);
12218               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12219             }
12220           else if (TREE_CODE (parm) == PARM_DECL)
12221             {
12222               parm = DECL_INITIAL (parm);
12223               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12224             }
12225
12226           if (parameter_pack)
12227             {
12228               int level, idx;
12229               tree targ;
12230               template_parm_level_and_index (parm, &level, &idx);
12231
12232               /* Mark the argument pack as "incomplete". We could
12233                  still deduce more arguments during unification.  */
12234               targ = TMPL_ARG (converted_args, level, idx);
12235               if (targ)
12236                 {
12237                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12238                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12239                     = ARGUMENT_PACK_ARGS (targ);
12240                 }
12241
12242               /* We have some incomplete argument packs.  */
12243               incomplete_argument_packs_p = true;
12244             }
12245         }
12246
12247       if (incomplete_argument_packs_p)
12248         /* Any substitution is guaranteed to be incomplete if there
12249            are incomplete argument packs, because we can still deduce
12250            more arguments.  */
12251         incomplete = 1;
12252       else
12253         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12254
12255       processing_template_decl += incomplete;
12256       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12257       processing_template_decl -= incomplete;
12258
12259       if (fntype == error_mark_node)
12260         return 1;
12261
12262       /* Place the explicitly specified arguments in TARGS.  */
12263       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12264         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12265     }
12266
12267   /* Never do unification on the 'this' parameter.  */
12268   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12269
12270   if (return_type)
12271     {
12272       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12273       args = tree_cons (NULL_TREE, return_type, args);
12274     }
12275
12276   /* We allow incomplete unification without an error message here
12277      because the standard doesn't seem to explicitly prohibit it.  Our
12278      callers must be ready to deal with unification failures in any
12279      event.  */
12280   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12281                                   targs, parms, args, /*subr=*/0,
12282                                   strict, flags);
12283
12284   if (result == 0 && incomplete_argument_packs_p)
12285     {
12286       int i, len = NUM_TMPL_ARGS (targs);
12287
12288       /* Clear the "incomplete" flags on all argument packs.  */
12289       for (i = 0; i < len; i++)
12290         {
12291           tree arg = TREE_VEC_ELT (targs, i);
12292           if (ARGUMENT_PACK_P (arg))
12293             {
12294               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12295               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12296             }
12297         }
12298     }
12299
12300   /* Now that we have bindings for all of the template arguments,
12301      ensure that the arguments deduced for the template template
12302      parameters have compatible template parameter lists.  We cannot
12303      check this property before we have deduced all template
12304      arguments, because the template parameter types of a template
12305      template parameter might depend on prior template parameters
12306      deduced after the template template parameter.  The following
12307      ill-formed example illustrates this issue:
12308
12309        template<typename T, template<T> class C> void f(C<5>, T);
12310
12311        template<int N> struct X {};
12312
12313        void g() {
12314          f(X<5>(), 5l); // error: template argument deduction fails
12315        }
12316
12317      The template parameter list of 'C' depends on the template type
12318      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12319      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12320      time that we deduce 'C'.  */
12321   if (result == 0
12322       && !template_template_parm_bindings_ok_p 
12323            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12324     return 1;
12325
12326   if (result == 0)
12327     /* All is well so far.  Now, check:
12328
12329        [temp.deduct]
12330
12331        When all template arguments have been deduced, all uses of
12332        template parameters in nondeduced contexts are replaced with
12333        the corresponding deduced argument values.  If the
12334        substitution results in an invalid type, as described above,
12335        type deduction fails.  */
12336     {
12337       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
12338       if (substed == error_mark_node)
12339         return 1;
12340
12341       /* If we're looking for an exact match, check that what we got
12342          is indeed an exact match.  It might not be if some template
12343          parameters are used in non-deduced contexts.  */
12344       if (strict == DEDUCE_EXACT)
12345         {
12346           tree sarg
12347             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
12348           tree arg = args;
12349           if (return_type)
12350             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
12351           for (; arg && sarg;
12352                arg = TREE_CHAIN (arg), sarg = TREE_CHAIN (sarg))
12353             if (!same_type_p (TREE_VALUE (arg), TREE_VALUE (sarg)))
12354               return 1;
12355         }
12356     }
12357
12358   return result;
12359 }
12360
12361 /* Adjust types before performing type deduction, as described in
12362    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12363    sections are symmetric.  PARM is the type of a function parameter
12364    or the return type of the conversion function.  ARG is the type of
12365    the argument passed to the call, or the type of the value
12366    initialized with the result of the conversion function.
12367    ARG_EXPR is the original argument expression, which may be null.  */
12368
12369 static int
12370 maybe_adjust_types_for_deduction (unification_kind_t strict,
12371                                   tree* parm,
12372                                   tree* arg,
12373                                   tree arg_expr)
12374 {
12375   int result = 0;
12376
12377   switch (strict)
12378     {
12379     case DEDUCE_CALL:
12380       break;
12381
12382     case DEDUCE_CONV:
12383       {
12384         /* Swap PARM and ARG throughout the remainder of this
12385            function; the handling is precisely symmetric since PARM
12386            will initialize ARG rather than vice versa.  */
12387         tree* temp = parm;
12388         parm = arg;
12389         arg = temp;
12390         break;
12391       }
12392
12393     case DEDUCE_EXACT:
12394       /* There is nothing to do in this case.  */
12395       return 0;
12396
12397     default:
12398       gcc_unreachable ();
12399     }
12400
12401   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12402     {
12403       /* [temp.deduct.call]
12404
12405          If P is not a reference type:
12406
12407          --If A is an array type, the pointer type produced by the
12408          array-to-pointer standard conversion (_conv.array_) is
12409          used in place of A for type deduction; otherwise,
12410
12411          --If A is a function type, the pointer type produced by
12412          the function-to-pointer standard conversion
12413          (_conv.func_) is used in place of A for type deduction;
12414          otherwise,
12415
12416          --If A is a cv-qualified type, the top level
12417          cv-qualifiers of A's type are ignored for type
12418          deduction.  */
12419       if (TREE_CODE (*arg) == ARRAY_TYPE)
12420         *arg = build_pointer_type (TREE_TYPE (*arg));
12421       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12422         *arg = build_pointer_type (*arg);
12423       else
12424         *arg = TYPE_MAIN_VARIANT (*arg);
12425     }
12426
12427   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12428      of the form T&&, where T is a template parameter, and the argument
12429      is an lvalue, T is deduced as A& */
12430   if (TREE_CODE (*parm) == REFERENCE_TYPE
12431       && TYPE_REF_IS_RVALUE (*parm)
12432       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12433       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12434       && arg_expr && real_lvalue_p (arg_expr))
12435     *arg = build_reference_type (*arg);
12436
12437   /* [temp.deduct.call]
12438
12439      If P is a cv-qualified type, the top level cv-qualifiers
12440      of P's type are ignored for type deduction.  If P is a
12441      reference type, the type referred to by P is used for
12442      type deduction.  */
12443   *parm = TYPE_MAIN_VARIANT (*parm);
12444   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12445     {
12446       *parm = TREE_TYPE (*parm);
12447       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12448     }
12449
12450   /* DR 322. For conversion deduction, remove a reference type on parm
12451      too (which has been swapped into ARG).  */
12452   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12453     *arg = TREE_TYPE (*arg);
12454
12455   return result;
12456 }
12457
12458 /* Most parms like fn_type_unification.
12459
12460    If SUBR is 1, we're being called recursively (to unify the
12461    arguments of a function or method parameter of a function
12462    template). */
12463
12464 static int
12465 type_unification_real (tree tparms,
12466                        tree targs,
12467                        tree xparms,
12468                        tree xargs,
12469                        int subr,
12470                        unification_kind_t strict,
12471                        int flags)
12472 {
12473   tree parm, arg, arg_expr;
12474   int i;
12475   int ntparms = TREE_VEC_LENGTH (tparms);
12476   int sub_strict;
12477   int saw_undeduced = 0;
12478   tree parms, args;
12479
12480   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
12481   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
12482   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
12483   gcc_assert (ntparms > 0);
12484
12485   switch (strict)
12486     {
12487     case DEDUCE_CALL:
12488       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12489                     | UNIFY_ALLOW_DERIVED);
12490       break;
12491
12492     case DEDUCE_CONV:
12493       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12494       break;
12495
12496     case DEDUCE_EXACT:
12497       sub_strict = UNIFY_ALLOW_NONE;
12498       break;
12499
12500     default:
12501       gcc_unreachable ();
12502     }
12503
12504  again:
12505   parms = xparms;
12506   args = xargs;
12507
12508   while (parms && parms != void_list_node
12509          && args && args != void_list_node)
12510     {
12511       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12512         break;
12513
12514       parm = TREE_VALUE (parms);
12515       parms = TREE_CHAIN (parms);
12516       arg = TREE_VALUE (args);
12517       args = TREE_CHAIN (args);
12518       arg_expr = NULL;
12519
12520       if (arg == error_mark_node)
12521         return 1;
12522       if (arg == unknown_type_node)
12523         /* We can't deduce anything from this, but we might get all the
12524            template args from other function args.  */
12525         continue;
12526
12527       /* Conversions will be performed on a function argument that
12528          corresponds with a function parameter that contains only
12529          non-deducible template parameters and explicitly specified
12530          template parameters.  */
12531       if (!uses_template_parms (parm))
12532         {
12533           tree type;
12534
12535           if (!TYPE_P (arg))
12536             type = TREE_TYPE (arg);
12537           else
12538             type = arg;
12539
12540           if (same_type_p (parm, type))
12541             continue;
12542           if (strict != DEDUCE_EXACT
12543               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12544                                   flags))
12545             continue;
12546
12547           return 1;
12548         }
12549
12550       if (!TYPE_P (arg))
12551         {
12552           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12553           if (type_unknown_p (arg))
12554             {
12555               /* [temp.deduct.type] 
12556
12557                  A template-argument can be deduced from a pointer to
12558                  function or pointer to member function argument if
12559                  the set of overloaded functions does not contain
12560                  function templates and at most one of a set of
12561                  overloaded functions provides a unique match.  */
12562               if (resolve_overloaded_unification
12563                   (tparms, targs, parm, arg, strict, sub_strict))
12564                 continue;
12565
12566               return 1;
12567             }
12568           arg_expr = arg;
12569           arg = unlowered_expr_type (arg);
12570           if (arg == error_mark_node)
12571             return 1;
12572         }
12573
12574       {
12575         int arg_strict = sub_strict;
12576
12577         if (!subr)
12578           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12579                                                           arg_expr);
12580
12581         if (arg == init_list_type_node && arg_expr)
12582           arg = arg_expr;
12583         if (unify (tparms, targs, parm, arg, arg_strict))
12584           return 1;
12585       }
12586     }
12587
12588
12589   if (parms 
12590       && parms != void_list_node
12591       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12592     {
12593       /* Unify the remaining arguments with the pack expansion type.  */
12594       tree argvec;
12595       tree parmvec = make_tree_vec (1);
12596       int len = 0;
12597       tree t;
12598
12599       /* Count the number of arguments that remain.  */
12600       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
12601         len++;
12602         
12603       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12604       argvec = make_tree_vec (len);
12605       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
12606         {
12607           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
12608           ++i;
12609         }
12610
12611       /* Copy the parameter into parmvec.  */
12612       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12613       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12614                                 /*call_args_p=*/true, /*subr=*/subr))
12615         return 1;
12616
12617       /* Advance to the end of the list of parameters.  */
12618       parms = TREE_CHAIN (parms);
12619     }
12620
12621   /* Fail if we've reached the end of the parm list, and more args
12622      are present, and the parm list isn't variadic.  */
12623   if (args && args != void_list_node && parms == void_list_node)
12624     return 1;
12625   /* Fail if parms are left and they don't have default values.  */
12626   if (parms && parms != void_list_node
12627       && TREE_PURPOSE (parms) == NULL_TREE)
12628     return 1;
12629
12630   if (!subr)
12631     for (i = 0; i < ntparms; i++)
12632       if (!TREE_VEC_ELT (targs, i))
12633         {
12634           tree tparm;
12635
12636           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12637             continue;
12638
12639           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12640
12641           /* If this is an undeduced nontype parameter that depends on
12642              a type parameter, try another pass; its type may have been
12643              deduced from a later argument than the one from which
12644              this parameter can be deduced.  */
12645           if (TREE_CODE (tparm) == PARM_DECL
12646               && uses_template_parms (TREE_TYPE (tparm))
12647               && !saw_undeduced++)
12648             goto again;
12649
12650           /* Core issue #226 (C++0x) [temp.deduct]:
12651
12652                If a template argument has not been deduced, its
12653                default template argument, if any, is used. 
12654
12655              When we are in C++98 mode, TREE_PURPOSE will either
12656              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12657              to explicitly check cxx_dialect here.  */
12658           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12659             {
12660               tree arg = tsubst_template_arg
12661                                 (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)),
12662                                  targs, tf_none, NULL_TREE);
12663               if (arg == error_mark_node)
12664                 return 1;
12665               else
12666                 {
12667                   TREE_VEC_ELT (targs, i) = arg;
12668                   continue;
12669                 }
12670             }
12671
12672           /* If the type parameter is a parameter pack, then it will
12673              be deduced to an empty parameter pack.  */
12674           if (template_parameter_pack_p (tparm))
12675             {
12676               tree arg;
12677
12678               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12679                 {
12680                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12681                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12682                   TREE_CONSTANT (arg) = 1;
12683                 }
12684               else
12685                 arg = make_node (TYPE_ARGUMENT_PACK);
12686
12687               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12688
12689               TREE_VEC_ELT (targs, i) = arg;
12690               continue;
12691             }
12692
12693           return 2;
12694         }
12695
12696   return 0;
12697 }
12698
12699 /* Subroutine of type_unification_real.  Args are like the variables
12700    at the call site.  ARG is an overloaded function (or template-id);
12701    we try deducing template args from each of the overloads, and if
12702    only one succeeds, we go with that.  Modifies TARGS and returns
12703    true on success.  */
12704
12705 static bool
12706 resolve_overloaded_unification (tree tparms,
12707                                 tree targs,
12708                                 tree parm,
12709                                 tree arg,
12710                                 unification_kind_t strict,
12711                                 int sub_strict)
12712 {
12713   tree tempargs = copy_node (targs);
12714   int good = 0;
12715   tree goodfn = NULL_TREE;
12716   bool addr_p;
12717
12718   if (TREE_CODE (arg) == ADDR_EXPR)
12719     {
12720       arg = TREE_OPERAND (arg, 0);
12721       addr_p = true;
12722     }
12723   else
12724     addr_p = false;
12725
12726   if (TREE_CODE (arg) == COMPONENT_REF)
12727     /* Handle `&x' where `x' is some static or non-static member
12728        function name.  */
12729     arg = TREE_OPERAND (arg, 1);
12730
12731   if (TREE_CODE (arg) == OFFSET_REF)
12732     arg = TREE_OPERAND (arg, 1);
12733
12734   /* Strip baselink information.  */
12735   if (BASELINK_P (arg))
12736     arg = BASELINK_FUNCTIONS (arg);
12737
12738   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12739     {
12740       /* If we got some explicit template args, we need to plug them into
12741          the affected templates before we try to unify, in case the
12742          explicit args will completely resolve the templates in question.  */
12743
12744       tree expl_subargs = TREE_OPERAND (arg, 1);
12745       arg = TREE_OPERAND (arg, 0);
12746
12747       for (; arg; arg = OVL_NEXT (arg))
12748         {
12749           tree fn = OVL_CURRENT (arg);
12750           tree subargs, elem;
12751
12752           if (TREE_CODE (fn) != TEMPLATE_DECL)
12753             continue;
12754
12755           ++processing_template_decl;
12756           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12757                                   expl_subargs, /*check_ret=*/false);
12758           if (subargs)
12759             {
12760               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12761               if (try_one_overload (tparms, targs, tempargs, parm,
12762                                     elem, strict, sub_strict, addr_p)
12763                   && (!goodfn || !decls_match (goodfn, elem)))
12764                 {
12765                   goodfn = elem;
12766                   ++good;
12767                 }
12768             }
12769           --processing_template_decl;
12770         }
12771     }
12772   else if (TREE_CODE (arg) != OVERLOAD
12773            && TREE_CODE (arg) != FUNCTION_DECL)
12774     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12775        -- but the deduction does not succeed because the expression is
12776        not just the function on its own.  */
12777     return false;
12778   else
12779     for (; arg; arg = OVL_NEXT (arg))
12780       if (try_one_overload (tparms, targs, tempargs, parm,
12781                             TREE_TYPE (OVL_CURRENT (arg)),
12782                             strict, sub_strict, addr_p)
12783           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
12784         {
12785           goodfn = OVL_CURRENT (arg);
12786           ++good;
12787         }
12788
12789   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12790      to function or pointer to member function argument if the set of
12791      overloaded functions does not contain function templates and at most
12792      one of a set of overloaded functions provides a unique match.
12793
12794      So if we found multiple possibilities, we return success but don't
12795      deduce anything.  */
12796
12797   if (good == 1)
12798     {
12799       int i = TREE_VEC_LENGTH (targs);
12800       for (; i--; )
12801         if (TREE_VEC_ELT (tempargs, i))
12802           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12803     }
12804   if (good)
12805     return true;
12806
12807   return false;
12808 }
12809
12810 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12811    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12812    different overloads deduce different arguments for a given parm.
12813    ADDR_P is true if the expression for which deduction is being
12814    performed was of the form "& fn" rather than simply "fn".
12815
12816    Returns 1 on success.  */
12817
12818 static int
12819 try_one_overload (tree tparms,
12820                   tree orig_targs,
12821                   tree targs,
12822                   tree parm,
12823                   tree arg,
12824                   unification_kind_t strict,
12825                   int sub_strict,
12826                   bool addr_p)
12827 {
12828   int nargs;
12829   tree tempargs;
12830   int i;
12831
12832   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12833      to function or pointer to member function argument if the set of
12834      overloaded functions does not contain function templates and at most
12835      one of a set of overloaded functions provides a unique match.
12836
12837      So if this is a template, just return success.  */
12838
12839   if (uses_template_parms (arg))
12840     return 1;
12841
12842   if (TREE_CODE (arg) == METHOD_TYPE)
12843     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12844   else if (addr_p)
12845     arg = build_pointer_type (arg);
12846
12847   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12848
12849   /* We don't copy orig_targs for this because if we have already deduced
12850      some template args from previous args, unify would complain when we
12851      try to deduce a template parameter for the same argument, even though
12852      there isn't really a conflict.  */
12853   nargs = TREE_VEC_LENGTH (targs);
12854   tempargs = make_tree_vec (nargs);
12855
12856   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12857     return 0;
12858
12859   /* First make sure we didn't deduce anything that conflicts with
12860      explicitly specified args.  */
12861   for (i = nargs; i--; )
12862     {
12863       tree elt = TREE_VEC_ELT (tempargs, i);
12864       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12865
12866       if (!elt)
12867         /*NOP*/;
12868       else if (uses_template_parms (elt))
12869         /* Since we're unifying against ourselves, we will fill in
12870            template args used in the function parm list with our own
12871            template parms.  Discard them.  */
12872         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12873       else if (oldelt && !template_args_equal (oldelt, elt))
12874         return 0;
12875     }
12876
12877   for (i = nargs; i--; )
12878     {
12879       tree elt = TREE_VEC_ELT (tempargs, i);
12880
12881       if (elt)
12882         TREE_VEC_ELT (targs, i) = elt;
12883     }
12884
12885   return 1;
12886 }
12887
12888 /* PARM is a template class (perhaps with unbound template
12889    parameters).  ARG is a fully instantiated type.  If ARG can be
12890    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12891    TARGS are as for unify.  */
12892
12893 static tree
12894 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12895 {
12896   tree copy_of_targs;
12897
12898   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12899       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12900           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12901     return NULL_TREE;
12902
12903   /* We need to make a new template argument vector for the call to
12904      unify.  If we used TARGS, we'd clutter it up with the result of
12905      the attempted unification, even if this class didn't work out.
12906      We also don't want to commit ourselves to all the unifications
12907      we've already done, since unification is supposed to be done on
12908      an argument-by-argument basis.  In other words, consider the
12909      following pathological case:
12910
12911        template <int I, int J, int K>
12912        struct S {};
12913
12914        template <int I, int J>
12915        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12916
12917        template <int I, int J, int K>
12918        void f(S<I, J, K>, S<I, I, I>);
12919
12920        void g() {
12921          S<0, 0, 0> s0;
12922          S<0, 1, 2> s2;
12923
12924          f(s0, s2);
12925        }
12926
12927      Now, by the time we consider the unification involving `s2', we
12928      already know that we must have `f<0, 0, 0>'.  But, even though
12929      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
12930      because there are two ways to unify base classes of S<0, 1, 2>
12931      with S<I, I, I>.  If we kept the already deduced knowledge, we
12932      would reject the possibility I=1.  */
12933   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
12934
12935   /* If unification failed, we're done.  */
12936   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
12937              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
12938     return NULL_TREE;
12939
12940   return arg;
12941 }
12942
12943 /* Given a template type PARM and a class type ARG, find the unique
12944    base type in ARG that is an instance of PARM.  We do not examine
12945    ARG itself; only its base-classes.  If there is not exactly one
12946    appropriate base class, return NULL_TREE.  PARM may be the type of
12947    a partial specialization, as well as a plain template type.  Used
12948    by unify.  */
12949
12950 static tree
12951 get_template_base (tree tparms, tree targs, tree parm, tree arg)
12952 {
12953   tree rval = NULL_TREE;
12954   tree binfo;
12955
12956   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
12957
12958   binfo = TYPE_BINFO (complete_type (arg));
12959   if (!binfo)
12960     /* The type could not be completed.  */
12961     return NULL_TREE;
12962
12963   /* Walk in inheritance graph order.  The search order is not
12964      important, and this avoids multiple walks of virtual bases.  */
12965   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
12966     {
12967       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
12968
12969       if (r)
12970         {
12971           /* If there is more than one satisfactory baseclass, then:
12972
12973                [temp.deduct.call]
12974
12975               If they yield more than one possible deduced A, the type
12976               deduction fails.
12977
12978              applies.  */
12979           if (rval && !same_type_p (r, rval))
12980             return NULL_TREE;
12981
12982           rval = r;
12983         }
12984     }
12985
12986   return rval;
12987 }
12988
12989 /* Returns the level of DECL, which declares a template parameter.  */
12990
12991 static int
12992 template_decl_level (tree decl)
12993 {
12994   switch (TREE_CODE (decl))
12995     {
12996     case TYPE_DECL:
12997     case TEMPLATE_DECL:
12998       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
12999
13000     case PARM_DECL:
13001       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13002
13003     default:
13004       gcc_unreachable ();
13005     }
13006   return 0;
13007 }
13008
13009 /* Decide whether ARG can be unified with PARM, considering only the
13010    cv-qualifiers of each type, given STRICT as documented for unify.
13011    Returns nonzero iff the unification is OK on that basis.  */
13012
13013 static int
13014 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13015 {
13016   int arg_quals = cp_type_quals (arg);
13017   int parm_quals = cp_type_quals (parm);
13018
13019   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13020       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13021     {
13022       /*  Although a CVR qualifier is ignored when being applied to a
13023           substituted template parameter ([8.3.2]/1 for example), that
13024           does not apply during deduction [14.8.2.4]/1, (even though
13025           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13026           this).  Except when we're allowing additional CV qualifiers
13027           at the outer level [14.8.2.1]/3,1st bullet.  */
13028       if ((TREE_CODE (arg) == REFERENCE_TYPE
13029            || TREE_CODE (arg) == FUNCTION_TYPE
13030            || TREE_CODE (arg) == METHOD_TYPE)
13031           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13032         return 0;
13033
13034       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13035           && (parm_quals & TYPE_QUAL_RESTRICT))
13036         return 0;
13037     }
13038
13039   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13040       && (arg_quals & parm_quals) != parm_quals)
13041     return 0;
13042
13043   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13044       && (parm_quals & arg_quals) != arg_quals)
13045     return 0;
13046
13047   return 1;
13048 }
13049
13050 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13051 void 
13052 template_parm_level_and_index (tree parm, int* level, int* index)
13053 {
13054   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13055       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13056       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13057     {
13058       *index = TEMPLATE_TYPE_IDX (parm);
13059       *level = TEMPLATE_TYPE_LEVEL (parm);
13060     }
13061   else
13062     {
13063       *index = TEMPLATE_PARM_IDX (parm);
13064       *level = TEMPLATE_PARM_LEVEL (parm);
13065     }
13066 }
13067
13068 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13069    expansion at the end of PACKED_PARMS. Returns 0 if the type
13070    deduction succeeds, 1 otherwise. STRICT is the same as in
13071    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13072    call argument list. We'll need to adjust the arguments to make them
13073    types. SUBR tells us if this is from a recursive call to
13074    type_unification_real.  */
13075 int
13076 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13077                       tree packed_args, int strict, bool call_args_p,
13078                       bool subr)
13079 {
13080   tree parm 
13081     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13082   tree pattern = PACK_EXPANSION_PATTERN (parm);
13083   tree pack, packs = NULL_TREE;
13084   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13085   int len = TREE_VEC_LENGTH (packed_args);
13086
13087   /* Determine the parameter packs we will be deducing from the
13088      pattern, and record their current deductions.  */
13089   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13090        pack; pack = TREE_CHAIN (pack))
13091     {
13092       tree parm_pack = TREE_VALUE (pack);
13093       int idx, level;
13094
13095       /* Determine the index and level of this parameter pack.  */
13096       template_parm_level_and_index (parm_pack, &level, &idx);
13097
13098       /* Keep track of the parameter packs and their corresponding
13099          argument packs.  */
13100       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13101       TREE_TYPE (packs) = make_tree_vec (len - start);
13102     }
13103   
13104   /* Loop through all of the arguments that have not yet been
13105      unified and unify each with the pattern.  */
13106   for (i = start; i < len; i++)
13107     {
13108       tree parm = pattern;
13109
13110       /* For each parameter pack, clear out the deduced value so that
13111          we can deduce it again.  */
13112       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13113         {
13114           int idx, level;
13115           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13116
13117           TMPL_ARG (targs, level, idx) = NULL_TREE;
13118         }
13119
13120       /* Unify the pattern with the current argument.  */
13121       {
13122         tree arg = TREE_VEC_ELT (packed_args, i);
13123         tree arg_expr = NULL_TREE;
13124         int arg_strict = strict;
13125         bool skip_arg_p = false;
13126
13127         if (call_args_p)
13128           {
13129             int sub_strict;
13130
13131             /* This mirrors what we do in type_unification_real.  */
13132             switch (strict)
13133               {
13134               case DEDUCE_CALL:
13135                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13136                               | UNIFY_ALLOW_MORE_CV_QUAL
13137                               | UNIFY_ALLOW_DERIVED);
13138                 break;
13139                 
13140               case DEDUCE_CONV:
13141                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13142                 break;
13143                 
13144               case DEDUCE_EXACT:
13145                 sub_strict = UNIFY_ALLOW_NONE;
13146                 break;
13147                 
13148               default:
13149                 gcc_unreachable ();
13150               }
13151
13152             if (!TYPE_P (arg))
13153               {
13154                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13155                 if (type_unknown_p (arg))
13156                   {
13157                     /* [temp.deduct.type] A template-argument can be
13158                        deduced from a pointer to function or pointer
13159                        to member function argument if the set of
13160                        overloaded functions does not contain function
13161                        templates and at most one of a set of
13162                        overloaded functions provides a unique
13163                        match.  */
13164
13165                     if (resolve_overloaded_unification
13166                         (tparms, targs, parm, arg, strict, sub_strict)
13167                         != 0)
13168                       return 1;
13169                     skip_arg_p = true;
13170                   }
13171
13172                 if (!skip_arg_p)
13173                   {
13174                     arg_expr = arg;
13175                     arg = unlowered_expr_type (arg);
13176                     if (arg == error_mark_node)
13177                       return 1;
13178                   }
13179               }
13180       
13181             arg_strict = sub_strict;
13182
13183             if (!subr)
13184               arg_strict |= 
13185                 maybe_adjust_types_for_deduction (strict, &parm, &arg, 
13186                                                   arg_expr);
13187           }
13188
13189         if (!skip_arg_p)
13190           {
13191             if (unify (tparms, targs, parm, arg, arg_strict))
13192               return 1;
13193           }
13194       }
13195
13196       /* For each parameter pack, collect the deduced value.  */
13197       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13198         {
13199           int idx, level;
13200           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13201
13202           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13203             TMPL_ARG (targs, level, idx);
13204         }
13205     }
13206
13207   /* Verify that the results of unification with the parameter packs
13208      produce results consistent with what we've seen before, and make
13209      the deduced argument packs available.  */
13210   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13211     {
13212       tree old_pack = TREE_VALUE (pack);
13213       tree new_args = TREE_TYPE (pack);
13214       int i, len = TREE_VEC_LENGTH (new_args);
13215       bool nondeduced_p = false;
13216
13217       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13218          actually deduce anything.  */
13219       for (i = 0; i < len && !nondeduced_p; ++i)
13220         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13221           nondeduced_p = true;
13222       if (nondeduced_p)
13223         continue;
13224
13225       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13226         {
13227           /* Prepend the explicit arguments onto NEW_ARGS.  */
13228           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13229           tree old_args = new_args;
13230           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13231           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13232
13233           /* Copy the explicit arguments.  */
13234           new_args = make_tree_vec (len);
13235           for (i = 0; i < explicit_len; i++)
13236             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13237
13238           /* Copy the deduced arguments.  */
13239           for (; i < len; i++)
13240             TREE_VEC_ELT (new_args, i) =
13241               TREE_VEC_ELT (old_args, i - explicit_len);
13242         }
13243
13244       if (!old_pack)
13245         {
13246           tree result;
13247           int idx, level;
13248           
13249           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13250
13251           /* Build the deduced *_ARGUMENT_PACK.  */
13252           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13253             {
13254               result = make_node (NONTYPE_ARGUMENT_PACK);
13255               TREE_TYPE (result) = 
13256                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13257               TREE_CONSTANT (result) = 1;
13258             }
13259           else
13260             result = make_node (TYPE_ARGUMENT_PACK);
13261
13262           SET_ARGUMENT_PACK_ARGS (result, new_args);
13263
13264           /* Note the deduced argument packs for this parameter
13265              pack.  */
13266           TMPL_ARG (targs, level, idx) = result;
13267         }
13268       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13269                && (ARGUMENT_PACK_ARGS (old_pack) 
13270                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13271         {
13272           /* We only had the explicitly-provided arguments before, but
13273              now we have a complete set of arguments.  */
13274           int idx, level;
13275           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13276           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13277
13278           /* Keep the original deduced argument pack.  */
13279           TMPL_ARG (targs, level, idx) = old_pack;
13280
13281           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13282           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13283           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13284         }
13285       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13286                                     new_args))
13287         /* Inconsistent unification of this parameter pack.  */
13288         return 1;
13289       else
13290         {
13291           int idx, level;
13292           
13293           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13294
13295           /* Keep the original deduced argument pack.  */
13296           TMPL_ARG (targs, level, idx) = old_pack;
13297         }
13298     }
13299
13300   return 0;
13301 }
13302
13303 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13304    set of template parameters to a template.  TARGS is the bindings
13305    for those template parameters, as determined thus far; TARGS may
13306    include template arguments for outer levels of template parameters
13307    as well.  PARM is a parameter to a template function, or a
13308    subcomponent of that parameter; ARG is the corresponding argument.
13309    This function attempts to match PARM with ARG in a manner
13310    consistent with the existing assignments in TARGS.  If more values
13311    are deduced, then TARGS is updated.
13312
13313    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13314    parameter STRICT is a bitwise or of the following flags:
13315
13316      UNIFY_ALLOW_NONE:
13317        Require an exact match between PARM and ARG.
13318      UNIFY_ALLOW_MORE_CV_QUAL:
13319        Allow the deduced ARG to be more cv-qualified (by qualification
13320        conversion) than ARG.
13321      UNIFY_ALLOW_LESS_CV_QUAL:
13322        Allow the deduced ARG to be less cv-qualified than ARG.
13323      UNIFY_ALLOW_DERIVED:
13324        Allow the deduced ARG to be a template base class of ARG,
13325        or a pointer to a template base class of the type pointed to by
13326        ARG.
13327      UNIFY_ALLOW_INTEGER:
13328        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13329        case for more information.
13330      UNIFY_ALLOW_OUTER_LEVEL:
13331        This is the outermost level of a deduction. Used to determine validity
13332        of qualification conversions. A valid qualification conversion must
13333        have const qualified pointers leading up to the inner type which
13334        requires additional CV quals, except at the outer level, where const
13335        is not required [conv.qual]. It would be normal to set this flag in
13336        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13337      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13338        This is the outermost level of a deduction, and PARM can be more CV
13339        qualified at this point.
13340      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13341        This is the outermost level of a deduction, and PARM can be less CV
13342        qualified at this point.  */
13343
13344 static int
13345 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13346 {
13347   int idx;
13348   tree targ;
13349   tree tparm;
13350   int strict_in = strict;
13351
13352   /* I don't think this will do the right thing with respect to types.
13353      But the only case I've seen it in so far has been array bounds, where
13354      signedness is the only information lost, and I think that will be
13355      okay.  */
13356   while (TREE_CODE (parm) == NOP_EXPR)
13357     parm = TREE_OPERAND (parm, 0);
13358
13359   if (arg == error_mark_node)
13360     return 1;
13361   if (arg == unknown_type_node
13362       || arg == init_list_type_node)
13363     /* We can't deduce anything from this, but we might get all the
13364        template args from other function args.  */
13365     return 0;
13366
13367   /* If PARM uses template parameters, then we can't bail out here,
13368      even if ARG == PARM, since we won't record unifications for the
13369      template parameters.  We might need them if we're trying to
13370      figure out which of two things is more specialized.  */
13371   if (arg == parm && !uses_template_parms (parm))
13372     return 0;
13373
13374   /* Handle init lists early, so the rest of the function can assume
13375      we're dealing with a type. */
13376   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
13377     {
13378       tree elt, elttype;
13379       unsigned i;
13380       tree orig_parm = parm;
13381
13382       /* Replace T with std::initializer_list<T> for deduction.  */
13383       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13384           && flag_deduce_init_list)
13385         parm = listify (parm);
13386
13387       if (!is_std_init_list (parm))
13388         /* We can only deduce from an initializer list argument if the
13389            parameter is std::initializer_list; otherwise this is a
13390            non-deduced context. */
13391         return 0;
13392
13393       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
13394
13395       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
13396         {
13397           int elt_strict = strict;
13398           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
13399             {
13400               tree type = TREE_TYPE (elt);
13401               /* It should only be possible to get here for a call.  */
13402               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
13403               elt_strict |= maybe_adjust_types_for_deduction
13404                 (DEDUCE_CALL, &elttype, &type, elt);
13405               elt = type;
13406             }
13407
13408           if (unify (tparms, targs, elttype, elt, elt_strict))
13409             return 1;
13410         }
13411
13412       /* If the std::initializer_list<T> deduction worked, replace the
13413          deduced A with std::initializer_list<A>.  */
13414       if (orig_parm != parm)
13415         {
13416           idx = TEMPLATE_TYPE_IDX (orig_parm);
13417           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13418           targ = listify (targ);
13419           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
13420         }
13421       return 0;
13422     }
13423
13424   /* Immediately reject some pairs that won't unify because of
13425      cv-qualification mismatches.  */
13426   if (TREE_CODE (arg) == TREE_CODE (parm)
13427       && TYPE_P (arg)
13428       /* It is the elements of the array which hold the cv quals of an array
13429          type, and the elements might be template type parms. We'll check
13430          when we recurse.  */
13431       && TREE_CODE (arg) != ARRAY_TYPE
13432       /* We check the cv-qualifiers when unifying with template type
13433          parameters below.  We want to allow ARG `const T' to unify with
13434          PARM `T' for example, when computing which of two templates
13435          is more specialized, for example.  */
13436       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
13437       && !check_cv_quals_for_unify (strict_in, arg, parm))
13438     return 1;
13439
13440   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
13441       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
13442     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
13443   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
13444   strict &= ~UNIFY_ALLOW_DERIVED;
13445   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13446   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
13447
13448   switch (TREE_CODE (parm))
13449     {
13450     case TYPENAME_TYPE:
13451     case SCOPE_REF:
13452     case UNBOUND_CLASS_TEMPLATE:
13453       /* In a type which contains a nested-name-specifier, template
13454          argument values cannot be deduced for template parameters used
13455          within the nested-name-specifier.  */
13456       return 0;
13457
13458     case TEMPLATE_TYPE_PARM:
13459     case TEMPLATE_TEMPLATE_PARM:
13460     case BOUND_TEMPLATE_TEMPLATE_PARM:
13461       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13462       if (tparm == error_mark_node)
13463         return 1;
13464
13465       if (TEMPLATE_TYPE_LEVEL (parm)
13466           != template_decl_level (tparm))
13467         /* The PARM is not one we're trying to unify.  Just check
13468            to see if it matches ARG.  */
13469         return (TREE_CODE (arg) == TREE_CODE (parm)
13470                 && same_type_p (parm, arg)) ? 0 : 1;
13471       idx = TEMPLATE_TYPE_IDX (parm);
13472       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13473       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
13474
13475       /* Check for mixed types and values.  */
13476       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13477            && TREE_CODE (tparm) != TYPE_DECL)
13478           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13479               && TREE_CODE (tparm) != TEMPLATE_DECL))
13480         return 1;
13481
13482       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13483         {
13484           /* ARG must be constructed from a template class or a template
13485              template parameter.  */
13486           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
13487               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
13488             return 1;
13489
13490           {
13491             tree parmvec = TYPE_TI_ARGS (parm);
13492             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
13493             tree parm_parms 
13494               = DECL_INNERMOST_TEMPLATE_PARMS
13495                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
13496             int i, len;
13497             int parm_variadic_p = 0;
13498
13499             /* The resolution to DR150 makes clear that default
13500                arguments for an N-argument may not be used to bind T
13501                to a template template parameter with fewer than N
13502                parameters.  It is not safe to permit the binding of
13503                default arguments as an extension, as that may change
13504                the meaning of a conforming program.  Consider:
13505
13506                   struct Dense { static const unsigned int dim = 1; };
13507
13508                   template <template <typename> class View,
13509                             typename Block>
13510                   void operator+(float, View<Block> const&);
13511
13512                   template <typename Block,
13513                             unsigned int Dim = Block::dim>
13514                   struct Lvalue_proxy { operator float() const; };
13515
13516                   void
13517                   test_1d (void) {
13518                     Lvalue_proxy<Dense> p;
13519                     float b;
13520                     b + p;
13521                   }
13522
13523               Here, if Lvalue_proxy is permitted to bind to View, then
13524               the global operator+ will be used; if they are not, the
13525               Lvalue_proxy will be converted to float.  */
13526             if (coerce_template_parms (parm_parms,
13527                                        argvec,
13528                                        TYPE_TI_TEMPLATE (parm),
13529                                        tf_none,
13530                                        /*require_all_args=*/true,
13531                                        /*use_default_args=*/false)
13532                 == error_mark_node)
13533               return 1;
13534
13535             /* Deduce arguments T, i from TT<T> or TT<i>.
13536                We check each element of PARMVEC and ARGVEC individually
13537                rather than the whole TREE_VEC since they can have
13538                different number of elements.  */
13539
13540             parmvec = expand_template_argument_pack (parmvec);
13541             argvec = expand_template_argument_pack (argvec);
13542
13543             len = TREE_VEC_LENGTH (parmvec);
13544
13545             /* Check if the parameters end in a pack, making them
13546                variadic.  */
13547             if (len > 0
13548                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
13549               parm_variadic_p = 1;
13550             
13551             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
13552               return 1;
13553
13554              for (i = 0; i < len - parm_variadic_p; ++i)
13555               {
13556                 if (unify (tparms, targs,
13557                            TREE_VEC_ELT (parmvec, i),
13558                            TREE_VEC_ELT (argvec, i),
13559                            UNIFY_ALLOW_NONE))
13560                   return 1;
13561               }
13562
13563             if (parm_variadic_p
13564                 && unify_pack_expansion (tparms, targs,
13565                                          parmvec, argvec,
13566                                          UNIFY_ALLOW_NONE,
13567                                          /*call_args_p=*/false,
13568                                          /*subr=*/false))
13569               return 1;
13570           }
13571           arg = TYPE_TI_TEMPLATE (arg);
13572
13573           /* Fall through to deduce template name.  */
13574         }
13575
13576       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13577           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13578         {
13579           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13580
13581           /* Simple cases: Value already set, does match or doesn't.  */
13582           if (targ != NULL_TREE && template_args_equal (targ, arg))
13583             return 0;
13584           else if (targ)
13585             return 1;
13586         }
13587       else
13588         {
13589           /* If PARM is `const T' and ARG is only `int', we don't have
13590              a match unless we are allowing additional qualification.
13591              If ARG is `const int' and PARM is just `T' that's OK;
13592              that binds `const int' to `T'.  */
13593           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13594                                          arg, parm))
13595             return 1;
13596
13597           /* Consider the case where ARG is `const volatile int' and
13598              PARM is `const T'.  Then, T should be `volatile int'.  */
13599           arg = cp_build_qualified_type_real
13600             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13601           if (arg == error_mark_node)
13602             return 1;
13603
13604           /* Simple cases: Value already set, does match or doesn't.  */
13605           if (targ != NULL_TREE && same_type_p (targ, arg))
13606             return 0;
13607           else if (targ)
13608             return 1;
13609
13610           /* Make sure that ARG is not a variable-sized array.  (Note
13611              that were talking about variable-sized arrays (like
13612              `int[n]'), rather than arrays of unknown size (like
13613              `int[]').)  We'll get very confused by such a type since
13614              the bound of the array will not be computable in an
13615              instantiation.  Besides, such types are not allowed in
13616              ISO C++, so we can do as we please here.  */
13617           if (variably_modified_type_p (arg, NULL_TREE))
13618             return 1;
13619         }
13620
13621       /* If ARG is a parameter pack or an expansion, we cannot unify
13622          against it unless PARM is also a parameter pack.  */
13623       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13624           && !template_parameter_pack_p (parm))
13625         return 1;
13626
13627       /* If the argument deduction results is a METHOD_TYPE,
13628          then there is a problem.
13629          METHOD_TYPE doesn't map to any real C++ type the result of
13630          the deduction can not be of that type.  */
13631       if (TREE_CODE (arg) == METHOD_TYPE)
13632         return 1;
13633
13634       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13635       return 0;
13636
13637     case TEMPLATE_PARM_INDEX:
13638       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13639       if (tparm == error_mark_node)
13640         return 1;
13641
13642       if (TEMPLATE_PARM_LEVEL (parm)
13643           != template_decl_level (tparm))
13644         /* The PARM is not one we're trying to unify.  Just check
13645            to see if it matches ARG.  */
13646         return !(TREE_CODE (arg) == TREE_CODE (parm)
13647                  && cp_tree_equal (parm, arg));
13648
13649       idx = TEMPLATE_PARM_IDX (parm);
13650       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13651
13652       if (targ)
13653         return !cp_tree_equal (targ, arg);
13654
13655       /* [temp.deduct.type] If, in the declaration of a function template
13656          with a non-type template-parameter, the non-type
13657          template-parameter is used in an expression in the function
13658          parameter-list and, if the corresponding template-argument is
13659          deduced, the template-argument type shall match the type of the
13660          template-parameter exactly, except that a template-argument
13661          deduced from an array bound may be of any integral type.
13662          The non-type parameter might use already deduced type parameters.  */
13663       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13664       if (!TREE_TYPE (arg))
13665         /* Template-parameter dependent expression.  Just accept it for now.
13666            It will later be processed in convert_template_argument.  */
13667         ;
13668       else if (same_type_p (TREE_TYPE (arg), tparm))
13669         /* OK */;
13670       else if ((strict & UNIFY_ALLOW_INTEGER)
13671                && (TREE_CODE (tparm) == INTEGER_TYPE
13672                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13673         /* Convert the ARG to the type of PARM; the deduced non-type
13674            template argument must exactly match the types of the
13675            corresponding parameter.  */
13676         arg = fold (build_nop (tparm, arg));
13677       else if (uses_template_parms (tparm))
13678         /* We haven't deduced the type of this parameter yet.  Try again
13679            later.  */
13680         return 0;
13681       else
13682         return 1;
13683
13684       /* If ARG is a parameter pack or an expansion, we cannot unify
13685          against it unless PARM is also a parameter pack.  */
13686       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13687           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13688         return 1;
13689
13690       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13691       return 0;
13692
13693     case PTRMEM_CST:
13694      {
13695         /* A pointer-to-member constant can be unified only with
13696          another constant.  */
13697       if (TREE_CODE (arg) != PTRMEM_CST)
13698         return 1;
13699
13700       /* Just unify the class member. It would be useless (and possibly
13701          wrong, depending on the strict flags) to unify also
13702          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13703          arg refer to the same variable, even if through different
13704          classes. For instance:
13705
13706          struct A { int x; };
13707          struct B : A { };
13708
13709          Unification of &A::x and &B::x must succeed.  */
13710       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13711                     PTRMEM_CST_MEMBER (arg), strict);
13712      }
13713
13714     case POINTER_TYPE:
13715       {
13716         if (TREE_CODE (arg) != POINTER_TYPE)
13717           return 1;
13718
13719         /* [temp.deduct.call]
13720
13721            A can be another pointer or pointer to member type that can
13722            be converted to the deduced A via a qualification
13723            conversion (_conv.qual_).
13724
13725            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13726            This will allow for additional cv-qualification of the
13727            pointed-to types if appropriate.  */
13728
13729         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13730           /* The derived-to-base conversion only persists through one
13731              level of pointers.  */
13732           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13733
13734         return unify (tparms, targs, TREE_TYPE (parm),
13735                       TREE_TYPE (arg), strict);
13736       }
13737
13738     case REFERENCE_TYPE:
13739       if (TREE_CODE (arg) != REFERENCE_TYPE)
13740         return 1;
13741       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13742                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13743
13744     case ARRAY_TYPE:
13745       if (TREE_CODE (arg) != ARRAY_TYPE)
13746         return 1;
13747       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13748           != (TYPE_DOMAIN (arg) == NULL_TREE))
13749         return 1;
13750       if (TYPE_DOMAIN (parm) != NULL_TREE)
13751         {
13752           tree parm_max;
13753           tree arg_max;
13754           bool parm_cst;
13755           bool arg_cst;
13756
13757           /* Our representation of array types uses "N - 1" as the
13758              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13759              not an integer constant.  We cannot unify arbitrarily
13760              complex expressions, so we eliminate the MINUS_EXPRs
13761              here.  */
13762           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13763           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13764           if (!parm_cst)
13765             {
13766               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13767               parm_max = TREE_OPERAND (parm_max, 0);
13768             }
13769           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13770           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13771           if (!arg_cst)
13772             {
13773               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13774                  trying to unify the type of a variable with the type
13775                  of a template parameter.  For example:
13776
13777                    template <unsigned int N>
13778                    void f (char (&) [N]);
13779                    int g(); 
13780                    void h(int i) {
13781                      char a[g(i)];
13782                      f(a); 
13783                    }
13784
13785                 Here, the type of the ARG will be "int [g(i)]", and
13786                 may be a SAVE_EXPR, etc.  */
13787               if (TREE_CODE (arg_max) != MINUS_EXPR)
13788                 return 1;
13789               arg_max = TREE_OPERAND (arg_max, 0);
13790             }
13791
13792           /* If only one of the bounds used a MINUS_EXPR, compensate
13793              by adding one to the other bound.  */
13794           if (parm_cst && !arg_cst)
13795             parm_max = fold_build2 (PLUS_EXPR,
13796                                     integer_type_node,
13797                                     parm_max,
13798                                     integer_one_node);
13799           else if (arg_cst && !parm_cst)
13800             arg_max = fold_build2 (PLUS_EXPR,
13801                                    integer_type_node,
13802                                    arg_max,
13803                                    integer_one_node);
13804
13805           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13806             return 1;
13807         }
13808       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13809                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13810
13811     case REAL_TYPE:
13812     case COMPLEX_TYPE:
13813     case VECTOR_TYPE:
13814     case INTEGER_TYPE:
13815     case BOOLEAN_TYPE:
13816     case ENUMERAL_TYPE:
13817     case VOID_TYPE:
13818       if (TREE_CODE (arg) != TREE_CODE (parm))
13819         return 1;
13820
13821       /* We have already checked cv-qualification at the top of the
13822          function.  */
13823       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13824         return 1;
13825
13826       /* As far as unification is concerned, this wins.  Later checks
13827          will invalidate it if necessary.  */
13828       return 0;
13829
13830       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13831       /* Type INTEGER_CST can come from ordinary constant template args.  */
13832     case INTEGER_CST:
13833       while (TREE_CODE (arg) == NOP_EXPR)
13834         arg = TREE_OPERAND (arg, 0);
13835
13836       if (TREE_CODE (arg) != INTEGER_CST)
13837         return 1;
13838       return !tree_int_cst_equal (parm, arg);
13839
13840     case TREE_VEC:
13841       {
13842         int i;
13843         if (TREE_CODE (arg) != TREE_VEC)
13844           return 1;
13845         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13846           return 1;
13847         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13848           if (unify (tparms, targs,
13849                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13850                      UNIFY_ALLOW_NONE))
13851             return 1;
13852         return 0;
13853       }
13854
13855     case RECORD_TYPE:
13856     case UNION_TYPE:
13857       if (TREE_CODE (arg) != TREE_CODE (parm))
13858         return 1;
13859
13860       if (TYPE_PTRMEMFUNC_P (parm))
13861         {
13862           if (!TYPE_PTRMEMFUNC_P (arg))
13863             return 1;
13864
13865           return unify (tparms, targs,
13866                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13867                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13868                         strict);
13869         }
13870
13871       if (CLASSTYPE_TEMPLATE_INFO (parm))
13872         {
13873           tree t = NULL_TREE;
13874
13875           if (strict_in & UNIFY_ALLOW_DERIVED)
13876             {
13877               /* First, we try to unify the PARM and ARG directly.  */
13878               t = try_class_unification (tparms, targs,
13879                                          parm, arg);
13880
13881               if (!t)
13882                 {
13883                   /* Fallback to the special case allowed in
13884                      [temp.deduct.call]:
13885
13886                        If P is a class, and P has the form
13887                        template-id, then A can be a derived class of
13888                        the deduced A.  Likewise, if P is a pointer to
13889                        a class of the form template-id, A can be a
13890                        pointer to a derived class pointed to by the
13891                        deduced A.  */
13892                   t = get_template_base (tparms, targs, parm, arg);
13893
13894                   if (!t)
13895                     return 1;
13896                 }
13897             }
13898           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13899                    && (CLASSTYPE_TI_TEMPLATE (parm)
13900                        == CLASSTYPE_TI_TEMPLATE (arg)))
13901             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13902                Then, we should unify `int' and `U'.  */
13903             t = arg;
13904           else
13905             /* There's no chance of unification succeeding.  */
13906             return 1;
13907
13908           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13909                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13910         }
13911       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13912         return 1;
13913       return 0;
13914
13915     case METHOD_TYPE:
13916     case FUNCTION_TYPE:
13917       if (TREE_CODE (arg) != TREE_CODE (parm))
13918         return 1;
13919
13920       /* CV qualifications for methods can never be deduced, they must
13921          match exactly.  We need to check them explicitly here,
13922          because type_unification_real treats them as any other
13923          cv-qualified parameter.  */
13924       if (TREE_CODE (parm) == METHOD_TYPE
13925           && (!check_cv_quals_for_unify
13926               (UNIFY_ALLOW_NONE,
13927                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
13928                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
13929         return 1;
13930
13931       if (unify (tparms, targs, TREE_TYPE (parm),
13932                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
13933         return 1;
13934       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
13935                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
13936                                     LOOKUP_NORMAL);
13937
13938     case OFFSET_TYPE:
13939       /* Unify a pointer to member with a pointer to member function, which
13940          deduces the type of the member as a function type. */
13941       if (TYPE_PTRMEMFUNC_P (arg))
13942         {
13943           tree method_type;
13944           tree fntype;
13945           cp_cv_quals cv_quals;
13946
13947           /* Check top-level cv qualifiers */
13948           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
13949             return 1;
13950
13951           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13952                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
13953             return 1;
13954
13955           /* Determine the type of the function we are unifying against. */
13956           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
13957           fntype =
13958             build_function_type (TREE_TYPE (method_type),
13959                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
13960
13961           /* Extract the cv-qualifiers of the member function from the
13962              implicit object parameter and place them on the function
13963              type to be restored later. */
13964           cv_quals =
13965             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
13966           fntype = build_qualified_type (fntype, cv_quals);
13967           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
13968         }
13969
13970       if (TREE_CODE (arg) != OFFSET_TYPE)
13971         return 1;
13972       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13973                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
13974         return 1;
13975       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13976                     strict);
13977
13978     case CONST_DECL:
13979       if (DECL_TEMPLATE_PARM_P (parm))
13980         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
13981       if (arg != integral_constant_value (parm))
13982         return 1;
13983       return 0;
13984
13985     case FIELD_DECL:
13986     case TEMPLATE_DECL:
13987       /* Matched cases are handled by the ARG == PARM test above.  */
13988       return 1;
13989
13990     case TYPE_ARGUMENT_PACK:
13991     case NONTYPE_ARGUMENT_PACK:
13992       {
13993         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
13994         tree packed_args = ARGUMENT_PACK_ARGS (arg);
13995         int i, len = TREE_VEC_LENGTH (packed_parms);
13996         int argslen = TREE_VEC_LENGTH (packed_args);
13997         int parm_variadic_p = 0;
13998
13999         for (i = 0; i < len; ++i)
14000           {
14001             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14002               {
14003                 if (i == len - 1)
14004                   /* We can unify against something with a trailing
14005                      parameter pack.  */
14006                   parm_variadic_p = 1;
14007                 else
14008                   /* Since there is something following the pack
14009                      expansion, we cannot unify this template argument
14010                      list.  */
14011                   return 0;
14012               }
14013           }
14014           
14015
14016         /* If we don't have enough arguments to satisfy the parameters
14017            (not counting the pack expression at the end), or we have
14018            too many arguments for a parameter list that doesn't end in
14019            a pack expression, we can't unify.  */
14020         if (argslen < (len - parm_variadic_p)
14021             || (argslen > len && !parm_variadic_p))
14022           return 1;
14023
14024         /* Unify all of the parameters that precede the (optional)
14025            pack expression.  */
14026         for (i = 0; i < len - parm_variadic_p; ++i)
14027           {
14028             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14029                        TREE_VEC_ELT (packed_args, i), strict))
14030               return 1;
14031           }
14032
14033         if (parm_variadic_p)
14034           return unify_pack_expansion (tparms, targs, 
14035                                        packed_parms, packed_args,
14036                                        strict, /*call_args_p=*/false,
14037                                        /*subr=*/false);
14038         return 0;
14039       }
14040
14041       break;
14042
14043     case TYPEOF_TYPE:
14044     case DECLTYPE_TYPE:
14045       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14046          nodes.  */
14047       return 0;
14048
14049     case ERROR_MARK:
14050       /* Unification fails if we hit an error node.  */
14051       return 1;
14052
14053     default:
14054       gcc_assert (EXPR_P (parm));
14055
14056       /* We must be looking at an expression.  This can happen with
14057          something like:
14058
14059            template <int I>
14060            void foo(S<I>, S<I + 2>);
14061
14062          This is a "nondeduced context":
14063
14064            [deduct.type]
14065
14066            The nondeduced contexts are:
14067
14068            --A type that is a template-id in which one or more of
14069              the template-arguments is an expression that references
14070              a template-parameter.
14071
14072          In these cases, we assume deduction succeeded, but don't
14073          actually infer any unifications.  */
14074
14075       if (!uses_template_parms (parm)
14076           && !template_args_equal (parm, arg))
14077         return 1;
14078       else
14079         return 0;
14080     }
14081 }
14082 \f
14083 /* Note that DECL can be defined in this translation unit, if
14084    required.  */
14085
14086 static void
14087 mark_definable (tree decl)
14088 {
14089   tree clone;
14090   DECL_NOT_REALLY_EXTERN (decl) = 1;
14091   FOR_EACH_CLONE (clone, decl)
14092     DECL_NOT_REALLY_EXTERN (clone) = 1;
14093 }
14094
14095 /* Called if RESULT is explicitly instantiated, or is a member of an
14096    explicitly instantiated class.  */
14097
14098 void
14099 mark_decl_instantiated (tree result, int extern_p)
14100 {
14101   SET_DECL_EXPLICIT_INSTANTIATION (result);
14102
14103   /* If this entity has already been written out, it's too late to
14104      make any modifications.  */
14105   if (TREE_ASM_WRITTEN (result))
14106     return;
14107
14108   if (TREE_CODE (result) != FUNCTION_DECL)
14109     /* The TREE_PUBLIC flag for function declarations will have been
14110        set correctly by tsubst.  */
14111     TREE_PUBLIC (result) = 1;
14112
14113   /* This might have been set by an earlier implicit instantiation.  */
14114   DECL_COMDAT (result) = 0;
14115
14116   if (extern_p)
14117     DECL_NOT_REALLY_EXTERN (result) = 0;
14118   else
14119     {
14120       mark_definable (result);
14121       /* Always make artificials weak.  */
14122       if (DECL_ARTIFICIAL (result) && flag_weak)
14123         comdat_linkage (result);
14124       /* For WIN32 we also want to put explicit instantiations in
14125          linkonce sections.  */
14126       else if (TREE_PUBLIC (result))
14127         maybe_make_one_only (result);
14128     }
14129
14130   /* If EXTERN_P, then this function will not be emitted -- unless
14131      followed by an explicit instantiation, at which point its linkage
14132      will be adjusted.  If !EXTERN_P, then this function will be
14133      emitted here.  In neither circumstance do we want
14134      import_export_decl to adjust the linkage.  */
14135   DECL_INTERFACE_KNOWN (result) = 1;
14136 }
14137
14138 /* Given two function templates PAT1 and PAT2, return:
14139
14140    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14141    -1 if PAT2 is more specialized than PAT1.
14142    0 if neither is more specialized.
14143
14144    LEN indicates the number of parameters we should consider
14145    (defaulted parameters should not be considered).
14146
14147    The 1998 std underspecified function template partial ordering, and
14148    DR214 addresses the issue.  We take pairs of arguments, one from
14149    each of the templates, and deduce them against each other.  One of
14150    the templates will be more specialized if all the *other*
14151    template's arguments deduce against its arguments and at least one
14152    of its arguments *does* *not* deduce against the other template's
14153    corresponding argument.  Deduction is done as for class templates.
14154    The arguments used in deduction have reference and top level cv
14155    qualifiers removed.  Iff both arguments were originally reference
14156    types *and* deduction succeeds in both directions, the template
14157    with the more cv-qualified argument wins for that pairing (if
14158    neither is more cv-qualified, they both are equal).  Unlike regular
14159    deduction, after all the arguments have been deduced in this way,
14160    we do *not* verify the deduced template argument values can be
14161    substituted into non-deduced contexts, nor do we have to verify
14162    that all template arguments have been deduced.  */
14163
14164 int
14165 more_specialized_fn (tree pat1, tree pat2, int len)
14166 {
14167   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
14168   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
14169   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
14170   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
14171   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
14172   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
14173   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
14174   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
14175   int better1 = 0;
14176   int better2 = 0;
14177
14178   /* Remove the this parameter from non-static member functions.  If
14179      one is a non-static member function and the other is not a static
14180      member function, remove the first parameter from that function
14181      also.  This situation occurs for operator functions where we
14182      locate both a member function (with this pointer) and non-member
14183      operator (with explicit first operand).  */
14184   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
14185     {
14186       len--; /* LEN is the number of significant arguments for DECL1 */
14187       args1 = TREE_CHAIN (args1);
14188       if (!DECL_STATIC_FUNCTION_P (decl2))
14189         args2 = TREE_CHAIN (args2);
14190     }
14191   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
14192     {
14193       args2 = TREE_CHAIN (args2);
14194       if (!DECL_STATIC_FUNCTION_P (decl1))
14195         {
14196           len--;
14197           args1 = TREE_CHAIN (args1);
14198         }
14199     }
14200
14201   /* If only one is a conversion operator, they are unordered.  */
14202   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
14203     return 0;
14204
14205   /* Consider the return type for a conversion function */
14206   if (DECL_CONV_FN_P (decl1))
14207     {
14208       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
14209       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
14210       len++;
14211     }
14212
14213   processing_template_decl++;
14214
14215   while (len--
14216          /* Stop when an ellipsis is seen.  */
14217          && args1 != NULL_TREE && args2 != NULL_TREE)
14218     {
14219       tree arg1 = TREE_VALUE (args1);
14220       tree arg2 = TREE_VALUE (args2);
14221       int deduce1, deduce2;
14222       int quals1 = -1;
14223       int quals2 = -1;
14224
14225       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14226           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14227         {
14228           /* When both arguments are pack expansions, we need only
14229              unify the patterns themselves.  */
14230           arg1 = PACK_EXPANSION_PATTERN (arg1);
14231           arg2 = PACK_EXPANSION_PATTERN (arg2);
14232
14233           /* This is the last comparison we need to do.  */
14234           len = 0;
14235         }
14236
14237       if (TREE_CODE (arg1) == REFERENCE_TYPE)
14238         {
14239           arg1 = TREE_TYPE (arg1);
14240           quals1 = cp_type_quals (arg1);
14241         }
14242
14243       if (TREE_CODE (arg2) == REFERENCE_TYPE)
14244         {
14245           arg2 = TREE_TYPE (arg2);
14246           quals2 = cp_type_quals (arg2);
14247         }
14248
14249       if ((quals1 < 0) != (quals2 < 0))
14250         {
14251           /* Only of the args is a reference, see if we should apply
14252              array/function pointer decay to it.  This is not part of
14253              DR214, but is, IMHO, consistent with the deduction rules
14254              for the function call itself, and with our earlier
14255              implementation of the underspecified partial ordering
14256              rules.  (nathan).  */
14257           if (quals1 >= 0)
14258             {
14259               switch (TREE_CODE (arg1))
14260                 {
14261                 case ARRAY_TYPE:
14262                   arg1 = TREE_TYPE (arg1);
14263                   /* FALLTHROUGH. */
14264                 case FUNCTION_TYPE:
14265                   arg1 = build_pointer_type (arg1);
14266                   break;
14267
14268                 default:
14269                   break;
14270                 }
14271             }
14272           else
14273             {
14274               switch (TREE_CODE (arg2))
14275                 {
14276                 case ARRAY_TYPE:
14277                   arg2 = TREE_TYPE (arg2);
14278                   /* FALLTHROUGH. */
14279                 case FUNCTION_TYPE:
14280                   arg2 = build_pointer_type (arg2);
14281                   break;
14282
14283                 default:
14284                   break;
14285                 }
14286             }
14287         }
14288
14289       arg1 = TYPE_MAIN_VARIANT (arg1);
14290       arg2 = TYPE_MAIN_VARIANT (arg2);
14291
14292       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
14293         {
14294           int i, len2 = list_length (args2);
14295           tree parmvec = make_tree_vec (1);
14296           tree argvec = make_tree_vec (len2);
14297           tree ta = args2;
14298
14299           /* Setup the parameter vector, which contains only ARG1.  */
14300           TREE_VEC_ELT (parmvec, 0) = arg1;
14301
14302           /* Setup the argument vector, which contains the remaining
14303              arguments.  */
14304           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
14305             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14306
14307           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
14308                                            argvec, UNIFY_ALLOW_NONE, 
14309                                            /*call_args_p=*/false, 
14310                                            /*subr=*/0);
14311
14312           /* We cannot deduce in the other direction, because ARG1 is
14313              a pack expansion but ARG2 is not.  */
14314           deduce2 = 0;
14315         }
14316       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14317         {
14318           int i, len1 = list_length (args1);
14319           tree parmvec = make_tree_vec (1);
14320           tree argvec = make_tree_vec (len1);
14321           tree ta = args1;
14322
14323           /* Setup the parameter vector, which contains only ARG1.  */
14324           TREE_VEC_ELT (parmvec, 0) = arg2;
14325
14326           /* Setup the argument vector, which contains the remaining
14327              arguments.  */
14328           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14329             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14330
14331           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14332                                            argvec, UNIFY_ALLOW_NONE, 
14333                                            /*call_args_p=*/false, 
14334                                            /*subr=*/0);
14335
14336           /* We cannot deduce in the other direction, because ARG2 is
14337              a pack expansion but ARG1 is not.*/
14338           deduce1 = 0;
14339         }
14340
14341       else
14342         {
14343           /* The normal case, where neither argument is a pack
14344              expansion.  */
14345           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
14346           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
14347         }
14348
14349       if (!deduce1)
14350         better2 = -1;
14351       if (!deduce2)
14352         better1 = -1;
14353       if (better1 < 0 && better2 < 0)
14354         /* We've failed to deduce something in either direction.
14355            These must be unordered.  */
14356         break;
14357
14358       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
14359         {
14360           /* Deduces in both directions, see if quals can
14361              disambiguate.  Pretend the worse one failed to deduce. */
14362           if ((quals1 & quals2) == quals2)
14363             deduce1 = 0;
14364           if ((quals1 & quals2) == quals1)
14365             deduce2 = 0;
14366         }
14367       if (deduce1 && !deduce2 && !better2)
14368         better2 = 1;
14369       if (deduce2 && !deduce1 && !better1)
14370         better1 = 1;
14371
14372       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14373           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14374         /* We have already processed all of the arguments in our
14375            handing of the pack expansion type.  */
14376         len = 0;
14377
14378       args1 = TREE_CHAIN (args1);
14379       args2 = TREE_CHAIN (args2);
14380     }
14381
14382   processing_template_decl--;
14383
14384   /* All things being equal, if the next argument is a pack expansion
14385      for one function but not for the other, prefer the
14386      non-variadic function.  */
14387   if ((better1 > 0) - (better2 > 0) == 0
14388       && args1 && TREE_VALUE (args1)
14389       && args2 && TREE_VALUE (args2))
14390     {
14391       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
14392         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
14393       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
14394         return 1;
14395     }
14396
14397   return (better1 > 0) - (better2 > 0);
14398 }
14399
14400 /* Determine which of two partial specializations is more specialized.
14401
14402    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
14403    to the first partial specialization.  The TREE_VALUE is the
14404    innermost set of template parameters for the partial
14405    specialization.  PAT2 is similar, but for the second template.
14406
14407    Return 1 if the first partial specialization is more specialized;
14408    -1 if the second is more specialized; 0 if neither is more
14409    specialized.
14410
14411    See [temp.class.order] for information about determining which of
14412    two templates is more specialized.  */
14413
14414 static int
14415 more_specialized_class (tree pat1, tree pat2)
14416 {
14417   tree targs;
14418   tree tmpl1, tmpl2;
14419   int winner = 0;
14420   bool any_deductions = false;
14421
14422   tmpl1 = TREE_TYPE (pat1);
14423   tmpl2 = TREE_TYPE (pat2);
14424
14425   /* Just like what happens for functions, if we are ordering between
14426      different class template specializations, we may encounter dependent
14427      types in the arguments, and we need our dependency check functions
14428      to behave correctly.  */
14429   ++processing_template_decl;
14430   targs = get_class_bindings (TREE_VALUE (pat1),
14431                               CLASSTYPE_TI_ARGS (tmpl1),
14432                               CLASSTYPE_TI_ARGS (tmpl2));
14433   if (targs)
14434     {
14435       --winner;
14436       any_deductions = true;
14437     }
14438
14439   targs = get_class_bindings (TREE_VALUE (pat2),
14440                               CLASSTYPE_TI_ARGS (tmpl2),
14441                               CLASSTYPE_TI_ARGS (tmpl1));
14442   if (targs)
14443     {
14444       ++winner;
14445       any_deductions = true;
14446     }
14447   --processing_template_decl;
14448
14449   /* In the case of a tie where at least one of the class templates
14450      has a parameter pack at the end, the template with the most
14451      non-packed parameters wins.  */
14452   if (winner == 0
14453       && any_deductions
14454       && (template_args_variadic_p (TREE_PURPOSE (pat1))
14455           || template_args_variadic_p (TREE_PURPOSE (pat2))))
14456     {
14457       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
14458       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
14459       int len1 = TREE_VEC_LENGTH (args1);
14460       int len2 = TREE_VEC_LENGTH (args2);
14461
14462       /* We don't count the pack expansion at the end.  */
14463       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
14464         --len1;
14465       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
14466         --len2;
14467
14468       if (len1 > len2)
14469         return 1;
14470       else if (len1 < len2)
14471         return -1;
14472     }
14473
14474   return winner;
14475 }
14476
14477 /* Return the template arguments that will produce the function signature
14478    DECL from the function template FN, with the explicit template
14479    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
14480    also match.  Return NULL_TREE if no satisfactory arguments could be
14481    found.  */
14482
14483 static tree
14484 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
14485 {
14486   int ntparms = DECL_NTPARMS (fn);
14487   tree targs = make_tree_vec (ntparms);
14488   tree decl_type;
14489   tree decl_arg_types;
14490
14491   /* Substitute the explicit template arguments into the type of DECL.
14492      The call to fn_type_unification will handle substitution into the
14493      FN.  */
14494   decl_type = TREE_TYPE (decl);
14495   if (explicit_args && uses_template_parms (decl_type))
14496     {
14497       tree tmpl;
14498       tree converted_args;
14499
14500       if (DECL_TEMPLATE_INFO (decl))
14501         tmpl = DECL_TI_TEMPLATE (decl);
14502       else
14503         /* We can get here for some invalid specializations.  */
14504         return NULL_TREE;
14505
14506       converted_args
14507         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
14508                                  explicit_args, NULL_TREE,
14509                                  tf_none,
14510                                  /*require_all_args=*/false,
14511                                  /*use_default_args=*/false);
14512       if (converted_args == error_mark_node)
14513         return NULL_TREE;
14514
14515       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
14516       if (decl_type == error_mark_node)
14517         return NULL_TREE;
14518     }
14519
14520   /* Never do unification on the 'this' parameter.  */
14521   decl_arg_types = skip_artificial_parms_for (decl, 
14522                                               TYPE_ARG_TYPES (decl_type));
14523
14524   if (fn_type_unification (fn, explicit_args, targs,
14525                            decl_arg_types,
14526                            (check_rettype || DECL_CONV_FN_P (fn)
14527                             ? TREE_TYPE (decl_type) : NULL_TREE),
14528                            DEDUCE_EXACT, LOOKUP_NORMAL))
14529     return NULL_TREE;
14530
14531   return targs;
14532 }
14533
14534 /* Return the innermost template arguments that, when applied to a
14535    template specialization whose innermost template parameters are
14536    TPARMS, and whose specialization arguments are PARMS, yield the
14537    ARGS.
14538
14539    For example, suppose we have:
14540
14541      template <class T, class U> struct S {};
14542      template <class T> struct S<T*, int> {};
14543
14544    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
14545    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
14546    int}.  The resulting vector will be {double}, indicating that `T'
14547    is bound to `double'.  */
14548
14549 static tree
14550 get_class_bindings (tree tparms, tree spec_args, tree args)
14551 {
14552   int i, ntparms = TREE_VEC_LENGTH (tparms);
14553   tree deduced_args;
14554   tree innermost_deduced_args;
14555
14556   innermost_deduced_args = make_tree_vec (ntparms);
14557   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14558     {
14559       deduced_args = copy_node (args);
14560       SET_TMPL_ARGS_LEVEL (deduced_args,
14561                            TMPL_ARGS_DEPTH (deduced_args),
14562                            innermost_deduced_args);
14563     }
14564   else
14565     deduced_args = innermost_deduced_args;
14566
14567   if (unify (tparms, deduced_args,
14568              INNERMOST_TEMPLATE_ARGS (spec_args),
14569              INNERMOST_TEMPLATE_ARGS (args),
14570              UNIFY_ALLOW_NONE))
14571     return NULL_TREE;
14572
14573   for (i =  0; i < ntparms; ++i)
14574     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14575       return NULL_TREE;
14576
14577   /* Verify that nondeduced template arguments agree with the type
14578      obtained from argument deduction.
14579
14580      For example:
14581
14582        struct A { typedef int X; };
14583        template <class T, class U> struct C {};
14584        template <class T> struct C<T, typename T::X> {};
14585
14586      Then with the instantiation `C<A, int>', we can deduce that
14587      `T' is `A' but unify () does not check whether `typename T::X'
14588      is `int'.  */
14589   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14590   if (spec_args == error_mark_node
14591       /* We only need to check the innermost arguments; the other
14592          arguments will always agree.  */
14593       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14594                               INNERMOST_TEMPLATE_ARGS (args)))
14595     return NULL_TREE;
14596
14597   /* Now that we have bindings for all of the template arguments,
14598      ensure that the arguments deduced for the template template
14599      parameters have compatible template parameter lists.  See the use
14600      of template_template_parm_bindings_ok_p in fn_type_unification
14601      for more information.  */
14602   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14603     return NULL_TREE;
14604
14605   return deduced_args;
14606 }
14607
14608 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14609    Return the TREE_LIST node with the most specialized template, if
14610    any.  If there is no most specialized template, the error_mark_node
14611    is returned.
14612
14613    Note that this function does not look at, or modify, the
14614    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14615    returned is one of the elements of INSTANTIATIONS, callers may
14616    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14617    and retrieve it from the value returned.  */
14618
14619 tree
14620 most_specialized_instantiation (tree templates)
14621 {
14622   tree fn, champ;
14623
14624   ++processing_template_decl;
14625
14626   champ = templates;
14627   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14628     {
14629       int fate = 0;
14630
14631       if (get_bindings (TREE_VALUE (champ),
14632                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14633                         NULL_TREE, /*check_ret=*/false))
14634         fate--;
14635
14636       if (get_bindings (TREE_VALUE (fn),
14637                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14638                         NULL_TREE, /*check_ret=*/false))
14639         fate++;
14640
14641       if (fate == -1)
14642         champ = fn;
14643       else if (!fate)
14644         {
14645           /* Equally specialized, move to next function.  If there
14646              is no next function, nothing's most specialized.  */
14647           fn = TREE_CHAIN (fn);
14648           champ = fn;
14649           if (!fn)
14650             break;
14651         }
14652     }
14653
14654   if (champ)
14655     /* Now verify that champ is better than everything earlier in the
14656        instantiation list.  */
14657     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14658       if (get_bindings (TREE_VALUE (champ),
14659                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14660                         NULL_TREE, /*check_ret=*/false)
14661           || !get_bindings (TREE_VALUE (fn),
14662                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14663                             NULL_TREE, /*check_ret=*/false))
14664         {
14665           champ = NULL_TREE;
14666           break;
14667         }
14668
14669   processing_template_decl--;
14670
14671   if (!champ)
14672     return error_mark_node;
14673
14674   return champ;
14675 }
14676
14677 /* If DECL is a specialization of some template, return the most
14678    general such template.  Otherwise, returns NULL_TREE.
14679
14680    For example, given:
14681
14682      template <class T> struct S { template <class U> void f(U); };
14683
14684    if TMPL is `template <class U> void S<int>::f(U)' this will return
14685    the full template.  This function will not trace past partial
14686    specializations, however.  For example, given in addition:
14687
14688      template <class T> struct S<T*> { template <class U> void f(U); };
14689
14690    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14691    `template <class T> template <class U> S<T*>::f(U)'.  */
14692
14693 tree
14694 most_general_template (tree decl)
14695 {
14696   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14697      an immediate specialization.  */
14698   if (TREE_CODE (decl) == FUNCTION_DECL)
14699     {
14700       if (DECL_TEMPLATE_INFO (decl)) {
14701         decl = DECL_TI_TEMPLATE (decl);
14702
14703         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14704            template friend.  */
14705         if (TREE_CODE (decl) != TEMPLATE_DECL)
14706           return NULL_TREE;
14707       } else
14708         return NULL_TREE;
14709     }
14710
14711   /* Look for more and more general templates.  */
14712   while (DECL_TEMPLATE_INFO (decl))
14713     {
14714       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14715          (See cp-tree.h for details.)  */
14716       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14717         break;
14718
14719       if (CLASS_TYPE_P (TREE_TYPE (decl))
14720           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14721         break;
14722
14723       /* Stop if we run into an explicitly specialized class template.  */
14724       if (!DECL_NAMESPACE_SCOPE_P (decl)
14725           && DECL_CONTEXT (decl)
14726           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14727         break;
14728
14729       decl = DECL_TI_TEMPLATE (decl);
14730     }
14731
14732   return decl;
14733 }
14734
14735 /* Return the most specialized of the class template partial
14736    specializations of TMPL which can produce TYPE, a specialization of
14737    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14738    a _TYPE node corresponding to the partial specialization, while the
14739    TREE_PURPOSE is the set of template arguments that must be
14740    substituted into the TREE_TYPE in order to generate TYPE.
14741
14742    If the choice of partial specialization is ambiguous, a diagnostic
14743    is issued, and the error_mark_node is returned.  If there are no
14744    partial specializations of TMPL matching TYPE, then NULL_TREE is
14745    returned.  */
14746
14747 static tree
14748 most_specialized_class (tree type, tree tmpl)
14749 {
14750   tree list = NULL_TREE;
14751   tree t;
14752   tree champ;
14753   int fate;
14754   bool ambiguous_p;
14755   tree args;
14756   tree outer_args = NULL_TREE;
14757
14758   tmpl = most_general_template (tmpl);
14759   args = CLASSTYPE_TI_ARGS (type);
14760
14761   /* For determining which partial specialization to use, only the
14762      innermost args are interesting.  */
14763   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14764     {
14765       outer_args = strip_innermost_template_args (args, 1);
14766       args = INNERMOST_TEMPLATE_ARGS (args);
14767     }
14768
14769   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14770     {
14771       tree partial_spec_args;
14772       tree spec_args;
14773       tree parms = TREE_VALUE (t);
14774
14775       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14776       if (outer_args)
14777         {
14778           int i;
14779
14780           ++processing_template_decl;
14781
14782           /* Discard the outer levels of args, and then substitute in the
14783              template args from the enclosing class.  */
14784           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14785           partial_spec_args = tsubst_template_args
14786             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14787
14788           /* PARMS already refers to just the innermost parms, but the
14789              template parms in partial_spec_args had their levels lowered
14790              by tsubst, so we need to do the same for the parm list.  We
14791              can't just tsubst the TREE_VEC itself, as tsubst wants to
14792              treat a TREE_VEC as an argument vector.  */
14793           parms = copy_node (parms);
14794           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14795             TREE_VEC_ELT (parms, i) =
14796               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14797
14798           --processing_template_decl;
14799         }
14800       spec_args = get_class_bindings (parms,
14801                                       partial_spec_args,
14802                                       args);
14803       if (spec_args)
14804         {
14805           if (outer_args)
14806             spec_args = add_to_template_args (outer_args, spec_args);
14807           list = tree_cons (spec_args, TREE_VALUE (t), list);
14808           TREE_TYPE (list) = TREE_TYPE (t);
14809         }
14810     }
14811
14812   if (! list)
14813     return NULL_TREE;
14814
14815   ambiguous_p = false;
14816   t = list;
14817   champ = t;
14818   t = TREE_CHAIN (t);
14819   for (; t; t = TREE_CHAIN (t))
14820     {
14821       fate = more_specialized_class (champ, t);
14822       if (fate == 1)
14823         ;
14824       else
14825         {
14826           if (fate == 0)
14827             {
14828               t = TREE_CHAIN (t);
14829               if (! t)
14830                 {
14831                   ambiguous_p = true;
14832                   break;
14833                 }
14834             }
14835           champ = t;
14836         }
14837     }
14838
14839   if (!ambiguous_p)
14840     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14841       {
14842         fate = more_specialized_class (champ, t);
14843         if (fate != 1)
14844           {
14845             ambiguous_p = true;
14846             break;
14847           }
14848       }
14849
14850   if (ambiguous_p)
14851     {
14852       const char *str = "candidates are:";
14853       error ("ambiguous class template instantiation for %q#T", type);
14854       for (t = list; t; t = TREE_CHAIN (t))
14855         {
14856           error ("%s %+#T", str, TREE_TYPE (t));
14857           str = "               ";
14858         }
14859       return error_mark_node;
14860     }
14861
14862   return champ;
14863 }
14864
14865 /* Explicitly instantiate DECL.  */
14866
14867 void
14868 do_decl_instantiation (tree decl, tree storage)
14869 {
14870   tree result = NULL_TREE;
14871   int extern_p = 0;
14872
14873   if (!decl || decl == error_mark_node)
14874     /* An error occurred, for which grokdeclarator has already issued
14875        an appropriate message.  */
14876     return;
14877   else if (! DECL_LANG_SPECIFIC (decl))
14878     {
14879       error ("explicit instantiation of non-template %q#D", decl);
14880       return;
14881     }
14882   else if (TREE_CODE (decl) == VAR_DECL)
14883     {
14884       /* There is an asymmetry here in the way VAR_DECLs and
14885          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14886          the latter, the DECL we get back will be marked as a
14887          template instantiation, and the appropriate
14888          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14889          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14890          should handle VAR_DECLs as it currently handles
14891          FUNCTION_DECLs.  */
14892       if (!DECL_CLASS_SCOPE_P (decl))
14893         {
14894           error ("%qD is not a static data member of a class template", decl);
14895           return;
14896         }
14897       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14898       if (!result || TREE_CODE (result) != VAR_DECL)
14899         {
14900           error ("no matching template for %qD found", decl);
14901           return;
14902         }
14903       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14904         {
14905           error ("type %qT for explicit instantiation %qD does not match "
14906                  "declared type %qT", TREE_TYPE (result), decl,
14907                  TREE_TYPE (decl));
14908           return;
14909         }
14910     }
14911   else if (TREE_CODE (decl) != FUNCTION_DECL)
14912     {
14913       error ("explicit instantiation of %q#D", decl);
14914       return;
14915     }
14916   else
14917     result = decl;
14918
14919   /* Check for various error cases.  Note that if the explicit
14920      instantiation is valid the RESULT will currently be marked as an
14921      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
14922      until we get here.  */
14923
14924   if (DECL_TEMPLATE_SPECIALIZATION (result))
14925     {
14926       /* DR 259 [temp.spec].
14927
14928          Both an explicit instantiation and a declaration of an explicit
14929          specialization shall not appear in a program unless the explicit
14930          instantiation follows a declaration of the explicit specialization.
14931
14932          For a given set of template parameters, if an explicit
14933          instantiation of a template appears after a declaration of an
14934          explicit specialization for that template, the explicit
14935          instantiation has no effect.  */
14936       return;
14937     }
14938   else if (DECL_EXPLICIT_INSTANTIATION (result))
14939     {
14940       /* [temp.spec]
14941
14942          No program shall explicitly instantiate any template more
14943          than once.
14944
14945          We check DECL_NOT_REALLY_EXTERN so as not to complain when
14946          the first instantiation was `extern' and the second is not,
14947          and EXTERN_P for the opposite case.  */
14948       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
14949         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
14950       /* If an "extern" explicit instantiation follows an ordinary
14951          explicit instantiation, the template is instantiated.  */
14952       if (extern_p)
14953         return;
14954     }
14955   else if (!DECL_IMPLICIT_INSTANTIATION (result))
14956     {
14957       error ("no matching template for %qD found", result);
14958       return;
14959     }
14960   else if (!DECL_TEMPLATE_INFO (result))
14961     {
14962       permerror (input_location, "explicit instantiation of non-template %q#D", result);
14963       return;
14964     }
14965
14966   if (storage == NULL_TREE)
14967     ;
14968   else if (storage == ridpointers[(int) RID_EXTERN])
14969     {
14970       if (!in_system_header && (cxx_dialect == cxx98))
14971         pedwarn (input_location, OPT_pedantic, 
14972                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
14973                  "instantiations");
14974       extern_p = 1;
14975     }
14976   else
14977     error ("storage class %qD applied to template instantiation", storage);
14978
14979   check_explicit_instantiation_namespace (result);
14980   mark_decl_instantiated (result, extern_p);
14981   if (! extern_p)
14982     instantiate_decl (result, /*defer_ok=*/1,
14983                       /*expl_inst_class_mem_p=*/false);
14984 }
14985
14986 static void
14987 mark_class_instantiated (tree t, int extern_p)
14988 {
14989   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
14990   SET_CLASSTYPE_INTERFACE_KNOWN (t);
14991   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
14992   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
14993   if (! extern_p)
14994     {
14995       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
14996       rest_of_type_compilation (t, 1);
14997     }
14998 }
14999
15000 /* Called from do_type_instantiation through binding_table_foreach to
15001    do recursive instantiation for the type bound in ENTRY.  */
15002 static void
15003 bt_instantiate_type_proc (binding_entry entry, void *data)
15004 {
15005   tree storage = *(tree *) data;
15006
15007   if (MAYBE_CLASS_TYPE_P (entry->type)
15008       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15009     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15010 }
15011
15012 /* Called from do_type_instantiation to instantiate a member
15013    (a member function or a static member variable) of an
15014    explicitly instantiated class template.  */
15015 static void
15016 instantiate_class_member (tree decl, int extern_p)
15017 {
15018   mark_decl_instantiated (decl, extern_p);
15019   if (! extern_p)
15020     instantiate_decl (decl, /*defer_ok=*/1,
15021                       /*expl_inst_class_mem_p=*/true);
15022 }
15023
15024 /* Perform an explicit instantiation of template class T.  STORAGE, if
15025    non-null, is the RID for extern, inline or static.  COMPLAIN is
15026    nonzero if this is called from the parser, zero if called recursively,
15027    since the standard is unclear (as detailed below).  */
15028
15029 void
15030 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15031 {
15032   int extern_p = 0;
15033   int nomem_p = 0;
15034   int static_p = 0;
15035   int previous_instantiation_extern_p = 0;
15036
15037   if (TREE_CODE (t) == TYPE_DECL)
15038     t = TREE_TYPE (t);
15039
15040   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15041     {
15042       error ("explicit instantiation of non-template type %qT", t);
15043       return;
15044     }
15045
15046   complete_type (t);
15047
15048   if (!COMPLETE_TYPE_P (t))
15049     {
15050       if (complain & tf_error)
15051         error ("explicit instantiation of %q#T before definition of template",
15052                t);
15053       return;
15054     }
15055
15056   if (storage != NULL_TREE)
15057     {
15058       if (!in_system_header)
15059         {
15060           if (storage == ridpointers[(int) RID_EXTERN])
15061             {
15062               if (cxx_dialect == cxx98)
15063                 pedwarn (input_location, OPT_pedantic, 
15064                          "ISO C++ 1998 forbids the use of %<extern%> on "
15065                          "explicit instantiations");
15066             }
15067           else
15068             pedwarn (input_location, OPT_pedantic, 
15069                      "ISO C++ forbids the use of %qE"
15070                      " on explicit instantiations", storage);
15071         }
15072
15073       if (storage == ridpointers[(int) RID_INLINE])
15074         nomem_p = 1;
15075       else if (storage == ridpointers[(int) RID_EXTERN])
15076         extern_p = 1;
15077       else if (storage == ridpointers[(int) RID_STATIC])
15078         static_p = 1;
15079       else
15080         {
15081           error ("storage class %qD applied to template instantiation",
15082                  storage);
15083           extern_p = 0;
15084         }
15085     }
15086
15087   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15088     {
15089       /* DR 259 [temp.spec].
15090
15091          Both an explicit instantiation and a declaration of an explicit
15092          specialization shall not appear in a program unless the explicit
15093          instantiation follows a declaration of the explicit specialization.
15094
15095          For a given set of template parameters, if an explicit
15096          instantiation of a template appears after a declaration of an
15097          explicit specialization for that template, the explicit
15098          instantiation has no effect.  */
15099       return;
15100     }
15101   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15102     {
15103       /* [temp.spec]
15104
15105          No program shall explicitly instantiate any template more
15106          than once.
15107
15108          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15109          instantiation was `extern'.  If EXTERN_P then the second is.
15110          These cases are OK.  */
15111       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15112
15113       if (!previous_instantiation_extern_p && !extern_p
15114           && (complain & tf_error))
15115         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15116
15117       /* If we've already instantiated the template, just return now.  */
15118       if (!CLASSTYPE_INTERFACE_ONLY (t))
15119         return;
15120     }
15121
15122   check_explicit_instantiation_namespace (TYPE_NAME (t));
15123   mark_class_instantiated (t, extern_p);
15124
15125   if (nomem_p)
15126     return;
15127
15128   {
15129     tree tmp;
15130
15131     /* In contrast to implicit instantiation, where only the
15132        declarations, and not the definitions, of members are
15133        instantiated, we have here:
15134
15135          [temp.explicit]
15136
15137          The explicit instantiation of a class template specialization
15138          implies the instantiation of all of its members not
15139          previously explicitly specialized in the translation unit
15140          containing the explicit instantiation.
15141
15142        Of course, we can't instantiate member template classes, since
15143        we don't have any arguments for them.  Note that the standard
15144        is unclear on whether the instantiation of the members are
15145        *explicit* instantiations or not.  However, the most natural
15146        interpretation is that it should be an explicit instantiation.  */
15147
15148     if (! static_p)
15149       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
15150         if (TREE_CODE (tmp) == FUNCTION_DECL
15151             && DECL_TEMPLATE_INSTANTIATION (tmp))
15152           instantiate_class_member (tmp, extern_p);
15153
15154     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
15155       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
15156         instantiate_class_member (tmp, extern_p);
15157
15158     if (CLASSTYPE_NESTED_UTDS (t))
15159       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
15160                              bt_instantiate_type_proc, &storage);
15161   }
15162 }
15163
15164 /* Given a function DECL, which is a specialization of TMPL, modify
15165    DECL to be a re-instantiation of TMPL with the same template
15166    arguments.  TMPL should be the template into which tsubst'ing
15167    should occur for DECL, not the most general template.
15168
15169    One reason for doing this is a scenario like this:
15170
15171      template <class T>
15172      void f(const T&, int i);
15173
15174      void g() { f(3, 7); }
15175
15176      template <class T>
15177      void f(const T& t, const int i) { }
15178
15179    Note that when the template is first instantiated, with
15180    instantiate_template, the resulting DECL will have no name for the
15181    first parameter, and the wrong type for the second.  So, when we go
15182    to instantiate the DECL, we regenerate it.  */
15183
15184 static void
15185 regenerate_decl_from_template (tree decl, tree tmpl)
15186 {
15187   /* The arguments used to instantiate DECL, from the most general
15188      template.  */
15189   tree args;
15190   tree code_pattern;
15191
15192   args = DECL_TI_ARGS (decl);
15193   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
15194
15195   /* Make sure that we can see identifiers, and compute access
15196      correctly.  */
15197   push_access_scope (decl);
15198
15199   if (TREE_CODE (decl) == FUNCTION_DECL)
15200     {
15201       tree decl_parm;
15202       tree pattern_parm;
15203       tree specs;
15204       int args_depth;
15205       int parms_depth;
15206
15207       args_depth = TMPL_ARGS_DEPTH (args);
15208       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
15209       if (args_depth > parms_depth)
15210         args = get_innermost_template_args (args, parms_depth);
15211
15212       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
15213                                               args, tf_error, NULL_TREE);
15214       if (specs)
15215         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
15216                                                     specs);
15217
15218       /* Merge parameter declarations.  */
15219       decl_parm = skip_artificial_parms_for (decl,
15220                                              DECL_ARGUMENTS (decl));
15221       pattern_parm
15222         = skip_artificial_parms_for (code_pattern,
15223                                      DECL_ARGUMENTS (code_pattern));
15224       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
15225         {
15226           tree parm_type;
15227           tree attributes;
15228           
15229           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15230             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
15231           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
15232                               NULL_TREE);
15233           parm_type = type_decays_to (parm_type);
15234           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15235             TREE_TYPE (decl_parm) = parm_type;
15236           attributes = DECL_ATTRIBUTES (pattern_parm);
15237           if (DECL_ATTRIBUTES (decl_parm) != attributes)
15238             {
15239               DECL_ATTRIBUTES (decl_parm) = attributes;
15240               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15241             }
15242           decl_parm = TREE_CHAIN (decl_parm);
15243           pattern_parm = TREE_CHAIN (pattern_parm);
15244         }
15245       /* Merge any parameters that match with the function parameter
15246          pack.  */
15247       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
15248         {
15249           int i, len;
15250           tree expanded_types;
15251           /* Expand the TYPE_PACK_EXPANSION that provides the types for
15252              the parameters in this function parameter pack.  */
15253           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
15254                                                  args, tf_error, NULL_TREE);
15255           len = TREE_VEC_LENGTH (expanded_types);
15256           for (i = 0; i < len; i++)
15257             {
15258               tree parm_type;
15259               tree attributes;
15260           
15261               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15262                 /* Rename the parameter to include the index.  */
15263                 DECL_NAME (decl_parm) = 
15264                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
15265               parm_type = TREE_VEC_ELT (expanded_types, i);
15266               parm_type = type_decays_to (parm_type);
15267               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15268                 TREE_TYPE (decl_parm) = parm_type;
15269               attributes = DECL_ATTRIBUTES (pattern_parm);
15270               if (DECL_ATTRIBUTES (decl_parm) != attributes)
15271                 {
15272                   DECL_ATTRIBUTES (decl_parm) = attributes;
15273                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15274                 }
15275               decl_parm = TREE_CHAIN (decl_parm);
15276             }
15277         }
15278       /* Merge additional specifiers from the CODE_PATTERN.  */
15279       if (DECL_DECLARED_INLINE_P (code_pattern)
15280           && !DECL_DECLARED_INLINE_P (decl))
15281         DECL_DECLARED_INLINE_P (decl) = 1;
15282     }
15283   else if (TREE_CODE (decl) == VAR_DECL)
15284     DECL_INITIAL (decl) =
15285       tsubst_expr (DECL_INITIAL (code_pattern), args,
15286                    tf_error, DECL_TI_TEMPLATE (decl),
15287                    /*integral_constant_expression_p=*/false);
15288   else
15289     gcc_unreachable ();
15290
15291   pop_access_scope (decl);
15292 }
15293
15294 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
15295    substituted to get DECL.  */
15296
15297 tree
15298 template_for_substitution (tree decl)
15299 {
15300   tree tmpl = DECL_TI_TEMPLATE (decl);
15301
15302   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
15303      for the instantiation.  This is not always the most general
15304      template.  Consider, for example:
15305
15306         template <class T>
15307         struct S { template <class U> void f();
15308                    template <> void f<int>(); };
15309
15310      and an instantiation of S<double>::f<int>.  We want TD to be the
15311      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
15312   while (/* An instantiation cannot have a definition, so we need a
15313             more general template.  */
15314          DECL_TEMPLATE_INSTANTIATION (tmpl)
15315            /* We must also deal with friend templates.  Given:
15316
15317                 template <class T> struct S {
15318                   template <class U> friend void f() {};
15319                 };
15320
15321               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15322               so far as the language is concerned, but that's still
15323               where we get the pattern for the instantiation from.  On
15324               other hand, if the definition comes outside the class, say:
15325
15326                 template <class T> struct S {
15327                   template <class U> friend void f();
15328                 };
15329                 template <class U> friend void f() {}
15330
15331               we don't need to look any further.  That's what the check for
15332               DECL_INITIAL is for.  */
15333           || (TREE_CODE (decl) == FUNCTION_DECL
15334               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
15335               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
15336     {
15337       /* The present template, TD, should not be a definition.  If it
15338          were a definition, we should be using it!  Note that we
15339          cannot restructure the loop to just keep going until we find
15340          a template with a definition, since that might go too far if
15341          a specialization was declared, but not defined.  */
15342       gcc_assert (TREE_CODE (decl) != VAR_DECL
15343                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
15344
15345       /* Fetch the more general template.  */
15346       tmpl = DECL_TI_TEMPLATE (tmpl);
15347     }
15348
15349   return tmpl;
15350 }
15351
15352 /* Produce the definition of D, a _DECL generated from a template.  If
15353    DEFER_OK is nonzero, then we don't have to actually do the
15354    instantiation now; we just have to do it sometime.  Normally it is
15355    an error if this is an explicit instantiation but D is undefined.
15356    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
15357    explicitly instantiated class template.  */
15358
15359 tree
15360 instantiate_decl (tree d, int defer_ok,
15361                   bool expl_inst_class_mem_p)
15362 {
15363   tree tmpl = DECL_TI_TEMPLATE (d);
15364   tree gen_args;
15365   tree args;
15366   tree td;
15367   tree code_pattern;
15368   tree spec;
15369   tree gen_tmpl;
15370   bool pattern_defined;
15371   int need_push;
15372   location_t saved_loc = input_location;
15373   bool external_p;
15374
15375   /* This function should only be used to instantiate templates for
15376      functions and static member variables.  */
15377   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
15378               || TREE_CODE (d) == VAR_DECL);
15379
15380   /* Variables are never deferred; if instantiation is required, they
15381      are instantiated right away.  That allows for better code in the
15382      case that an expression refers to the value of the variable --
15383      if the variable has a constant value the referring expression can
15384      take advantage of that fact.  */
15385   if (TREE_CODE (d) == VAR_DECL)
15386     defer_ok = 0;
15387
15388   /* Don't instantiate cloned functions.  Instead, instantiate the
15389      functions they cloned.  */
15390   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
15391     d = DECL_CLONED_FUNCTION (d);
15392
15393   if (DECL_TEMPLATE_INSTANTIATED (d))
15394     /* D has already been instantiated.  It might seem reasonable to
15395        check whether or not D is an explicit instantiation, and, if so,
15396        stop here.  But when an explicit instantiation is deferred
15397        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
15398        is set, even though we still need to do the instantiation.  */
15399     return d;
15400
15401   /* If we already have a specialization of this declaration, then
15402      there's no reason to instantiate it.  Note that
15403      retrieve_specialization gives us both instantiations and
15404      specializations, so we must explicitly check
15405      DECL_TEMPLATE_SPECIALIZATION.  */
15406   gen_tmpl = most_general_template (tmpl);
15407   gen_args = DECL_TI_ARGS (d);
15408   spec = retrieve_specialization (gen_tmpl, gen_args,
15409                                   /*class_specializations_p=*/false);
15410   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
15411     return spec;
15412
15413   /* This needs to happen before any tsubsting.  */
15414   if (! push_tinst_level (d))
15415     return d;
15416
15417   timevar_push (TV_PARSE);
15418
15419   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
15420      for the instantiation.  */
15421   td = template_for_substitution (d);
15422   code_pattern = DECL_TEMPLATE_RESULT (td);
15423
15424   /* We should never be trying to instantiate a member of a class
15425      template or partial specialization.  */
15426   gcc_assert (d != code_pattern);
15427
15428   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
15429       || DECL_TEMPLATE_SPECIALIZATION (td))
15430     /* In the case of a friend template whose definition is provided
15431        outside the class, we may have too many arguments.  Drop the
15432        ones we don't need.  The same is true for specializations.  */
15433     args = get_innermost_template_args
15434       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
15435   else
15436     args = gen_args;
15437
15438   if (TREE_CODE (d) == FUNCTION_DECL)
15439     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
15440   else
15441     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
15442
15443   /* We may be in the middle of deferred access check.  Disable it now.  */
15444   push_deferring_access_checks (dk_no_deferred);
15445
15446   /* Unless an explicit instantiation directive has already determined
15447      the linkage of D, remember that a definition is available for
15448      this entity.  */
15449   if (pattern_defined
15450       && !DECL_INTERFACE_KNOWN (d)
15451       && !DECL_NOT_REALLY_EXTERN (d))
15452     mark_definable (d);
15453
15454   input_location = DECL_SOURCE_LOCATION (d);
15455
15456   /* If D is a member of an explicitly instantiated class template,
15457      and no definition is available, treat it like an implicit
15458      instantiation.  */
15459   if (!pattern_defined && expl_inst_class_mem_p
15460       && DECL_EXPLICIT_INSTANTIATION (d))
15461     {
15462       DECL_NOT_REALLY_EXTERN (d) = 0;
15463       DECL_INTERFACE_KNOWN (d) = 0;
15464       SET_DECL_IMPLICIT_INSTANTIATION (d);
15465     }
15466
15467   if (!defer_ok)
15468     {
15469       /* Recheck the substitutions to obtain any warning messages
15470          about ignoring cv qualifiers.  */
15471       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
15472       tree type = TREE_TYPE (gen);
15473
15474       /* Make sure that we can see identifiers, and compute access
15475          correctly.  D is already the target FUNCTION_DECL with the
15476          right context.  */
15477       push_access_scope (d);
15478
15479       if (TREE_CODE (gen) == FUNCTION_DECL)
15480         {
15481           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
15482           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
15483                                           d);
15484           /* Don't simply tsubst the function type, as that will give
15485              duplicate warnings about poor parameter qualifications.
15486              The function arguments are the same as the decl_arguments
15487              without the top level cv qualifiers.  */
15488           type = TREE_TYPE (type);
15489         }
15490       tsubst (type, gen_args, tf_warning_or_error, d);
15491
15492       pop_access_scope (d);
15493     }
15494
15495   /* Check to see whether we know that this template will be
15496      instantiated in some other file, as with "extern template"
15497      extension.  */
15498   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
15499   /* In general, we do not instantiate such templates...  */
15500   if (external_p
15501       /* ... but we instantiate inline functions so that we can inline
15502          them.  An explicit instantiation declaration prohibits implicit
15503          instantiation of non-inline functions.  With high levels of
15504          optimization, we would normally inline non-inline functions
15505          -- but we're not allowed to do that for "extern template" functions.
15506          Therefore, we check DECL_DECLARED_INLINE_P, rather than
15507          possibly_inlined_p.  And ...  */
15508       && ! (TREE_CODE (d) == FUNCTION_DECL
15509             && DECL_DECLARED_INLINE_P (d))
15510       /* ... we instantiate static data members whose values are
15511          needed in integral constant expressions.  */
15512       && ! (TREE_CODE (d) == VAR_DECL
15513             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
15514     goto out;
15515   /* Defer all other templates, unless we have been explicitly
15516      forbidden from doing so.  */
15517   if (/* If there is no definition, we cannot instantiate the
15518          template.  */
15519       ! pattern_defined
15520       /* If it's OK to postpone instantiation, do so.  */
15521       || defer_ok
15522       /* If this is a static data member that will be defined
15523          elsewhere, we don't want to instantiate the entire data
15524          member, but we do want to instantiate the initializer so that
15525          we can substitute that elsewhere.  */
15526       || (external_p && TREE_CODE (d) == VAR_DECL))
15527     {
15528       /* The definition of the static data member is now required so
15529          we must substitute the initializer.  */
15530       if (TREE_CODE (d) == VAR_DECL
15531           && !DECL_INITIAL (d)
15532           && DECL_INITIAL (code_pattern))
15533         {
15534           tree ns;
15535           tree init;
15536
15537           ns = decl_namespace_context (d);
15538           push_nested_namespace (ns);
15539           push_nested_class (DECL_CONTEXT (d));
15540           init = tsubst_expr (DECL_INITIAL (code_pattern),
15541                               args,
15542                               tf_warning_or_error, NULL_TREE,
15543                               /*integral_constant_expression_p=*/false);
15544           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
15545                           /*asmspec_tree=*/NULL_TREE,
15546                           LOOKUP_ONLYCONVERTING);
15547           pop_nested_class ();
15548           pop_nested_namespace (ns);
15549         }
15550
15551       /* We restore the source position here because it's used by
15552          add_pending_template.  */
15553       input_location = saved_loc;
15554
15555       if (at_eof && !pattern_defined
15556           && DECL_EXPLICIT_INSTANTIATION (d)
15557           && DECL_NOT_REALLY_EXTERN (d))
15558         /* [temp.explicit]
15559
15560            The definition of a non-exported function template, a
15561            non-exported member function template, or a non-exported
15562            member function or static data member of a class template
15563            shall be present in every translation unit in which it is
15564            explicitly instantiated.  */
15565         permerror (input_location,  "explicit instantiation of %qD "
15566                    "but no definition available", d);
15567
15568       /* ??? Historically, we have instantiated inline functions, even
15569          when marked as "extern template".  */
15570       if (!(external_p && TREE_CODE (d) == VAR_DECL))
15571         add_pending_template (d);
15572       goto out;
15573     }
15574   /* Tell the repository that D is available in this translation unit
15575      -- and see if it is supposed to be instantiated here.  */
15576   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15577     {
15578       /* In a PCH file, despite the fact that the repository hasn't
15579          requested instantiation in the PCH it is still possible that
15580          an instantiation will be required in a file that includes the
15581          PCH.  */
15582       if (pch_file)
15583         add_pending_template (d);
15584       /* Instantiate inline functions so that the inliner can do its
15585          job, even though we'll not be emitting a copy of this
15586          function.  */
15587       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
15588         goto out;
15589     }
15590
15591   need_push = !cfun || !global_bindings_p ();
15592   if (need_push)
15593     push_to_top_level ();
15594
15595   /* Mark D as instantiated so that recursive calls to
15596      instantiate_decl do not try to instantiate it again.  */
15597   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15598
15599   /* Regenerate the declaration in case the template has been modified
15600      by a subsequent redeclaration.  */
15601   regenerate_decl_from_template (d, td);
15602
15603   /* We already set the file and line above.  Reset them now in case
15604      they changed as a result of calling regenerate_decl_from_template.  */
15605   input_location = DECL_SOURCE_LOCATION (d);
15606
15607   if (TREE_CODE (d) == VAR_DECL)
15608     {
15609       tree init;
15610
15611       /* Clear out DECL_RTL; whatever was there before may not be right
15612          since we've reset the type of the declaration.  */
15613       SET_DECL_RTL (d, NULL_RTX);
15614       DECL_IN_AGGR_P (d) = 0;
15615
15616       /* The initializer is placed in DECL_INITIAL by
15617          regenerate_decl_from_template.  Pull it out so that
15618          finish_decl can process it.  */
15619       init = DECL_INITIAL (d);
15620       DECL_INITIAL (d) = NULL_TREE;
15621       DECL_INITIALIZED_P (d) = 0;
15622
15623       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15624          initializer.  That function will defer actual emission until
15625          we have a chance to determine linkage.  */
15626       DECL_EXTERNAL (d) = 0;
15627
15628       /* Enter the scope of D so that access-checking works correctly.  */
15629       push_nested_class (DECL_CONTEXT (d));
15630       finish_decl (d, init, NULL_TREE);
15631       pop_nested_class ();
15632     }
15633   else if (TREE_CODE (d) == FUNCTION_DECL)
15634     {
15635       htab_t saved_local_specializations;
15636       tree subst_decl;
15637       tree tmpl_parm;
15638       tree spec_parm;
15639
15640       /* Save away the current list, in case we are instantiating one
15641          template from within the body of another.  */
15642       saved_local_specializations = local_specializations;
15643
15644       /* Set up the list of local specializations.  */
15645       local_specializations = htab_create (37,
15646                                            hash_local_specialization,
15647                                            eq_local_specializations,
15648                                            NULL);
15649
15650       /* Set up context.  */
15651       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15652
15653       /* Create substitution entries for the parameters.  */
15654       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15655       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15656       spec_parm = DECL_ARGUMENTS (d);
15657       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15658         {
15659           register_local_specialization (spec_parm, tmpl_parm);
15660           spec_parm = skip_artificial_parms_for (d, spec_parm);
15661           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15662         }
15663       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15664         {
15665           register_local_specialization (spec_parm, tmpl_parm);
15666           tmpl_parm = TREE_CHAIN (tmpl_parm);
15667           spec_parm = TREE_CHAIN (spec_parm);
15668         }
15669       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15670         {
15671           /* Register the (value) argument pack as a specialization of
15672              TMPL_PARM, then move on.  */
15673           tree argpack = make_fnparm_pack (spec_parm);
15674           register_local_specialization (argpack, tmpl_parm);
15675           tmpl_parm = TREE_CHAIN (tmpl_parm);
15676           spec_parm = NULL_TREE;
15677         }
15678       gcc_assert (!spec_parm);
15679
15680       /* Substitute into the body of the function.  */
15681       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15682                    tf_warning_or_error, tmpl,
15683                    /*integral_constant_expression_p=*/false);
15684
15685       /* Set the current input_location to the end of the function
15686          so that finish_function knows where we are.  */
15687       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15688
15689       /* We don't need the local specializations any more.  */
15690       htab_delete (local_specializations);
15691       local_specializations = saved_local_specializations;
15692
15693       /* Finish the function.  */
15694       d = finish_function (0);
15695       expand_or_defer_fn (d);
15696     }
15697
15698   /* We're not deferring instantiation any more.  */
15699   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15700
15701   if (need_push)
15702     pop_from_top_level ();
15703
15704 out:
15705   input_location = saved_loc;
15706   pop_deferring_access_checks ();
15707   pop_tinst_level ();
15708
15709   timevar_pop (TV_PARSE);
15710
15711   return d;
15712 }
15713
15714 /* Run through the list of templates that we wish we could
15715    instantiate, and instantiate any we can.  RETRIES is the
15716    number of times we retry pending template instantiation.  */
15717
15718 void
15719 instantiate_pending_templates (int retries)
15720 {
15721   int reconsider;
15722   location_t saved_loc = input_location;
15723
15724   /* Instantiating templates may trigger vtable generation.  This in turn
15725      may require further template instantiations.  We place a limit here
15726      to avoid infinite loop.  */
15727   if (pending_templates && retries >= max_tinst_depth)
15728     {
15729       tree decl = pending_templates->tinst->decl;
15730
15731       error ("template instantiation depth exceeds maximum of %d"
15732              " instantiating %q+D, possibly from virtual table generation"
15733              " (use -ftemplate-depth-NN to increase the maximum)",
15734              max_tinst_depth, decl);
15735       if (TREE_CODE (decl) == FUNCTION_DECL)
15736         /* Pretend that we defined it.  */
15737         DECL_INITIAL (decl) = error_mark_node;
15738       return;
15739     }
15740
15741   do
15742     {
15743       struct pending_template **t = &pending_templates;
15744       struct pending_template *last = NULL;
15745       reconsider = 0;
15746       while (*t)
15747         {
15748           tree instantiation = reopen_tinst_level ((*t)->tinst);
15749           bool complete = false;
15750
15751           if (TYPE_P (instantiation))
15752             {
15753               tree fn;
15754
15755               if (!COMPLETE_TYPE_P (instantiation))
15756                 {
15757                   instantiate_class_template (instantiation);
15758                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15759                     for (fn = TYPE_METHODS (instantiation);
15760                          fn;
15761                          fn = TREE_CHAIN (fn))
15762                       if (! DECL_ARTIFICIAL (fn))
15763                         instantiate_decl (fn,
15764                                           /*defer_ok=*/0,
15765                                           /*expl_inst_class_mem_p=*/false);
15766                   if (COMPLETE_TYPE_P (instantiation))
15767                     reconsider = 1;
15768                 }
15769
15770               complete = COMPLETE_TYPE_P (instantiation);
15771             }
15772           else
15773             {
15774               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15775                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15776                 {
15777                   instantiation
15778                     = instantiate_decl (instantiation,
15779                                         /*defer_ok=*/0,
15780                                         /*expl_inst_class_mem_p=*/false);
15781                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15782                     reconsider = 1;
15783                 }
15784
15785               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15786                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15787             }
15788
15789           if (complete)
15790             /* If INSTANTIATION has been instantiated, then we don't
15791                need to consider it again in the future.  */
15792             *t = (*t)->next;
15793           else
15794             {
15795               last = *t;
15796               t = &(*t)->next;
15797             }
15798           tinst_depth = 0;
15799           current_tinst_level = NULL;
15800         }
15801       last_pending_template = last;
15802     }
15803   while (reconsider);
15804
15805   input_location = saved_loc;
15806 }
15807
15808 /* Substitute ARGVEC into T, which is a list of initializers for
15809    either base class or a non-static data member.  The TREE_PURPOSEs
15810    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15811    instantiate_decl.  */
15812
15813 static tree
15814 tsubst_initializer_list (tree t, tree argvec)
15815 {
15816   tree inits = NULL_TREE;
15817
15818   for (; t; t = TREE_CHAIN (t))
15819     {
15820       tree decl;
15821       tree init;
15822       tree expanded_bases = NULL_TREE;
15823       tree expanded_arguments = NULL_TREE;
15824       int i, len = 1;
15825
15826       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15827         {
15828           tree expr;
15829           tree arg;
15830
15831           /* Expand the base class expansion type into separate base
15832              classes.  */
15833           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15834                                                  tf_warning_or_error,
15835                                                  NULL_TREE);
15836           if (expanded_bases == error_mark_node)
15837             continue;
15838           
15839           /* We'll be building separate TREE_LISTs of arguments for
15840              each base.  */
15841           len = TREE_VEC_LENGTH (expanded_bases);
15842           expanded_arguments = make_tree_vec (len);
15843           for (i = 0; i < len; i++)
15844             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15845
15846           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15847              expand each argument in the TREE_VALUE of t.  */
15848           expr = make_node (EXPR_PACK_EXPANSION);
15849           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15850             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15851
15852           if (TREE_VALUE (t) == void_type_node)
15853             /* VOID_TYPE_NODE is used to indicate
15854                value-initialization.  */
15855             {
15856               for (i = 0; i < len; i++)
15857                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
15858             }
15859           else
15860             {
15861               /* Substitute parameter packs into each argument in the
15862                  TREE_LIST.  */
15863               in_base_initializer = 1;
15864               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15865                 {
15866                   tree expanded_exprs;
15867
15868                   /* Expand the argument.  */
15869                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15870                   expanded_exprs 
15871                     = tsubst_pack_expansion (expr, argvec,
15872                                              tf_warning_or_error,
15873                                              NULL_TREE);
15874                   if (expanded_exprs == error_mark_node)
15875                     continue;
15876
15877                   /* Prepend each of the expanded expressions to the
15878                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15879                   for (i = 0; i < len; i++)
15880                     {
15881                       TREE_VEC_ELT (expanded_arguments, i) = 
15882                         tree_cons (NULL_TREE, 
15883                                    TREE_VEC_ELT (expanded_exprs, i),
15884                                    TREE_VEC_ELT (expanded_arguments, i));
15885                     }
15886                 }
15887               in_base_initializer = 0;
15888
15889               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15890                  since we built them backwards.  */
15891               for (i = 0; i < len; i++)
15892                 {
15893                   TREE_VEC_ELT (expanded_arguments, i) = 
15894                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
15895                 }
15896             }
15897         }
15898
15899       for (i = 0; i < len; ++i)
15900         {
15901           if (expanded_bases)
15902             {
15903               decl = TREE_VEC_ELT (expanded_bases, i);
15904               decl = expand_member_init (decl);
15905               init = TREE_VEC_ELT (expanded_arguments, i);
15906             }
15907           else
15908             {
15909               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15910                                   tf_warning_or_error, NULL_TREE);
15911
15912               decl = expand_member_init (decl);
15913               if (decl && !DECL_P (decl))
15914                 in_base_initializer = 1;
15915
15916               init = tsubst_expr (TREE_VALUE (t), argvec, 
15917                                   tf_warning_or_error, NULL_TREE,
15918                                   /*integral_constant_expression_p=*/false);
15919               in_base_initializer = 0;
15920             }
15921
15922           if (decl)
15923             {
15924               init = build_tree_list (decl, init);
15925               TREE_CHAIN (init) = inits;
15926               inits = init;
15927             }
15928         }
15929     }
15930   return inits;
15931 }
15932
15933 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
15934
15935 static void
15936 set_current_access_from_decl (tree decl)
15937 {
15938   if (TREE_PRIVATE (decl))
15939     current_access_specifier = access_private_node;
15940   else if (TREE_PROTECTED (decl))
15941     current_access_specifier = access_protected_node;
15942   else
15943     current_access_specifier = access_public_node;
15944 }
15945
15946 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
15947    is the instantiation (which should have been created with
15948    start_enum) and ARGS are the template arguments to use.  */
15949
15950 static void
15951 tsubst_enum (tree tag, tree newtag, tree args)
15952 {
15953   tree e;
15954
15955   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
15956     {
15957       tree value;
15958       tree decl;
15959
15960       decl = TREE_VALUE (e);
15961       /* Note that in a template enum, the TREE_VALUE is the
15962          CONST_DECL, not the corresponding INTEGER_CST.  */
15963       value = tsubst_expr (DECL_INITIAL (decl),
15964                            args, tf_warning_or_error, NULL_TREE,
15965                            /*integral_constant_expression_p=*/true);
15966
15967       /* Give this enumeration constant the correct access.  */
15968       set_current_access_from_decl (decl);
15969
15970       /* Actually build the enumerator itself.  */
15971       build_enumerator (DECL_NAME (decl), value, newtag);
15972     }
15973
15974   finish_enum (newtag);
15975   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
15976     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
15977 }
15978
15979 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
15980    its type -- but without substituting the innermost set of template
15981    arguments.  So, innermost set of template parameters will appear in
15982    the type.  */
15983
15984 tree
15985 get_mostly_instantiated_function_type (tree decl)
15986 {
15987   tree fn_type;
15988   tree tmpl;
15989   tree targs;
15990   tree tparms;
15991   int parm_depth;
15992
15993   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15994   targs = DECL_TI_ARGS (decl);
15995   tparms = DECL_TEMPLATE_PARMS (tmpl);
15996   parm_depth = TMPL_PARMS_DEPTH (tparms);
15997
15998   /* There should be as many levels of arguments as there are levels
15999      of parameters.  */
16000   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16001
16002   fn_type = TREE_TYPE (tmpl);
16003
16004   if (parm_depth == 1)
16005     /* No substitution is necessary.  */
16006     ;
16007   else
16008     {
16009       int i, save_access_control;
16010       tree partial_args;
16011
16012       /* Replace the innermost level of the TARGS with NULL_TREEs to
16013          let tsubst know not to substitute for those parameters.  */
16014       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16015       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16016         SET_TMPL_ARGS_LEVEL (partial_args, i,
16017                              TMPL_ARGS_LEVEL (targs, i));
16018       SET_TMPL_ARGS_LEVEL (partial_args,
16019                            TMPL_ARGS_DEPTH (targs),
16020                            make_tree_vec (DECL_NTPARMS (tmpl)));
16021
16022       /* Disable access control as this function is used only during
16023          name-mangling.  */
16024       save_access_control = flag_access_control;
16025       flag_access_control = 0;
16026
16027       ++processing_template_decl;
16028       /* Now, do the (partial) substitution to figure out the
16029          appropriate function type.  */
16030       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16031       --processing_template_decl;
16032
16033       /* Substitute into the template parameters to obtain the real
16034          innermost set of parameters.  This step is important if the
16035          innermost set of template parameters contains value
16036          parameters whose types depend on outer template parameters.  */
16037       TREE_VEC_LENGTH (partial_args)--;
16038       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16039
16040       flag_access_control = save_access_control;
16041     }
16042
16043   return fn_type;
16044 }
16045
16046 /* Return truthvalue if we're processing a template different from
16047    the last one involved in diagnostics.  */
16048 int
16049 problematic_instantiation_changed (void)
16050 {
16051   return last_template_error_tick != tinst_level_tick;
16052 }
16053
16054 /* Remember current template involved in diagnostics.  */
16055 void
16056 record_last_problematic_instantiation (void)
16057 {
16058   last_template_error_tick = tinst_level_tick;
16059 }
16060
16061 struct tinst_level *
16062 current_instantiation (void)
16063 {
16064   return current_tinst_level;
16065 }
16066
16067 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16068    type. Return zero for ok, nonzero for disallowed. Issue error and
16069    warning messages under control of COMPLAIN.  */
16070
16071 static int
16072 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16073 {
16074   if (INTEGRAL_TYPE_P (type))
16075     return 0;
16076   else if (POINTER_TYPE_P (type))
16077     return 0;
16078   else if (TYPE_PTR_TO_MEMBER_P (type))
16079     return 0;
16080   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16081     return 0;
16082   else if (TREE_CODE (type) == TYPENAME_TYPE)
16083     return 0;
16084
16085   if (complain & tf_error)
16086     error ("%q#T is not a valid type for a template constant parameter", type);
16087   return 1;
16088 }
16089
16090 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16091    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16092
16093 static bool
16094 dependent_type_p_r (tree type)
16095 {
16096   tree scope;
16097
16098   /* [temp.dep.type]
16099
16100      A type is dependent if it is:
16101
16102      -- a template parameter. Template template parameters are types
16103         for us (since TYPE_P holds true for them) so we handle
16104         them here.  */
16105   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16106       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
16107     return true;
16108   /* -- a qualified-id with a nested-name-specifier which contains a
16109         class-name that names a dependent type or whose unqualified-id
16110         names a dependent type.  */
16111   if (TREE_CODE (type) == TYPENAME_TYPE)
16112     return true;
16113   /* -- a cv-qualified type where the cv-unqualified type is
16114         dependent.  */
16115   type = TYPE_MAIN_VARIANT (type);
16116   /* -- a compound type constructed from any dependent type.  */
16117   if (TYPE_PTR_TO_MEMBER_P (type))
16118     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
16119             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
16120                                            (type)));
16121   else if (TREE_CODE (type) == POINTER_TYPE
16122            || TREE_CODE (type) == REFERENCE_TYPE)
16123     return dependent_type_p (TREE_TYPE (type));
16124   else if (TREE_CODE (type) == FUNCTION_TYPE
16125            || TREE_CODE (type) == METHOD_TYPE)
16126     {
16127       tree arg_type;
16128
16129       if (dependent_type_p (TREE_TYPE (type)))
16130         return true;
16131       for (arg_type = TYPE_ARG_TYPES (type);
16132            arg_type;
16133            arg_type = TREE_CHAIN (arg_type))
16134         if (dependent_type_p (TREE_VALUE (arg_type)))
16135           return true;
16136       return false;
16137     }
16138   /* -- an array type constructed from any dependent type or whose
16139         size is specified by a constant expression that is
16140         value-dependent.  */
16141   if (TREE_CODE (type) == ARRAY_TYPE)
16142     {
16143       if (TYPE_DOMAIN (type)
16144           && dependent_type_p (TYPE_DOMAIN (type)))
16145         return true;
16146       return dependent_type_p (TREE_TYPE (type));
16147     }
16148   else if (TREE_CODE (type) == INTEGER_TYPE
16149            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
16150     {
16151       /* If this is the TYPE_DOMAIN of an array type, consider it
16152          dependent.  We already checked for value-dependence in
16153          compute_array_index_type.  */
16154       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
16155     }
16156
16157   /* -- a template-id in which either the template name is a template
16158      parameter ...  */
16159   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16160     return true;
16161   /* ... or any of the template arguments is a dependent type or
16162         an expression that is type-dependent or value-dependent.  */
16163   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
16164            && (any_dependent_template_arguments_p
16165                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
16166     return true;
16167
16168   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
16169      argument of the `typeof' expression is not type-dependent, then
16170      it should already been have resolved.  */
16171   if (TREE_CODE (type) == TYPEOF_TYPE
16172       || TREE_CODE (type) == DECLTYPE_TYPE)
16173     return true;
16174
16175   /* A template argument pack is dependent if any of its packed
16176      arguments are.  */
16177   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
16178     {
16179       tree args = ARGUMENT_PACK_ARGS (type);
16180       int i, len = TREE_VEC_LENGTH (args);
16181       for (i = 0; i < len; ++i)
16182         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16183           return true;
16184     }
16185
16186   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
16187      be template parameters.  */
16188   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
16189     return true;
16190
16191   /* The standard does not specifically mention types that are local
16192      to template functions or local classes, but they should be
16193      considered dependent too.  For example:
16194
16195        template <int I> void f() {
16196          enum E { a = I };
16197          S<sizeof (E)> s;
16198        }
16199
16200      The size of `E' cannot be known until the value of `I' has been
16201      determined.  Therefore, `E' must be considered dependent.  */
16202   scope = TYPE_CONTEXT (type);
16203   if (scope && TYPE_P (scope))
16204     return dependent_type_p (scope);
16205   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
16206     return type_dependent_expression_p (scope);
16207
16208   /* Other types are non-dependent.  */
16209   return false;
16210 }
16211
16212 /* Returns TRUE if TYPE is dependent, in the sense of
16213    [temp.dep.type].  */
16214
16215 bool
16216 dependent_type_p (tree type)
16217 {
16218   /* If there are no template parameters in scope, then there can't be
16219      any dependent types.  */
16220   if (!processing_template_decl)
16221     {
16222       /* If we are not processing a template, then nobody should be
16223          providing us with a dependent type.  */
16224       gcc_assert (type);
16225       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
16226       return false;
16227     }
16228
16229   /* If the type is NULL, we have not computed a type for the entity
16230      in question; in that case, the type is dependent.  */
16231   if (!type)
16232     return true;
16233
16234   /* Erroneous types can be considered non-dependent.  */
16235   if (type == error_mark_node)
16236     return false;
16237
16238   /* If we have not already computed the appropriate value for TYPE,
16239      do so now.  */
16240   if (!TYPE_DEPENDENT_P_VALID (type))
16241     {
16242       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
16243       TYPE_DEPENDENT_P_VALID (type) = 1;
16244     }
16245
16246   return TYPE_DEPENDENT_P (type);
16247 }
16248
16249 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
16250    lookup.  In other words, a dependent type that is not the current
16251    instantiation.  */
16252
16253 bool
16254 dependent_scope_p (tree scope)
16255 {
16256   return (scope && TYPE_P (scope) && dependent_type_p (scope)
16257           && !currently_open_class (scope));
16258 }
16259
16260 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
16261
16262 static bool
16263 dependent_scope_ref_p (tree expression, bool criterion (tree))
16264 {
16265   tree scope;
16266   tree name;
16267
16268   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
16269
16270   if (!TYPE_P (TREE_OPERAND (expression, 0)))
16271     return true;
16272
16273   scope = TREE_OPERAND (expression, 0);
16274   name = TREE_OPERAND (expression, 1);
16275
16276   /* [temp.dep.expr]
16277
16278      An id-expression is type-dependent if it contains a
16279      nested-name-specifier that contains a class-name that names a
16280      dependent type.  */
16281   /* The suggested resolution to Core Issue 224 implies that if the
16282      qualifying type is the current class, then we must peek
16283      inside it.  */
16284   if (DECL_P (name)
16285       && currently_open_class (scope)
16286       && !criterion (name))
16287     return false;
16288   if (dependent_type_p (scope))
16289     return true;
16290
16291   return false;
16292 }
16293
16294 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
16295    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
16296    expression.  */
16297
16298 bool
16299 value_dependent_expression_p (tree expression)
16300 {
16301   if (!processing_template_decl)
16302     return false;
16303
16304   /* A name declared with a dependent type.  */
16305   if (DECL_P (expression) && type_dependent_expression_p (expression))
16306     return true;
16307
16308   switch (TREE_CODE (expression))
16309     {
16310     case IDENTIFIER_NODE:
16311       /* A name that has not been looked up -- must be dependent.  */
16312       return true;
16313
16314     case TEMPLATE_PARM_INDEX:
16315       /* A non-type template parm.  */
16316       return true;
16317
16318     case CONST_DECL:
16319       /* A non-type template parm.  */
16320       if (DECL_TEMPLATE_PARM_P (expression))
16321         return true;
16322       return value_dependent_expression_p (DECL_INITIAL (expression));
16323
16324     case VAR_DECL:
16325        /* A constant with integral or enumeration type and is initialized
16326           with an expression that is value-dependent.  */
16327       if (DECL_INITIAL (expression)
16328           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
16329           && value_dependent_expression_p (DECL_INITIAL (expression)))
16330         return true;
16331       return false;
16332
16333     case DYNAMIC_CAST_EXPR:
16334     case STATIC_CAST_EXPR:
16335     case CONST_CAST_EXPR:
16336     case REINTERPRET_CAST_EXPR:
16337     case CAST_EXPR:
16338       /* These expressions are value-dependent if the type to which
16339          the cast occurs is dependent or the expression being casted
16340          is value-dependent.  */
16341       {
16342         tree type = TREE_TYPE (expression);
16343
16344         if (dependent_type_p (type))
16345           return true;
16346
16347         /* A functional cast has a list of operands.  */
16348         expression = TREE_OPERAND (expression, 0);
16349         if (!expression)
16350           {
16351             /* If there are no operands, it must be an expression such
16352                as "int()". This should not happen for aggregate types
16353                because it would form non-constant expressions.  */
16354             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
16355
16356             return false;
16357           }
16358
16359         if (TREE_CODE (expression) == TREE_LIST)
16360           return any_value_dependent_elements_p (expression);
16361
16362         return value_dependent_expression_p (expression);
16363       }
16364
16365     case SIZEOF_EXPR:
16366     case ALIGNOF_EXPR:
16367       /* A `sizeof' expression is value-dependent if the operand is
16368          type-dependent or is a pack expansion.  */
16369       expression = TREE_OPERAND (expression, 0);
16370       if (PACK_EXPANSION_P (expression))
16371         return true;
16372       else if (TYPE_P (expression))
16373         return dependent_type_p (expression);
16374       return type_dependent_expression_p (expression);
16375
16376     case SCOPE_REF:
16377       return dependent_scope_ref_p (expression, value_dependent_expression_p);
16378
16379     case COMPONENT_REF:
16380       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
16381               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
16382
16383     case CALL_EXPR:
16384       /* A CALL_EXPR may appear in a constant expression if it is a
16385          call to a builtin function, e.g., __builtin_constant_p.  All
16386          such calls are value-dependent.  */
16387       return true;
16388
16389     case NONTYPE_ARGUMENT_PACK:
16390       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
16391          is value-dependent.  */
16392       {
16393         tree values = ARGUMENT_PACK_ARGS (expression);
16394         int i, len = TREE_VEC_LENGTH (values);
16395         
16396         for (i = 0; i < len; ++i)
16397           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
16398             return true;
16399         
16400         return false;
16401       }
16402
16403     case TRAIT_EXPR:
16404       {
16405         tree type2 = TRAIT_EXPR_TYPE2 (expression);
16406         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
16407                 || (type2 ? dependent_type_p (type2) : false));
16408       }
16409
16410     case MODOP_EXPR:
16411       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
16412               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
16413
16414     default:
16415       /* A constant expression is value-dependent if any subexpression is
16416          value-dependent.  */
16417       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
16418         {
16419         case tcc_reference:
16420         case tcc_unary:
16421           return (value_dependent_expression_p
16422                   (TREE_OPERAND (expression, 0)));
16423
16424         case tcc_comparison:
16425         case tcc_binary:
16426           return ((value_dependent_expression_p
16427                    (TREE_OPERAND (expression, 0)))
16428                   || (value_dependent_expression_p
16429                       (TREE_OPERAND (expression, 1))));
16430
16431         case tcc_expression:
16432         case tcc_vl_exp:
16433           {
16434             int i;
16435             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
16436               /* In some cases, some of the operands may be missing.
16437                  (For example, in the case of PREDECREMENT_EXPR, the
16438                  amount to increment by may be missing.)  That doesn't
16439                  make the expression dependent.  */
16440               if (TREE_OPERAND (expression, i)
16441                   && (value_dependent_expression_p
16442                       (TREE_OPERAND (expression, i))))
16443                 return true;
16444             return false;
16445           }
16446
16447         default:
16448           break;
16449         }
16450     }
16451
16452   /* The expression is not value-dependent.  */
16453   return false;
16454 }
16455
16456 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
16457    [temp.dep.expr].  */
16458
16459 bool
16460 type_dependent_expression_p (tree expression)
16461 {
16462   if (!processing_template_decl)
16463     return false;
16464
16465   if (expression == error_mark_node)
16466     return false;
16467
16468   /* An unresolved name is always dependent.  */
16469   if (TREE_CODE (expression) == IDENTIFIER_NODE
16470       || TREE_CODE (expression) == USING_DECL)
16471     return true;
16472
16473   /* Some expression forms are never type-dependent.  */
16474   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
16475       || TREE_CODE (expression) == SIZEOF_EXPR
16476       || TREE_CODE (expression) == ALIGNOF_EXPR
16477       || TREE_CODE (expression) == TRAIT_EXPR
16478       || TREE_CODE (expression) == TYPEID_EXPR
16479       || TREE_CODE (expression) == DELETE_EXPR
16480       || TREE_CODE (expression) == VEC_DELETE_EXPR
16481       || TREE_CODE (expression) == THROW_EXPR)
16482     return false;
16483
16484   /* The types of these expressions depends only on the type to which
16485      the cast occurs.  */
16486   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
16487       || TREE_CODE (expression) == STATIC_CAST_EXPR
16488       || TREE_CODE (expression) == CONST_CAST_EXPR
16489       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
16490       || TREE_CODE (expression) == CAST_EXPR)
16491     return dependent_type_p (TREE_TYPE (expression));
16492
16493   /* The types of these expressions depends only on the type created
16494      by the expression.  */
16495   if (TREE_CODE (expression) == NEW_EXPR
16496       || TREE_CODE (expression) == VEC_NEW_EXPR)
16497     {
16498       /* For NEW_EXPR tree nodes created inside a template, either
16499          the object type itself or a TREE_LIST may appear as the
16500          operand 1.  */
16501       tree type = TREE_OPERAND (expression, 1);
16502       if (TREE_CODE (type) == TREE_LIST)
16503         /* This is an array type.  We need to check array dimensions
16504            as well.  */
16505         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
16506                || value_dependent_expression_p
16507                     (TREE_OPERAND (TREE_VALUE (type), 1));
16508       else
16509         return dependent_type_p (type);
16510     }
16511
16512   if (TREE_CODE (expression) == SCOPE_REF
16513       && dependent_scope_ref_p (expression,
16514                                 type_dependent_expression_p))
16515     return true;
16516
16517   if (TREE_CODE (expression) == FUNCTION_DECL
16518       && DECL_LANG_SPECIFIC (expression)
16519       && DECL_TEMPLATE_INFO (expression)
16520       && (any_dependent_template_arguments_p
16521           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
16522     return true;
16523
16524   if (TREE_CODE (expression) == TEMPLATE_DECL
16525       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
16526     return false;
16527
16528   if (TREE_CODE (expression) == STMT_EXPR)
16529     expression = stmt_expr_value_expr (expression);
16530
16531   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
16532     {
16533       tree elt;
16534       unsigned i;
16535
16536       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
16537         {
16538           if (type_dependent_expression_p (elt))
16539             return true;
16540         }
16541       return false;
16542     }
16543
16544   if (TREE_TYPE (expression) == unknown_type_node)
16545     {
16546       if (TREE_CODE (expression) == ADDR_EXPR)
16547         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
16548       if (TREE_CODE (expression) == COMPONENT_REF
16549           || TREE_CODE (expression) == OFFSET_REF)
16550         {
16551           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
16552             return true;
16553           expression = TREE_OPERAND (expression, 1);
16554           if (TREE_CODE (expression) == IDENTIFIER_NODE)
16555             return false;
16556         }
16557       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
16558       if (TREE_CODE (expression) == SCOPE_REF)
16559         return false;
16560
16561       if (TREE_CODE (expression) == BASELINK)
16562         expression = BASELINK_FUNCTIONS (expression);
16563
16564       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
16565         {
16566           if (any_dependent_template_arguments_p
16567               (TREE_OPERAND (expression, 1)))
16568             return true;
16569           expression = TREE_OPERAND (expression, 0);
16570         }
16571       gcc_assert (TREE_CODE (expression) == OVERLOAD
16572                   || TREE_CODE (expression) == FUNCTION_DECL);
16573
16574       while (expression)
16575         {
16576           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16577             return true;
16578           expression = OVL_NEXT (expression);
16579         }
16580       return false;
16581     }
16582
16583   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16584
16585   return (dependent_type_p (TREE_TYPE (expression)));
16586 }
16587
16588 /* Like type_dependent_expression_p, but it also works while not processing
16589    a template definition, i.e. during substitution or mangling.  */
16590
16591 bool
16592 type_dependent_expression_p_push (tree expr)
16593 {
16594   bool b;
16595   ++processing_template_decl;
16596   b = type_dependent_expression_p (expr);
16597   --processing_template_decl;
16598   return b;
16599 }
16600
16601 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
16602    contains a type-dependent expression.  */
16603
16604 bool
16605 any_type_dependent_arguments_p (const_tree args)
16606 {
16607   while (args)
16608     {
16609       tree arg = TREE_VALUE (args);
16610
16611       if (type_dependent_expression_p (arg))
16612         return true;
16613       args = TREE_CHAIN (args);
16614     }
16615   return false;
16616 }
16617
16618 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16619    expressions) contains any value-dependent expressions.  */
16620
16621 bool
16622 any_value_dependent_elements_p (const_tree list)
16623 {
16624   for (; list; list = TREE_CHAIN (list))
16625     if (value_dependent_expression_p (TREE_VALUE (list)))
16626       return true;
16627
16628   return false;
16629 }
16630
16631 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16632
16633 bool
16634 dependent_template_arg_p (tree arg)
16635 {
16636   if (!processing_template_decl)
16637     return false;
16638
16639   if (TREE_CODE (arg) == TEMPLATE_DECL
16640       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16641     return dependent_template_p (arg);
16642   else if (ARGUMENT_PACK_P (arg))
16643     {
16644       tree args = ARGUMENT_PACK_ARGS (arg);
16645       int i, len = TREE_VEC_LENGTH (args);
16646       for (i = 0; i < len; ++i)
16647         {
16648           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16649             return true;
16650         }
16651
16652       return false;
16653     }
16654   else if (TYPE_P (arg))
16655     return dependent_type_p (arg);
16656   else
16657     return (type_dependent_expression_p (arg)
16658             || value_dependent_expression_p (arg));
16659 }
16660
16661 /* Returns true if ARGS (a collection of template arguments) contains
16662    any types that require structural equality testing.  */
16663
16664 bool
16665 any_template_arguments_need_structural_equality_p (tree args)
16666 {
16667   int i;
16668   int j;
16669
16670   if (!args)
16671     return false;
16672   if (args == error_mark_node)
16673     return true;
16674
16675   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16676     {
16677       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16678       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16679         {
16680           tree arg = TREE_VEC_ELT (level, j);
16681           tree packed_args = NULL_TREE;
16682           int k, len = 1;
16683
16684           if (ARGUMENT_PACK_P (arg))
16685             {
16686               /* Look inside the argument pack.  */
16687               packed_args = ARGUMENT_PACK_ARGS (arg);
16688               len = TREE_VEC_LENGTH (packed_args);
16689             }
16690
16691           for (k = 0; k < len; ++k)
16692             {
16693               if (packed_args)
16694                 arg = TREE_VEC_ELT (packed_args, k);
16695
16696               if (error_operand_p (arg))
16697                 return true;
16698               else if (TREE_CODE (arg) == TEMPLATE_DECL
16699                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16700                 continue;
16701               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
16702                 return true;
16703               else if (!TYPE_P (arg) && TREE_TYPE (arg)
16704                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
16705                 return true;
16706             }
16707         }
16708     }
16709
16710   return false;
16711 }
16712
16713 /* Returns true if ARGS (a collection of template arguments) contains
16714    any dependent arguments.  */
16715
16716 bool
16717 any_dependent_template_arguments_p (const_tree args)
16718 {
16719   int i;
16720   int j;
16721
16722   if (!args)
16723     return false;
16724   if (args == error_mark_node)
16725     return true;
16726
16727   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16728     {
16729       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16730       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16731         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16732           return true;
16733     }
16734
16735   return false;
16736 }
16737
16738 /* Returns TRUE if the template TMPL is dependent.  */
16739
16740 bool
16741 dependent_template_p (tree tmpl)
16742 {
16743   if (TREE_CODE (tmpl) == OVERLOAD)
16744     {
16745       while (tmpl)
16746         {
16747           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16748             return true;
16749           tmpl = OVL_CHAIN (tmpl);
16750         }
16751       return false;
16752     }
16753
16754   /* Template template parameters are dependent.  */
16755   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16756       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16757     return true;
16758   /* So are names that have not been looked up.  */
16759   if (TREE_CODE (tmpl) == SCOPE_REF
16760       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16761     return true;
16762   /* So are member templates of dependent classes.  */
16763   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16764     return dependent_type_p (DECL_CONTEXT (tmpl));
16765   return false;
16766 }
16767
16768 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16769
16770 bool
16771 dependent_template_id_p (tree tmpl, tree args)
16772 {
16773   return (dependent_template_p (tmpl)
16774           || any_dependent_template_arguments_p (args));
16775 }
16776
16777 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
16778    is dependent.  */
16779
16780 bool
16781 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
16782 {
16783   int i;
16784
16785   if (!processing_template_decl)
16786     return false;
16787
16788   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
16789     {
16790       tree decl = TREE_VEC_ELT (declv, i);
16791       tree init = TREE_VEC_ELT (initv, i);
16792       tree cond = TREE_VEC_ELT (condv, i);
16793       tree incr = TREE_VEC_ELT (incrv, i);
16794
16795       if (type_dependent_expression_p (decl))
16796         return true;
16797
16798       if (init && type_dependent_expression_p (init))
16799         return true;
16800
16801       if (type_dependent_expression_p (cond))
16802         return true;
16803
16804       if (COMPARISON_CLASS_P (cond)
16805           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
16806               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
16807         return true;
16808
16809       if (TREE_CODE (incr) == MODOP_EXPR)
16810         {
16811           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
16812               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
16813             return true;
16814         }
16815       else if (type_dependent_expression_p (incr))
16816         return true;
16817       else if (TREE_CODE (incr) == MODIFY_EXPR)
16818         {
16819           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
16820             return true;
16821           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
16822             {
16823               tree t = TREE_OPERAND (incr, 1);
16824               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
16825                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
16826                 return true;
16827             }
16828         }
16829     }
16830
16831   return false;
16832 }
16833
16834 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16835    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16836    no such TYPE can be found.  Note that this function peers inside
16837    uninstantiated templates and therefore should be used only in
16838    extremely limited situations.  ONLY_CURRENT_P restricts this
16839    peering to the currently open classes hierarchy (which is required
16840    when comparing types).  */
16841
16842 tree
16843 resolve_typename_type (tree type, bool only_current_p)
16844 {
16845   tree scope;
16846   tree name;
16847   tree decl;
16848   int quals;
16849   tree pushed_scope;
16850   tree result;
16851
16852   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16853
16854   scope = TYPE_CONTEXT (type);
16855   name = TYPE_IDENTIFIER (type);
16856
16857   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16858      it first before we can figure out what NAME refers to.  */
16859   if (TREE_CODE (scope) == TYPENAME_TYPE)
16860     scope = resolve_typename_type (scope, only_current_p);
16861   /* If we don't know what SCOPE refers to, then we cannot resolve the
16862      TYPENAME_TYPE.  */
16863   if (TREE_CODE (scope) == TYPENAME_TYPE)
16864     return type;
16865   /* If the SCOPE is a template type parameter, we have no way of
16866      resolving the name.  */
16867   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16868     return type;
16869   /* If the SCOPE is not the current instantiation, there's no reason
16870      to look inside it.  */
16871   if (only_current_p && !currently_open_class (scope))
16872     return type;
16873   /* If SCOPE isn't the template itself, it will not have a valid
16874      TYPE_FIELDS list.  */
16875   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16876     /* scope is either the template itself or a compatible instantiation
16877        like X<T>, so look up the name in the original template.  */
16878     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16879   else
16880     /* scope is a partial instantiation, so we can't do the lookup or we
16881        will lose the template arguments.  */
16882     return type;
16883   /* Enter the SCOPE so that name lookup will be resolved as if we
16884      were in the class definition.  In particular, SCOPE will no
16885      longer be considered a dependent type.  */
16886   pushed_scope = push_scope (scope);
16887   /* Look up the declaration.  */
16888   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16889
16890   result = NULL_TREE;
16891   
16892   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
16893      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
16894   if (!decl)
16895     /*nop*/;
16896   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
16897            && TREE_CODE (decl) == TYPE_DECL)
16898     {
16899       result = TREE_TYPE (decl);
16900       if (result == error_mark_node)
16901         result = NULL_TREE;
16902     }
16903   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
16904            && DECL_CLASS_TEMPLATE_P (decl))
16905     {
16906       tree tmpl;
16907       tree args;
16908       /* Obtain the template and the arguments.  */
16909       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
16910       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
16911       /* Instantiate the template.  */
16912       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
16913                                       /*entering_scope=*/0,
16914                                       tf_error | tf_user);
16915       if (result == error_mark_node)
16916         result = NULL_TREE;
16917     }
16918   
16919   /* Leave the SCOPE.  */
16920   if (pushed_scope)
16921     pop_scope (pushed_scope);
16922
16923   /* If we failed to resolve it, return the original typename.  */
16924   if (!result)
16925     return type;
16926   
16927   /* If lookup found a typename type, resolve that too.  */
16928   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
16929     {
16930       /* Ill-formed programs can cause infinite recursion here, so we
16931          must catch that.  */
16932       TYPENAME_IS_RESOLVING_P (type) = 1;
16933       result = resolve_typename_type (result, only_current_p);
16934       TYPENAME_IS_RESOLVING_P (type) = 0;
16935     }
16936   
16937   /* Qualify the resulting type.  */
16938   quals = cp_type_quals (type);
16939   if (quals)
16940     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
16941
16942   return result;
16943 }
16944
16945 /* EXPR is an expression which is not type-dependent.  Return a proxy
16946    for EXPR that can be used to compute the types of larger
16947    expressions containing EXPR.  */
16948
16949 tree
16950 build_non_dependent_expr (tree expr)
16951 {
16952   tree inner_expr;
16953
16954   /* Preserve null pointer constants so that the type of things like
16955      "p == 0" where "p" is a pointer can be determined.  */
16956   if (null_ptr_cst_p (expr))
16957     return expr;
16958   /* Preserve OVERLOADs; the functions must be available to resolve
16959      types.  */
16960   inner_expr = expr;
16961   if (TREE_CODE (inner_expr) == STMT_EXPR)
16962     inner_expr = stmt_expr_value_expr (inner_expr);
16963   if (TREE_CODE (inner_expr) == ADDR_EXPR)
16964     inner_expr = TREE_OPERAND (inner_expr, 0);
16965   if (TREE_CODE (inner_expr) == COMPONENT_REF)
16966     inner_expr = TREE_OPERAND (inner_expr, 1);
16967   if (is_overloaded_fn (inner_expr)
16968       || TREE_CODE (inner_expr) == OFFSET_REF)
16969     return expr;
16970   /* There is no need to return a proxy for a variable.  */
16971   if (TREE_CODE (expr) == VAR_DECL)
16972     return expr;
16973   /* Preserve string constants; conversions from string constants to
16974      "char *" are allowed, even though normally a "const char *"
16975      cannot be used to initialize a "char *".  */
16976   if (TREE_CODE (expr) == STRING_CST)
16977     return expr;
16978   /* Preserve arithmetic constants, as an optimization -- there is no
16979      reason to create a new node.  */
16980   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
16981     return expr;
16982   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
16983      There is at least one place where we want to know that a
16984      particular expression is a throw-expression: when checking a ?:
16985      expression, there are special rules if the second or third
16986      argument is a throw-expression.  */
16987   if (TREE_CODE (expr) == THROW_EXPR)
16988     return expr;
16989
16990   if (TREE_CODE (expr) == COND_EXPR)
16991     return build3 (COND_EXPR,
16992                    TREE_TYPE (expr),
16993                    TREE_OPERAND (expr, 0),
16994                    (TREE_OPERAND (expr, 1)
16995                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
16996                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
16997                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
16998   if (TREE_CODE (expr) == COMPOUND_EXPR
16999       && !COMPOUND_EXPR_OVERLOADED (expr))
17000     return build2 (COMPOUND_EXPR,
17001                    TREE_TYPE (expr),
17002                    TREE_OPERAND (expr, 0),
17003                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17004
17005   /* If the type is unknown, it can't really be non-dependent */
17006   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17007
17008   /* Otherwise, build a NON_DEPENDENT_EXPR.
17009
17010      REFERENCE_TYPEs are not stripped for expressions in templates
17011      because doing so would play havoc with mangling.  Consider, for
17012      example:
17013
17014        template <typename T> void f<T& g>() { g(); }
17015
17016      In the body of "f", the expression for "g" will have
17017      REFERENCE_TYPE, even though the standard says that it should
17018      not.  The reason is that we must preserve the syntactic form of
17019      the expression so that mangling (say) "f<g>" inside the body of
17020      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17021      stripped here.  */
17022   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17023 }
17024
17025 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
17026    Return a new TREE_LIST with the various arguments replaced with
17027    equivalent non-dependent expressions.  */
17028
17029 tree
17030 build_non_dependent_args (tree args)
17031 {
17032   tree a;
17033   tree new_args;
17034
17035   new_args = NULL_TREE;
17036   for (a = args; a; a = TREE_CHAIN (a))
17037     new_args = tree_cons (NULL_TREE,
17038                           build_non_dependent_expr (TREE_VALUE (a)),
17039                           new_args);
17040   return nreverse (new_args);
17041 }
17042
17043 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17044    with a level one deeper than the actual template parms.  */
17045
17046 tree
17047 make_auto (void)
17048 {
17049   tree au;
17050
17051   /* ??? Is it worth caching this for multiple autos at the same level?  */
17052   au = cxx_make_type (TEMPLATE_TYPE_PARM);
17053   TYPE_NAME (au) = build_decl (TYPE_DECL, get_identifier ("auto"), au);
17054   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17055   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17056     (0, processing_template_decl + 1, processing_template_decl + 1,
17057      TYPE_NAME (au), NULL_TREE);
17058   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17059   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17060   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17061
17062   return au;
17063 }
17064
17065 /* Given type ARG, return std::initializer_list<ARG>.  */
17066
17067 static tree
17068 listify (tree arg)
17069 {
17070   tree std_init_list = namespace_binding
17071     (get_identifier ("initializer_list"), std_node);
17072   tree argvec;
17073   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17074     {    
17075       error ("deducing from brace-enclosed initializer list requires "
17076              "#include <initializer_list>");
17077       return error_mark_node;
17078     }
17079   argvec = make_tree_vec (1);
17080   TREE_VEC_ELT (argvec, 0) = arg;
17081   return lookup_template_class (std_init_list, argvec, NULL_TREE,
17082                                 NULL_TREE, 0, tf_warning_or_error);
17083 }
17084
17085 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17086
17087 static tree
17088 listify_autos (tree type, tree auto_node)
17089 {
17090   tree init_auto = listify (auto_node);
17091   tree argvec = make_tree_vec (1);
17092   TREE_VEC_ELT (argvec, 0) = init_auto;
17093   if (processing_template_decl)
17094     argvec = add_to_template_args (current_template_args (), argvec);
17095   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17096 }
17097
17098 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
17099    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
17100
17101 tree
17102 do_auto_deduction (tree type, tree init, tree auto_node)
17103 {
17104   tree parms, args, tparms, targs;
17105   int val;
17106
17107   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
17108      with either a new invented type template parameter U or, if the
17109      initializer is a braced-init-list (8.5.4), with
17110      std::initializer_list<U>.  */
17111   if (BRACE_ENCLOSED_INITIALIZER_P (init))
17112     type = listify_autos (type, auto_node);
17113
17114   parms = build_tree_list (NULL_TREE, type);
17115   args = build_tree_list (NULL_TREE, init);
17116   tparms = make_tree_vec (1);
17117   targs = make_tree_vec (1);
17118   TREE_VEC_ELT (tparms, 0)
17119     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
17120   val = type_unification_real (tparms, targs, parms, args, 0,
17121                                DEDUCE_CALL, LOOKUP_NORMAL);
17122   if (val > 0)
17123     {
17124       error ("unable to deduce %qT from %qE", type, init);
17125       return error_mark_node;
17126     }
17127
17128   if (processing_template_decl)
17129     targs = add_to_template_args (current_template_args (), targs);
17130   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
17131 }
17132
17133 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
17134    result.  */
17135
17136 tree
17137 splice_late_return_type (tree type, tree late_return_type)
17138 {
17139   tree argvec;
17140
17141   if (late_return_type == NULL_TREE)
17142     return type;
17143   argvec = make_tree_vec (1);
17144   TREE_VEC_ELT (argvec, 0) = late_return_type;
17145   if (processing_template_decl)
17146     argvec = add_to_template_args (current_template_args (), argvec);
17147   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17148 }
17149
17150 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
17151
17152 bool
17153 is_auto (const_tree type)
17154 {
17155   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17156       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
17157     return true;
17158   else
17159     return false;
17160 }
17161
17162 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
17163    appear as a type-specifier for the declaration in question, we don't
17164    have to look through the whole type.  */
17165
17166 tree
17167 type_uses_auto (tree type)
17168 {
17169   enum tree_code code;
17170   if (is_auto (type))
17171     return type;
17172
17173   code = TREE_CODE (type);
17174
17175   if (code == POINTER_TYPE || code == REFERENCE_TYPE
17176       || code == OFFSET_TYPE || code == FUNCTION_TYPE
17177       || code == METHOD_TYPE || code == ARRAY_TYPE)
17178     return type_uses_auto (TREE_TYPE (type));
17179
17180   if (TYPE_PTRMEMFUNC_P (type))
17181     return type_uses_auto (TREE_TYPE (TREE_TYPE
17182                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
17183
17184   return NULL_TREE;
17185 }
17186
17187 #include "gt-cp-pt.h"