Upgrade GCC from 4.4.2 to 4.4.5 on the vendor branch.
[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 (arg == NULL_TREE)
2784         return args;
2785       if (ARGUMENT_PACK_P (arg))
2786         {
2787           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2788           if (num_result_args < 0)
2789             num_result_args = in_arg + num_packed;
2790           else
2791             num_result_args += num_packed;
2792         }
2793       else
2794         {
2795           if (num_result_args >= 0)
2796             num_result_args++;
2797         }
2798     }
2799
2800   /* If no expansion is necessary, we're done.  */
2801   if (num_result_args < 0)
2802     return args;
2803
2804   /* Expand arguments.  */
2805   result_args = make_tree_vec (num_result_args);
2806   for (in_arg = 0; in_arg < nargs; ++in_arg)
2807     {
2808       tree arg = TREE_VEC_ELT (args, in_arg);
2809       if (ARGUMENT_PACK_P (arg))
2810         {
2811           tree packed = ARGUMENT_PACK_ARGS (arg);
2812           int i, num_packed = TREE_VEC_LENGTH (packed);
2813           for (i = 0; i < num_packed; ++i, ++out_arg)
2814             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2815         }
2816       else
2817         {
2818           TREE_VEC_ELT (result_args, out_arg) = arg;
2819           ++out_arg;
2820         }
2821     }
2822
2823   return result_args;
2824 }
2825
2826 /* Checks if DECL shadows a template parameter.
2827
2828    [temp.local]: A template-parameter shall not be redeclared within its
2829    scope (including nested scopes).
2830
2831    Emits an error and returns TRUE if the DECL shadows a parameter,
2832    returns FALSE otherwise.  */
2833
2834 bool
2835 check_template_shadow (tree decl)
2836 {
2837   tree olddecl;
2838
2839   /* If we're not in a template, we can't possibly shadow a template
2840      parameter.  */
2841   if (!current_template_parms)
2842     return true;
2843
2844   /* Figure out what we're shadowing.  */
2845   if (TREE_CODE (decl) == OVERLOAD)
2846     decl = OVL_CURRENT (decl);
2847   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2848
2849   /* If there's no previous binding for this name, we're not shadowing
2850      anything, let alone a template parameter.  */
2851   if (!olddecl)
2852     return true;
2853
2854   /* If we're not shadowing a template parameter, we're done.  Note
2855      that OLDDECL might be an OVERLOAD (or perhaps even an
2856      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2857      node.  */
2858   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2859     return true;
2860
2861   /* We check for decl != olddecl to avoid bogus errors for using a
2862      name inside a class.  We check TPFI to avoid duplicate errors for
2863      inline member templates.  */
2864   if (decl == olddecl
2865       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2866     return true;
2867
2868   error ("declaration of %q+#D", decl);
2869   error (" shadows template parm %q+#D", olddecl);
2870   return false;
2871 }
2872
2873 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2874    ORIG_LEVEL, DECL, and TYPE.  */
2875
2876 static tree
2877 build_template_parm_index (int index,
2878                            int level,
2879                            int orig_level,
2880                            tree decl,
2881                            tree type)
2882 {
2883   tree t = make_node (TEMPLATE_PARM_INDEX);
2884   TEMPLATE_PARM_IDX (t) = index;
2885   TEMPLATE_PARM_LEVEL (t) = level;
2886   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2887   TEMPLATE_PARM_DECL (t) = decl;
2888   TREE_TYPE (t) = type;
2889   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2890   TREE_READONLY (t) = TREE_READONLY (decl);
2891
2892   return t;
2893 }
2894
2895 /* Find the canonical type parameter for the given template type
2896    parameter.  Returns the canonical type parameter, which may be TYPE
2897    if no such parameter existed.  */
2898 static tree
2899 canonical_type_parameter (tree type)
2900 {
2901   tree list;
2902   int idx = TEMPLATE_TYPE_IDX (type);
2903   if (!canonical_template_parms)
2904     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2905
2906   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2907     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2908
2909   list = VEC_index (tree, canonical_template_parms, idx);
2910   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2911     list = TREE_CHAIN (list);
2912
2913   if (list)
2914     return TREE_VALUE (list);
2915   else
2916     {
2917       VEC_replace(tree, canonical_template_parms, idx,
2918                   tree_cons (NULL_TREE, type, 
2919                              VEC_index (tree, canonical_template_parms, idx)));
2920       return type;
2921     }
2922 }
2923
2924 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2925    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2926    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2927    new one is created.  */
2928
2929 static tree
2930 reduce_template_parm_level (tree index, tree type, int levels, tree args,
2931                             tsubst_flags_t complain)
2932 {
2933   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2934       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2935           != TEMPLATE_PARM_LEVEL (index) - levels))
2936     {
2937       tree orig_decl = TEMPLATE_PARM_DECL (index);
2938       tree decl, t;
2939
2940       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2941       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2942       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2943       DECL_ARTIFICIAL (decl) = 1;
2944       SET_DECL_TEMPLATE_PARM_P (decl);
2945
2946       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2947                                      TEMPLATE_PARM_LEVEL (index) - levels,
2948                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2949                                      decl, type);
2950       TEMPLATE_PARM_DESCENDANTS (index) = t;
2951       TEMPLATE_PARM_PARAMETER_PACK (t) 
2952         = TEMPLATE_PARM_PARAMETER_PACK (index);
2953
2954         /* Template template parameters need this.  */
2955       if (TREE_CODE (decl) == TEMPLATE_DECL)
2956         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
2957           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
2958            args, complain);
2959     }
2960
2961   return TEMPLATE_PARM_DESCENDANTS (index);
2962 }
2963
2964 /* Process information from new template parameter PARM and append it to the
2965    LIST being built.  This new parameter is a non-type parameter iff
2966    IS_NON_TYPE is true. This new parameter is a parameter
2967    pack iff IS_PARAMETER_PACK is true.  */
2968
2969 tree
2970 process_template_parm (tree list, tree parm, bool is_non_type, 
2971                        bool is_parameter_pack)
2972 {
2973   tree decl = 0;
2974   tree defval;
2975   tree err_parm_list;
2976   int idx = 0;
2977
2978   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2979   defval = TREE_PURPOSE (parm);
2980
2981   if (list)
2982     {
2983       tree p = tree_last (list);
2984
2985       if (p && TREE_VALUE (p) != error_mark_node)
2986         {
2987           p = TREE_VALUE (p);
2988           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2989             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2990           else
2991             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2992         }
2993
2994       ++idx;
2995     }
2996   else
2997     idx = 0;
2998
2999   if (is_non_type)
3000     {
3001       parm = TREE_VALUE (parm);
3002
3003       SET_DECL_TEMPLATE_PARM_P (parm);
3004
3005       if (TREE_TYPE (parm) == error_mark_node)
3006         {
3007           err_parm_list = build_tree_list (defval, parm);
3008           TREE_VALUE (err_parm_list) = error_mark_node;
3009            return chainon (list, err_parm_list);
3010         }
3011       else
3012       {
3013         /* [temp.param]
3014
3015            The top-level cv-qualifiers on the template-parameter are
3016            ignored when determining its type.  */
3017         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3018         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3019           {
3020             err_parm_list = build_tree_list (defval, parm);
3021             TREE_VALUE (err_parm_list) = error_mark_node;
3022              return chainon (list, err_parm_list);
3023           }
3024
3025         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3026           {
3027             /* This template parameter is not a parameter pack, but it
3028                should be. Complain about "bare" parameter packs.  */
3029             check_for_bare_parameter_packs (TREE_TYPE (parm));
3030             
3031             /* Recover by calling this a parameter pack.  */
3032             is_parameter_pack = true;
3033           }
3034       }
3035
3036       /* A template parameter is not modifiable.  */
3037       TREE_CONSTANT (parm) = 1;
3038       TREE_READONLY (parm) = 1;
3039       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3040       TREE_CONSTANT (decl) = 1;
3041       TREE_READONLY (decl) = 1;
3042       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3043         = build_template_parm_index (idx, processing_template_decl,
3044                                      processing_template_decl,
3045                                      decl, TREE_TYPE (parm));
3046
3047       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3048         = is_parameter_pack;
3049     }
3050   else
3051     {
3052       tree t;
3053       parm = TREE_VALUE (TREE_VALUE (parm));
3054
3055       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3056         {
3057           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3058           /* This is for distinguishing between real templates and template
3059              template parameters */
3060           TREE_TYPE (parm) = t;
3061           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3062           decl = parm;
3063         }
3064       else
3065         {
3066           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3067           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3068           decl = build_decl (TYPE_DECL, parm, t);
3069         }
3070
3071       TYPE_NAME (t) = decl;
3072       TYPE_STUB_DECL (t) = decl;
3073       parm = decl;
3074       TEMPLATE_TYPE_PARM_INDEX (t)
3075         = build_template_parm_index (idx, processing_template_decl,
3076                                      processing_template_decl,
3077                                      decl, TREE_TYPE (parm));
3078       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3079       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3080     }
3081   DECL_ARTIFICIAL (decl) = 1;
3082   SET_DECL_TEMPLATE_PARM_P (decl);
3083   pushdecl (decl);
3084   parm = build_tree_list (defval, parm);
3085   return chainon (list, parm);
3086 }
3087
3088 /* The end of a template parameter list has been reached.  Process the
3089    tree list into a parameter vector, converting each parameter into a more
3090    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3091    as PARM_DECLs.  */
3092
3093 tree
3094 end_template_parm_list (tree parms)
3095 {
3096   int nparms;
3097   tree parm, next;
3098   tree saved_parmlist = make_tree_vec (list_length (parms));
3099
3100   current_template_parms
3101     = tree_cons (size_int (processing_template_decl),
3102                  saved_parmlist, current_template_parms);
3103
3104   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3105     {
3106       next = TREE_CHAIN (parm);
3107       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3108       TREE_CHAIN (parm) = NULL_TREE;
3109     }
3110
3111   --processing_template_parmlist;
3112
3113   return saved_parmlist;
3114 }
3115
3116 /* end_template_decl is called after a template declaration is seen.  */
3117
3118 void
3119 end_template_decl (void)
3120 {
3121   reset_specialization ();
3122
3123   if (! processing_template_decl)
3124     return;
3125
3126   /* This matches the pushlevel in begin_template_parm_list.  */
3127   finish_scope ();
3128
3129   --processing_template_decl;
3130   current_template_parms = TREE_CHAIN (current_template_parms);
3131 }
3132
3133 /* Within the declaration of a template, return all levels of template
3134    parameters that apply.  The template parameters are represented as
3135    a TREE_VEC, in the form documented in cp-tree.h for template
3136    arguments.  */
3137
3138 static tree
3139 current_template_args (void)
3140 {
3141   tree header;
3142   tree args = NULL_TREE;
3143   int length = TMPL_PARMS_DEPTH (current_template_parms);
3144   int l = length;
3145
3146   /* If there is only one level of template parameters, we do not
3147      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3148      TREE_VEC containing the arguments.  */
3149   if (length > 1)
3150     args = make_tree_vec (length);
3151
3152   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3153     {
3154       tree a = copy_node (TREE_VALUE (header));
3155       int i;
3156
3157       TREE_TYPE (a) = NULL_TREE;
3158       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3159         {
3160           tree t = TREE_VEC_ELT (a, i);
3161
3162           /* T will be a list if we are called from within a
3163              begin/end_template_parm_list pair, but a vector directly
3164              if within a begin/end_member_template_processing pair.  */
3165           if (TREE_CODE (t) == TREE_LIST)
3166             {
3167               t = TREE_VALUE (t);
3168
3169               if (!error_operand_p (t))
3170                 {
3171                   if (TREE_CODE (t) == TYPE_DECL
3172                       || TREE_CODE (t) == TEMPLATE_DECL)
3173                     {
3174                       t = TREE_TYPE (t);
3175                       
3176                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3177                         {
3178                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3179                              with a single element, which expands T.  */
3180                           tree vec = make_tree_vec (1);
3181                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3182                           
3183                           t = make_node (TYPE_ARGUMENT_PACK);
3184                           SET_ARGUMENT_PACK_ARGS (t, vec);
3185                         }
3186                     }
3187                   else
3188                     {
3189                       t = DECL_INITIAL (t);
3190                       
3191                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3192                         {
3193                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3194                              with a single element, which expands T.  */
3195                           tree vec = make_tree_vec (1);
3196                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3197                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3198                           
3199                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3200                           SET_ARGUMENT_PACK_ARGS (t, vec);
3201                           TREE_TYPE (t) = type;
3202                         }
3203                     }
3204                   TREE_VEC_ELT (a, i) = t;
3205                 }
3206             }
3207         }
3208
3209       if (length > 1)
3210         TREE_VEC_ELT (args, --l) = a;
3211       else
3212         args = a;
3213     }
3214
3215   return args;
3216 }
3217
3218 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3219    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3220    a member template.  Used by push_template_decl below.  */
3221
3222 static tree
3223 build_template_decl (tree decl, tree parms, bool member_template_p)
3224 {
3225   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3226   DECL_TEMPLATE_PARMS (tmpl) = parms;
3227   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3228   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3229   if (DECL_LANG_SPECIFIC (decl))
3230     {
3231       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3232       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3233       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3234       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3235       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3236       if (DECL_OVERLOADED_OPERATOR_P (decl))
3237         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3238                                       DECL_OVERLOADED_OPERATOR_P (decl));
3239     }
3240
3241   return tmpl;
3242 }
3243
3244 struct template_parm_data
3245 {
3246   /* The level of the template parameters we are currently
3247      processing.  */
3248   int level;
3249
3250   /* The index of the specialization argument we are currently
3251      processing.  */
3252   int current_arg;
3253
3254   /* An array whose size is the number of template parameters.  The
3255      elements are nonzero if the parameter has been used in any one
3256      of the arguments processed so far.  */
3257   int* parms;
3258
3259   /* An array whose size is the number of template arguments.  The
3260      elements are nonzero if the argument makes use of template
3261      parameters of this level.  */
3262   int* arg_uses_template_parms;
3263 };
3264
3265 /* Subroutine of push_template_decl used to see if each template
3266    parameter in a partial specialization is used in the explicit
3267    argument list.  If T is of the LEVEL given in DATA (which is
3268    treated as a template_parm_data*), then DATA->PARMS is marked
3269    appropriately.  */
3270
3271 static int
3272 mark_template_parm (tree t, void* data)
3273 {
3274   int level;
3275   int idx;
3276   struct template_parm_data* tpd = (struct template_parm_data*) data;
3277
3278   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3279     {
3280       level = TEMPLATE_PARM_LEVEL (t);
3281       idx = TEMPLATE_PARM_IDX (t);
3282     }
3283   else
3284     {
3285       level = TEMPLATE_TYPE_LEVEL (t);
3286       idx = TEMPLATE_TYPE_IDX (t);
3287     }
3288
3289   if (level == tpd->level)
3290     {
3291       tpd->parms[idx] = 1;
3292       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3293     }
3294
3295   /* Return zero so that for_each_template_parm will continue the
3296      traversal of the tree; we want to mark *every* template parm.  */
3297   return 0;
3298 }
3299
3300 /* Process the partial specialization DECL.  */
3301
3302 static tree
3303 process_partial_specialization (tree decl)
3304 {
3305   tree type = TREE_TYPE (decl);
3306   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3307   tree specargs = CLASSTYPE_TI_ARGS (type);
3308   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3309   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3310   tree inner_parms;
3311   int nargs = TREE_VEC_LENGTH (inner_args);
3312   int ntparms;
3313   int  i;
3314   int did_error_intro = 0;
3315   struct template_parm_data tpd;
3316   struct template_parm_data tpd2;
3317
3318   gcc_assert (current_template_parms);
3319
3320   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3321   ntparms = TREE_VEC_LENGTH (inner_parms);
3322
3323   /* We check that each of the template parameters given in the
3324      partial specialization is used in the argument list to the
3325      specialization.  For example:
3326
3327        template <class T> struct S;
3328        template <class T> struct S<T*>;
3329
3330      The second declaration is OK because `T*' uses the template
3331      parameter T, whereas
3332
3333        template <class T> struct S<int>;
3334
3335      is no good.  Even trickier is:
3336
3337        template <class T>
3338        struct S1
3339        {
3340           template <class U>
3341           struct S2;
3342           template <class U>
3343           struct S2<T>;
3344        };
3345
3346      The S2<T> declaration is actually invalid; it is a
3347      full-specialization.  Of course,
3348
3349           template <class U>
3350           struct S2<T (*)(U)>;
3351
3352      or some such would have been OK.  */
3353   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3354   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3355   memset (tpd.parms, 0, sizeof (int) * ntparms);
3356
3357   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3358   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3359   for (i = 0; i < nargs; ++i)
3360     {
3361       tpd.current_arg = i;
3362       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3363                               &mark_template_parm,
3364                               &tpd,
3365                               NULL,
3366                               /*include_nondeduced_p=*/false);
3367     }
3368   for (i = 0; i < ntparms; ++i)
3369     if (tpd.parms[i] == 0)
3370       {
3371         /* One of the template parms was not used in the
3372            specialization.  */
3373         if (!did_error_intro)
3374           {
3375             error ("template parameters not used in partial specialization:");
3376             did_error_intro = 1;
3377           }
3378
3379         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3380       }
3381
3382   /* [temp.class.spec]
3383
3384      The argument list of the specialization shall not be identical to
3385      the implicit argument list of the primary template.  */
3386   if (comp_template_args
3387       (inner_args,
3388        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3389                                                    (maintmpl)))))
3390     error ("partial specialization %qT does not specialize any template arguments", type);
3391
3392   /* [temp.class.spec]
3393
3394      A partially specialized non-type argument expression shall not
3395      involve template parameters of the partial specialization except
3396      when the argument expression is a simple identifier.
3397
3398      The type of a template parameter corresponding to a specialized
3399      non-type argument shall not be dependent on a parameter of the
3400      specialization. 
3401
3402      Also, we verify that pack expansions only occur at the
3403      end of the argument list.  */
3404   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3405   tpd2.parms = 0;
3406   for (i = 0; i < nargs; ++i)
3407     {
3408       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3409       tree arg = TREE_VEC_ELT (inner_args, i);
3410       tree packed_args = NULL_TREE;
3411       int j, len = 1;
3412
3413       if (ARGUMENT_PACK_P (arg))
3414         {
3415           /* Extract the arguments from the argument pack. We'll be
3416              iterating over these in the following loop.  */
3417           packed_args = ARGUMENT_PACK_ARGS (arg);
3418           len = TREE_VEC_LENGTH (packed_args);
3419         }
3420
3421       for (j = 0; j < len; j++)
3422         {
3423           if (packed_args)
3424             /* Get the Jth argument in the parameter pack.  */
3425             arg = TREE_VEC_ELT (packed_args, j);
3426
3427           if (PACK_EXPANSION_P (arg))
3428             {
3429               /* Pack expansions must come at the end of the
3430                  argument list.  */
3431               if ((packed_args && j < len - 1)
3432                   || (!packed_args && i < nargs - 1))
3433                 {
3434                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3435                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3436                   else
3437                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3438
3439                   if (packed_args)
3440                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3441                 }
3442             }
3443
3444           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3445             /* We only care about the pattern.  */
3446             arg = PACK_EXPANSION_PATTERN (arg);
3447
3448           if (/* These first two lines are the `non-type' bit.  */
3449               !TYPE_P (arg)
3450               && TREE_CODE (arg) != TEMPLATE_DECL
3451               /* This next line is the `argument expression is not just a
3452                  simple identifier' condition and also the `specialized
3453                  non-type argument' bit.  */
3454               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3455             {
3456               if ((!packed_args && tpd.arg_uses_template_parms[i])
3457                   || (packed_args && uses_template_parms (arg)))
3458                 error ("template argument %qE involves template parameter(s)",
3459                        arg);
3460               else 
3461                 {
3462                   /* Look at the corresponding template parameter,
3463                      marking which template parameters its type depends
3464                      upon.  */
3465                   tree type = TREE_TYPE (parm);
3466
3467                   if (!tpd2.parms)
3468                     {
3469                       /* We haven't yet initialized TPD2.  Do so now.  */
3470                       tpd2.arg_uses_template_parms 
3471                         = (int *) alloca (sizeof (int) * nargs);
3472                       /* The number of parameters here is the number in the
3473                          main template, which, as checked in the assertion
3474                          above, is NARGS.  */
3475                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3476                       tpd2.level = 
3477                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3478                     }
3479
3480                   /* Mark the template parameters.  But this time, we're
3481                      looking for the template parameters of the main
3482                      template, not in the specialization.  */
3483                   tpd2.current_arg = i;
3484                   tpd2.arg_uses_template_parms[i] = 0;
3485                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3486                   for_each_template_parm (type,
3487                                           &mark_template_parm,
3488                                           &tpd2,
3489                                           NULL,
3490                                           /*include_nondeduced_p=*/false);
3491
3492                   if (tpd2.arg_uses_template_parms [i])
3493                     {
3494                       /* The type depended on some template parameters.
3495                          If they are fully specialized in the
3496                          specialization, that's OK.  */
3497                       int j;
3498                       for (j = 0; j < nargs; ++j)
3499                         if (tpd2.parms[j] != 0
3500                             && tpd.arg_uses_template_parms [j])
3501                           {
3502                             error ("type %qT of template argument %qE depends "
3503                                    "on template parameter(s)", 
3504                                    type,
3505                                    arg);
3506                             break;
3507                           }
3508                     }
3509                 }
3510             }
3511         }
3512     }
3513
3514   if (retrieve_specialization (maintmpl, specargs,
3515                                /*class_specializations_p=*/true))
3516     /* We've already got this specialization.  */
3517     return decl;
3518
3519   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3520     = tree_cons (specargs, inner_parms,
3521                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3522   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3523   return decl;
3524 }
3525
3526 /* Check that a template declaration's use of default arguments and
3527    parameter packs is not invalid.  Here, PARMS are the template
3528    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3529    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3530    specialization.
3531    
3532
3533    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3534    declaration (but not a definition); 1 indicates a declaration, 2
3535    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3536    emitted for extraneous default arguments.
3537
3538    Returns TRUE if there were no errors found, FALSE otherwise. */
3539
3540 bool
3541 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3542                          int is_partial, int is_friend_decl)
3543 {
3544   const char *msg;
3545   int last_level_to_check;
3546   tree parm_level;
3547   bool no_errors = true;
3548
3549   /* [temp.param]
3550
3551      A default template-argument shall not be specified in a
3552      function template declaration or a function template definition, nor
3553      in the template-parameter-list of the definition of a member of a
3554      class template.  */
3555
3556   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3557     /* You can't have a function template declaration in a local
3558        scope, nor you can you define a member of a class template in a
3559        local scope.  */
3560     return true;
3561
3562   if (current_class_type
3563       && !TYPE_BEING_DEFINED (current_class_type)
3564       && DECL_LANG_SPECIFIC (decl)
3565       /* If this is either a friend defined in the scope of the class
3566          or a member function.  */
3567       && (DECL_FUNCTION_MEMBER_P (decl)
3568           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3569           : DECL_FRIEND_CONTEXT (decl)
3570           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3571           : false)
3572       /* And, if it was a member function, it really was defined in
3573          the scope of the class.  */
3574       && (!DECL_FUNCTION_MEMBER_P (decl)
3575           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3576     /* We already checked these parameters when the template was
3577        declared, so there's no need to do it again now.  This function
3578        was defined in class scope, but we're processing it's body now
3579        that the class is complete.  */
3580     return true;
3581
3582   /* Core issue 226 (C++0x only): the following only applies to class
3583      templates.  */
3584   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3585     {
3586       /* [temp.param]
3587
3588          If a template-parameter has a default template-argument, all
3589          subsequent template-parameters shall have a default
3590          template-argument supplied.  */
3591       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3592         {
3593           tree inner_parms = TREE_VALUE (parm_level);
3594           int ntparms = TREE_VEC_LENGTH (inner_parms);
3595           int seen_def_arg_p = 0;
3596           int i;
3597
3598           for (i = 0; i < ntparms; ++i)
3599             {
3600               tree parm = TREE_VEC_ELT (inner_parms, i);
3601
3602               if (parm == error_mark_node)
3603                 continue;
3604
3605               if (TREE_PURPOSE (parm))
3606                 seen_def_arg_p = 1;
3607               else if (seen_def_arg_p
3608                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3609                 {
3610                   error ("no default argument for %qD", TREE_VALUE (parm));
3611                   /* For better subsequent error-recovery, we indicate that
3612                      there should have been a default argument.  */
3613                   TREE_PURPOSE (parm) = error_mark_node;
3614                   no_errors = false;
3615                 }
3616               else if (is_primary
3617                        && !is_partial
3618                        && !is_friend_decl
3619                        /* Don't complain about an enclosing partial
3620                           specialization.  */
3621                        && parm_level == parms
3622                        && TREE_CODE (decl) == TYPE_DECL
3623                        && i < ntparms - 1
3624                        && template_parameter_pack_p (TREE_VALUE (parm)))
3625                 {
3626                   /* A primary class template can only have one
3627                      parameter pack, at the end of the template
3628                      parameter list.  */
3629
3630                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3631                     error ("parameter pack %qE must be at the end of the"
3632                            " template parameter list", TREE_VALUE (parm));
3633                   else
3634                     error ("parameter pack %qT must be at the end of the"
3635                            " template parameter list", 
3636                            TREE_TYPE (TREE_VALUE (parm)));
3637
3638                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3639                     = error_mark_node;
3640                   no_errors = false;
3641                 }
3642             }
3643         }
3644     }
3645
3646   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3647       || is_partial 
3648       || !is_primary
3649       || is_friend_decl)
3650     /* For an ordinary class template, default template arguments are
3651        allowed at the innermost level, e.g.:
3652          template <class T = int>
3653          struct S {};
3654        but, in a partial specialization, they're not allowed even
3655        there, as we have in [temp.class.spec]:
3656
3657          The template parameter list of a specialization shall not
3658          contain default template argument values.
3659
3660        So, for a partial specialization, or for a function template
3661        (in C++98/C++03), we look at all of them.  */
3662     ;
3663   else
3664     /* But, for a primary class template that is not a partial
3665        specialization we look at all template parameters except the
3666        innermost ones.  */
3667     parms = TREE_CHAIN (parms);
3668
3669   /* Figure out what error message to issue.  */
3670   if (is_friend_decl == 2)
3671     msg = "default template arguments may not be used in function template friend re-declaration";
3672   else if (is_friend_decl)
3673     msg = "default template arguments may not be used in function template friend declarations";
3674   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3675     msg = ("default template arguments may not be used in function templates "
3676            "without -std=c++0x or -std=gnu++0x");
3677   else if (is_partial)
3678     msg = "default template arguments may not be used in partial specializations";
3679   else
3680     msg = "default argument for template parameter for class enclosing %qD";
3681
3682   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3683     /* If we're inside a class definition, there's no need to
3684        examine the parameters to the class itself.  On the one
3685        hand, they will be checked when the class is defined, and,
3686        on the other, default arguments are valid in things like:
3687          template <class T = double>
3688          struct S { template <class U> void f(U); };
3689        Here the default argument for `S' has no bearing on the
3690        declaration of `f'.  */
3691     last_level_to_check = template_class_depth (current_class_type) + 1;
3692   else
3693     /* Check everything.  */
3694     last_level_to_check = 0;
3695
3696   for (parm_level = parms;
3697        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3698        parm_level = TREE_CHAIN (parm_level))
3699     {
3700       tree inner_parms = TREE_VALUE (parm_level);
3701       int i;
3702       int ntparms;
3703
3704       ntparms = TREE_VEC_LENGTH (inner_parms);
3705       for (i = 0; i < ntparms; ++i)
3706         {
3707           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3708             continue;
3709
3710           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3711             {
3712               if (msg)
3713                 {
3714                   no_errors = false;
3715                   if (is_friend_decl == 2)
3716                     return no_errors;
3717
3718                   error (msg, decl);
3719                   msg = 0;
3720                 }
3721
3722               /* Clear out the default argument so that we are not
3723                  confused later.  */
3724               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3725             }
3726         }
3727
3728       /* At this point, if we're still interested in issuing messages,
3729          they must apply to classes surrounding the object declared.  */
3730       if (msg)
3731         msg = "default argument for template parameter for class enclosing %qD";
3732     }
3733
3734   return no_errors;
3735 }
3736
3737 /* Worker for push_template_decl_real, called via
3738    for_each_template_parm.  DATA is really an int, indicating the
3739    level of the parameters we are interested in.  If T is a template
3740    parameter of that level, return nonzero.  */
3741
3742 static int
3743 template_parm_this_level_p (tree t, void* data)
3744 {
3745   int this_level = *(int *)data;
3746   int level;
3747
3748   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3749     level = TEMPLATE_PARM_LEVEL (t);
3750   else
3751     level = TEMPLATE_TYPE_LEVEL (t);
3752   return level == this_level;
3753 }
3754
3755 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3756    parameters given by current_template_args, or reuses a
3757    previously existing one, if appropriate.  Returns the DECL, or an
3758    equivalent one, if it is replaced via a call to duplicate_decls.
3759
3760    If IS_FRIEND is true, DECL is a friend declaration.  */
3761
3762 tree
3763 push_template_decl_real (tree decl, bool is_friend)
3764 {
3765   tree tmpl;
3766   tree args;
3767   tree info;
3768   tree ctx;
3769   int primary;
3770   int is_partial;
3771   int new_template_p = 0;
3772   /* True if the template is a member template, in the sense of
3773      [temp.mem].  */
3774   bool member_template_p = false;
3775
3776   if (decl == error_mark_node || !current_template_parms)
3777     return error_mark_node;
3778
3779   /* See if this is a partial specialization.  */
3780   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3781                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3782                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3783
3784   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3785     is_friend = true;
3786
3787   if (is_friend)
3788     /* For a friend, we want the context of the friend function, not
3789        the type of which it is a friend.  */
3790     ctx = DECL_CONTEXT (decl);
3791   else if (CP_DECL_CONTEXT (decl)
3792            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3793     /* In the case of a virtual function, we want the class in which
3794        it is defined.  */
3795     ctx = CP_DECL_CONTEXT (decl);
3796   else
3797     /* Otherwise, if we're currently defining some class, the DECL
3798        is assumed to be a member of the class.  */
3799     ctx = current_scope ();
3800
3801   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3802     ctx = NULL_TREE;
3803
3804   if (!DECL_CONTEXT (decl))
3805     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3806
3807   /* See if this is a primary template.  */
3808   if (is_friend && ctx)
3809     /* A friend template that specifies a class context, i.e.
3810          template <typename T> friend void A<T>::f();
3811        is not primary.  */
3812     primary = 0;
3813   else
3814     primary = template_parm_scope_p ();
3815
3816   if (primary)
3817     {
3818       if (DECL_CLASS_SCOPE_P (decl))
3819         member_template_p = true;
3820       if (TREE_CODE (decl) == TYPE_DECL
3821           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3822         {
3823           error ("template class without a name");
3824           return error_mark_node;
3825         }
3826       else if (TREE_CODE (decl) == FUNCTION_DECL)
3827         {
3828           if (DECL_DESTRUCTOR_P (decl))
3829             {
3830               /* [temp.mem]
3831
3832                  A destructor shall not be a member template.  */
3833               error ("destructor %qD declared as member template", decl);
3834               return error_mark_node;
3835             }
3836           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3837               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3838                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3839                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3840                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3841                       == void_list_node)))
3842             {
3843               /* [basic.stc.dynamic.allocation]
3844
3845                  An allocation function can be a function
3846                  template. ... Template allocation functions shall
3847                  have two or more parameters.  */
3848               error ("invalid template declaration of %qD", decl);
3849               return error_mark_node;
3850             }
3851         }
3852       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3853                && CLASS_TYPE_P (TREE_TYPE (decl)))
3854         /* OK */;
3855       else
3856         {
3857           error ("template declaration of %q#D", decl);
3858           return error_mark_node;
3859         }
3860     }
3861
3862   /* Check to see that the rules regarding the use of default
3863      arguments are not being violated.  */
3864   check_default_tmpl_args (decl, current_template_parms,
3865                            primary, is_partial, /*is_friend_decl=*/0);
3866
3867   /* Ensure that there are no parameter packs in the type of this
3868      declaration that have not been expanded.  */
3869   if (TREE_CODE (decl) == FUNCTION_DECL)
3870     {
3871       /* Check each of the arguments individually to see if there are
3872          any bare parameter packs.  */
3873       tree type = TREE_TYPE (decl);
3874       tree arg = DECL_ARGUMENTS (decl);
3875       tree argtype = TYPE_ARG_TYPES (type);
3876
3877       while (arg && argtype)
3878         {
3879           if (!FUNCTION_PARAMETER_PACK_P (arg)
3880               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
3881             {
3882             /* This is a PARM_DECL that contains unexpanded parameter
3883                packs. We have already complained about this in the
3884                check_for_bare_parameter_packs call, so just replace
3885                these types with ERROR_MARK_NODE.  */
3886               TREE_TYPE (arg) = error_mark_node;
3887               TREE_VALUE (argtype) = error_mark_node;
3888             }
3889
3890           arg = TREE_CHAIN (arg);
3891           argtype = TREE_CHAIN (argtype);
3892         }
3893
3894       /* Check for bare parameter packs in the return type and the
3895          exception specifiers.  */
3896       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
3897         /* Errors were already issued, set return type to int
3898            as the frontend doesn't expect error_mark_node as
3899            the return type.  */
3900         TREE_TYPE (type) = integer_type_node;
3901       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
3902         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
3903     }
3904   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
3905     {
3906       TREE_TYPE (decl) = error_mark_node;
3907       return error_mark_node;
3908     }
3909
3910   if (is_partial)
3911     return process_partial_specialization (decl);
3912
3913   args = current_template_args ();
3914
3915   if (!ctx
3916       || TREE_CODE (ctx) == FUNCTION_DECL
3917       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3918       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3919     {
3920       if (DECL_LANG_SPECIFIC (decl)
3921           && DECL_TEMPLATE_INFO (decl)
3922           && DECL_TI_TEMPLATE (decl))
3923         tmpl = DECL_TI_TEMPLATE (decl);
3924       /* If DECL is a TYPE_DECL for a class-template, then there won't
3925          be DECL_LANG_SPECIFIC.  The information equivalent to
3926          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3927       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3928                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3929                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3930         {
3931           /* Since a template declaration already existed for this
3932              class-type, we must be redeclaring it here.  Make sure
3933              that the redeclaration is valid.  */
3934           redeclare_class_template (TREE_TYPE (decl),
3935                                     current_template_parms);
3936           /* We don't need to create a new TEMPLATE_DECL; just use the
3937              one we already had.  */
3938           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3939         }
3940       else
3941         {
3942           tmpl = build_template_decl (decl, current_template_parms,
3943                                       member_template_p);
3944           new_template_p = 1;
3945
3946           if (DECL_LANG_SPECIFIC (decl)
3947               && DECL_TEMPLATE_SPECIALIZATION (decl))
3948             {
3949               /* A specialization of a member template of a template
3950                  class.  */
3951               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3952               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3953               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3954             }
3955         }
3956     }
3957   else
3958     {
3959       tree a, t, current, parms;
3960       int i;
3961       tree tinfo = get_template_info (decl);
3962
3963       if (!tinfo)
3964         {
3965           error ("template definition of non-template %q#D", decl);
3966           return error_mark_node;
3967         }
3968
3969       tmpl = TI_TEMPLATE (tinfo);
3970
3971       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3972           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3973           && DECL_TEMPLATE_SPECIALIZATION (decl)
3974           && DECL_MEMBER_TEMPLATE_P (tmpl))
3975         {
3976           tree new_tmpl;
3977
3978           /* The declaration is a specialization of a member
3979              template, declared outside the class.  Therefore, the
3980              innermost template arguments will be NULL, so we
3981              replace them with the arguments determined by the
3982              earlier call to check_explicit_specialization.  */
3983           args = DECL_TI_ARGS (decl);
3984
3985           new_tmpl
3986             = build_template_decl (decl, current_template_parms,
3987                                    member_template_p);
3988           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3989           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3990           DECL_TI_TEMPLATE (decl) = new_tmpl;
3991           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3992           DECL_TEMPLATE_INFO (new_tmpl)
3993             = tree_cons (tmpl, args, NULL_TREE);
3994
3995           register_specialization (new_tmpl,
3996                                    most_general_template (tmpl),
3997                                    args,
3998                                    is_friend);
3999           return decl;
4000         }
4001
4002       /* Make sure the template headers we got make sense.  */
4003
4004       parms = DECL_TEMPLATE_PARMS (tmpl);
4005       i = TMPL_PARMS_DEPTH (parms);
4006       if (TMPL_ARGS_DEPTH (args) != i)
4007         {
4008           error ("expected %d levels of template parms for %q#D, got %d",
4009                  i, decl, TMPL_ARGS_DEPTH (args));
4010         }
4011       else
4012         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4013           {
4014             a = TMPL_ARGS_LEVEL (args, i);
4015             t = INNERMOST_TEMPLATE_PARMS (parms);
4016
4017             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4018               {
4019                 if (current == decl)
4020                   error ("got %d template parameters for %q#D",
4021                          TREE_VEC_LENGTH (a), decl);
4022                 else
4023                   error ("got %d template parameters for %q#T",
4024                          TREE_VEC_LENGTH (a), current);
4025                 error ("  but %d required", TREE_VEC_LENGTH (t));
4026                 return error_mark_node;
4027               }
4028
4029             if (current == decl)
4030               current = ctx;
4031             else
4032               current = (TYPE_P (current)
4033                          ? TYPE_CONTEXT (current)
4034                          : DECL_CONTEXT (current));
4035           }
4036
4037       /* Check that the parms are used in the appropriate qualifying scopes
4038          in the declarator.  */
4039       if (!comp_template_args
4040           (TI_ARGS (tinfo),
4041            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4042         {
4043           error ("\
4044 template arguments to %qD do not match original template %qD",
4045                  decl, DECL_TEMPLATE_RESULT (tmpl));
4046           if (!uses_template_parms (TI_ARGS (tinfo)))
4047             inform (input_location, "use template<> for an explicit specialization");
4048           /* Avoid crash in import_export_decl.  */
4049           DECL_INTERFACE_KNOWN (decl) = 1;
4050           return error_mark_node;
4051         }
4052     }
4053
4054   DECL_TEMPLATE_RESULT (tmpl) = decl;
4055   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4056
4057   /* Push template declarations for global functions and types.  Note
4058      that we do not try to push a global template friend declared in a
4059      template class; such a thing may well depend on the template
4060      parameters of the class.  */
4061   if (new_template_p && !ctx
4062       && !(is_friend && template_class_depth (current_class_type) > 0))
4063     {
4064       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4065       if (tmpl == error_mark_node)
4066         return error_mark_node;
4067
4068       /* Hide template friend classes that haven't been declared yet.  */
4069       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4070         {
4071           DECL_ANTICIPATED (tmpl) = 1;
4072           DECL_FRIEND_P (tmpl) = 1;
4073         }
4074     }
4075
4076   if (primary)
4077     {
4078       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4079       int i;
4080
4081       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4082       if (DECL_CONV_FN_P (tmpl))
4083         {
4084           int depth = TMPL_PARMS_DEPTH (parms);
4085
4086           /* It is a conversion operator. See if the type converted to
4087              depends on innermost template operands.  */
4088
4089           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4090                                          depth))
4091             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4092         }
4093
4094       /* Give template template parms a DECL_CONTEXT of the template
4095          for which they are a parameter.  */
4096       parms = INNERMOST_TEMPLATE_PARMS (parms);
4097       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4098         {
4099           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4100           if (TREE_CODE (parm) == TEMPLATE_DECL)
4101             DECL_CONTEXT (parm) = tmpl;
4102         }
4103     }
4104
4105   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4106      back to its most general template.  If TMPL is a specialization,
4107      ARGS may only have the innermost set of arguments.  Add the missing
4108      argument levels if necessary.  */
4109   if (DECL_TEMPLATE_INFO (tmpl))
4110     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4111
4112   info = tree_cons (tmpl, args, NULL_TREE);
4113
4114   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4115     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4116   else if (DECL_LANG_SPECIFIC (decl))
4117     DECL_TEMPLATE_INFO (decl) = info;
4118
4119   return DECL_TEMPLATE_RESULT (tmpl);
4120 }
4121
4122 tree
4123 push_template_decl (tree decl)
4124 {
4125   return push_template_decl_real (decl, false);
4126 }
4127
4128 /* Called when a class template TYPE is redeclared with the indicated
4129    template PARMS, e.g.:
4130
4131      template <class T> struct S;
4132      template <class T> struct S {};  */
4133
4134 bool
4135 redeclare_class_template (tree type, tree parms)
4136 {
4137   tree tmpl;
4138   tree tmpl_parms;
4139   int i;
4140
4141   if (!TYPE_TEMPLATE_INFO (type))
4142     {
4143       error ("%qT is not a template type", type);
4144       return false;
4145     }
4146
4147   tmpl = TYPE_TI_TEMPLATE (type);
4148   if (!PRIMARY_TEMPLATE_P (tmpl))
4149     /* The type is nested in some template class.  Nothing to worry
4150        about here; there are no new template parameters for the nested
4151        type.  */
4152     return true;
4153
4154   if (!parms)
4155     {
4156       error ("template specifiers not specified in declaration of %qD",
4157              tmpl);
4158       return false;
4159     }
4160
4161   parms = INNERMOST_TEMPLATE_PARMS (parms);
4162   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4163
4164   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4165     {
4166       error ("redeclared with %d template parameter(s)", 
4167              TREE_VEC_LENGTH (parms));
4168       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4169              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4170       return false;
4171     }
4172
4173   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4174     {
4175       tree tmpl_parm;
4176       tree parm;
4177       tree tmpl_default;
4178       tree parm_default;
4179
4180       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4181           || TREE_VEC_ELT (parms, i) == error_mark_node)
4182         continue;
4183
4184       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4185       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4186       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4187       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4188
4189       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4190          TEMPLATE_DECL.  */
4191       if (tmpl_parm != error_mark_node
4192           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4193               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4194                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4195               || (TREE_CODE (tmpl_parm) != PARM_DECL
4196                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4197                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4198               || (TREE_CODE (tmpl_parm) == PARM_DECL
4199                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4200                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4201         {
4202           error ("template parameter %q+#D", tmpl_parm);
4203           error ("redeclared here as %q#D", parm);
4204           return false;
4205         }
4206
4207       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4208         {
4209           /* We have in [temp.param]:
4210
4211              A template-parameter may not be given default arguments
4212              by two different declarations in the same scope.  */
4213           error ("redefinition of default argument for %q#D", parm);
4214           inform (input_location, "%Joriginal definition appeared here", tmpl_parm);
4215           return false;
4216         }
4217
4218       if (parm_default != NULL_TREE)
4219         /* Update the previous template parameters (which are the ones
4220            that will really count) with the new default value.  */
4221         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4222       else if (tmpl_default != NULL_TREE)
4223         /* Update the new parameters, too; they'll be used as the
4224            parameters for any members.  */
4225         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4226     }
4227
4228     return true;
4229 }
4230
4231 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4232    (possibly simplified) expression.  */
4233
4234 tree
4235 fold_non_dependent_expr (tree expr)
4236 {
4237   if (expr == NULL_TREE)
4238     return NULL_TREE;
4239
4240   /* If we're in a template, but EXPR isn't value dependent, simplify
4241      it.  We're supposed to treat:
4242
4243        template <typename T> void f(T[1 + 1]);
4244        template <typename T> void f(T[2]);
4245
4246      as two declarations of the same function, for example.  */
4247   if (processing_template_decl
4248       && !type_dependent_expression_p (expr)
4249       && !value_dependent_expression_p (expr))
4250     {
4251       HOST_WIDE_INT saved_processing_template_decl;
4252
4253       saved_processing_template_decl = processing_template_decl;
4254       processing_template_decl = 0;
4255       expr = tsubst_copy_and_build (expr,
4256                                     /*args=*/NULL_TREE,
4257                                     tf_error,
4258                                     /*in_decl=*/NULL_TREE,
4259                                     /*function_p=*/false,
4260                                     /*integral_constant_expression_p=*/true);
4261       processing_template_decl = saved_processing_template_decl;
4262     }
4263   return expr;
4264 }
4265
4266 /* EXPR is an expression which is used in a constant-expression context.
4267    For instance, it could be a VAR_DECL with a constant initializer.
4268    Extract the innermost constant expression.
4269
4270    This is basically a more powerful version of
4271    integral_constant_value, which can be used also in templates where
4272    initializers can maintain a syntactic rather than semantic form
4273    (even if they are non-dependent, for access-checking purposes).  */
4274
4275 static tree
4276 fold_decl_constant_value (tree expr)
4277 {
4278   tree const_expr = expr;
4279   do
4280     {
4281       expr = fold_non_dependent_expr (const_expr);
4282       const_expr = integral_constant_value (expr);
4283     }
4284   while (expr != const_expr);
4285
4286   return expr;
4287 }
4288
4289 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4290    must be a function or a pointer-to-function type, as specified
4291    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4292    and check that the resulting function has external linkage.  */
4293
4294 static tree
4295 convert_nontype_argument_function (tree type, tree expr)
4296 {
4297   tree fns = expr;
4298   tree fn, fn_no_ptr;
4299
4300   fn = instantiate_type (type, fns, tf_none);
4301   if (fn == error_mark_node)
4302     return error_mark_node;
4303
4304   fn_no_ptr = fn;
4305   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4306     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4307   if (TREE_CODE (fn_no_ptr) == BASELINK)
4308     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4309  
4310   /* [temp.arg.nontype]/1
4311
4312      A template-argument for a non-type, non-template template-parameter
4313      shall be one of:
4314      [...]
4315      -- the address of an object or function with external linkage.  */
4316   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4317     {
4318       error ("%qE is not a valid template argument for type %qT "
4319              "because function %qD has not external linkage",
4320              expr, type, fn_no_ptr);
4321       return NULL_TREE;
4322     }
4323
4324   return fn;
4325 }
4326
4327 /* Subroutine of convert_nontype_argument.
4328    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4329    Emit an error otherwise.  */
4330
4331 static bool
4332 check_valid_ptrmem_cst_expr (tree type, tree expr)
4333 {
4334   STRIP_NOPS (expr);
4335   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4336     return true;
4337   error ("%qE is not a valid template argument for type %qT",
4338          expr, type);
4339   error ("it must be a pointer-to-member of the form `&X::Y'");
4340   return false;
4341 }
4342
4343 /* Returns TRUE iff the address of OP is value-dependent.
4344
4345    14.6.2.4 [temp.dep.temp]:
4346    A non-integral non-type template-argument is dependent if its type is
4347    dependent or it has either of the following forms
4348      qualified-id
4349      & qualified-id
4350    and contains a nested-name-specifier which specifies a class-name that
4351    names a dependent type.
4352
4353    We generalize this to just say that the address of a member of a
4354    dependent class is value-dependent; the above doesn't cover the
4355    address of a static data member named with an unqualified-id.  */
4356
4357 static bool
4358 has_value_dependent_address (tree op)
4359 {
4360   /* We could use get_inner_reference here, but there's no need;
4361      this is only relevant for template non-type arguments, which
4362      can only be expressed as &id-expression.  */
4363   if (DECL_P (op))
4364     {
4365       tree ctx = CP_DECL_CONTEXT (op);
4366       if (TYPE_P (ctx) && dependent_type_p (ctx))
4367         return true;
4368     }
4369
4370   return false;
4371 }
4372
4373 /* Attempt to convert the non-type template parameter EXPR to the
4374    indicated TYPE.  If the conversion is successful, return the
4375    converted value.  If the conversion is unsuccessful, return
4376    NULL_TREE if we issued an error message, or error_mark_node if we
4377    did not.  We issue error messages for out-and-out bad template
4378    parameters, but not simply because the conversion failed, since we
4379    might be just trying to do argument deduction.  Both TYPE and EXPR
4380    must be non-dependent.
4381
4382    The conversion follows the special rules described in
4383    [temp.arg.nontype], and it is much more strict than an implicit
4384    conversion.
4385
4386    This function is called twice for each template argument (see
4387    lookup_template_class for a more accurate description of this
4388    problem). This means that we need to handle expressions which
4389    are not valid in a C++ source, but can be created from the
4390    first call (for instance, casts to perform conversions). These
4391    hacks can go away after we fix the double coercion problem.  */
4392
4393 static tree
4394 convert_nontype_argument (tree type, tree expr)
4395 {
4396   tree expr_type;
4397
4398   /* Detect immediately string literals as invalid non-type argument.
4399      This special-case is not needed for correctness (we would easily
4400      catch this later), but only to provide better diagnostic for this
4401      common user mistake. As suggested by DR 100, we do not mention
4402      linkage issues in the diagnostic as this is not the point.  */
4403   if (TREE_CODE (expr) == STRING_CST)
4404     {
4405       error ("%qE is not a valid template argument for type %qT "
4406              "because string literals can never be used in this context",
4407              expr, type);
4408       return NULL_TREE;
4409     }
4410
4411   /* Add the ADDR_EXPR now for the benefit of
4412      value_dependent_expression_p.  */
4413   if (TYPE_PTROBV_P (type))
4414     expr = decay_conversion (expr);
4415
4416   /* If we are in a template, EXPR may be non-dependent, but still
4417      have a syntactic, rather than semantic, form.  For example, EXPR
4418      might be a SCOPE_REF, rather than the VAR_DECL to which the
4419      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4420      so that access checking can be performed when the template is
4421      instantiated -- but here we need the resolved form so that we can
4422      convert the argument.  */
4423   if (TYPE_REF_OBJ_P (type)
4424       && has_value_dependent_address (expr))
4425     /* If we want the address and it's value-dependent, don't fold.  */;
4426   else
4427     expr = fold_non_dependent_expr (expr);
4428   if (error_operand_p (expr))
4429     return error_mark_node;
4430   expr_type = TREE_TYPE (expr);
4431
4432   /* HACK: Due to double coercion, we can get a
4433      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4434      which is the tree that we built on the first call (see
4435      below when coercing to reference to object or to reference to
4436      function). We just strip everything and get to the arg.
4437      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4438      for examples.  */
4439   if (TREE_CODE (expr) == NOP_EXPR)
4440     {
4441       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4442         {
4443           /* ??? Maybe we could use convert_from_reference here, but we
4444              would need to relax its constraints because the NOP_EXPR
4445              could actually change the type to something more cv-qualified,
4446              and this is not folded by convert_from_reference.  */
4447           tree addr = TREE_OPERAND (expr, 0);
4448           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4449           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4450           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4451           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4452                       (TREE_TYPE (expr_type),
4453                        TREE_TYPE (TREE_TYPE (addr))));
4454
4455           expr = TREE_OPERAND (addr, 0);
4456           expr_type = TREE_TYPE (expr);
4457         }
4458
4459       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4460          parameter is a pointer to object, through decay and
4461          qualification conversion. Let's strip everything.  */
4462       else if (TYPE_PTROBV_P (type))
4463         {
4464           STRIP_NOPS (expr);
4465           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4466           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4467           /* Skip the ADDR_EXPR only if it is part of the decay for
4468              an array. Otherwise, it is part of the original argument
4469              in the source code.  */
4470           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4471             expr = TREE_OPERAND (expr, 0);
4472           expr_type = TREE_TYPE (expr);
4473         }
4474     }
4475
4476   /* [temp.arg.nontype]/5, bullet 1
4477
4478      For a non-type template-parameter of integral or enumeration type,
4479      integral promotions (_conv.prom_) and integral conversions
4480      (_conv.integral_) are applied.  */
4481   if (INTEGRAL_TYPE_P (type))
4482     {
4483       if (!INTEGRAL_TYPE_P (expr_type))
4484         return error_mark_node;
4485
4486       expr = fold_decl_constant_value (expr);
4487       /* Notice that there are constant expressions like '4 % 0' which
4488          do not fold into integer constants.  */
4489       if (TREE_CODE (expr) != INTEGER_CST)
4490         {
4491           error ("%qE is not a valid template argument for type %qT "
4492                  "because it is a non-constant expression", expr, type);
4493           return NULL_TREE;
4494         }
4495
4496       /* At this point, an implicit conversion does what we want,
4497          because we already know that the expression is of integral
4498          type.  */
4499       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4500       if (expr == error_mark_node)
4501         return error_mark_node;
4502
4503       /* Conversion was allowed: fold it to a bare integer constant.  */
4504       expr = fold (expr);
4505     }
4506   /* [temp.arg.nontype]/5, bullet 2
4507
4508      For a non-type template-parameter of type pointer to object,
4509      qualification conversions (_conv.qual_) and the array-to-pointer
4510      conversion (_conv.array_) are applied.  */
4511   else if (TYPE_PTROBV_P (type))
4512     {
4513       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4514
4515          A template-argument for a non-type, non-template template-parameter
4516          shall be one of: [...]
4517
4518          -- the name of a non-type template-parameter;
4519          -- the address of an object or function with external linkage, [...]
4520             expressed as "& id-expression" where the & is optional if the name
4521             refers to a function or array, or if the corresponding
4522             template-parameter is a reference.
4523
4524         Here, we do not care about functions, as they are invalid anyway
4525         for a parameter of type pointer-to-object.  */
4526
4527       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4528         /* Non-type template parameters are OK.  */
4529         ;
4530       else if (TREE_CODE (expr) != ADDR_EXPR
4531                && TREE_CODE (expr_type) != ARRAY_TYPE)
4532         {
4533           if (TREE_CODE (expr) == VAR_DECL)
4534             {
4535               error ("%qD is not a valid template argument "
4536                      "because %qD is a variable, not the address of "
4537                      "a variable",
4538                      expr, expr);
4539               return NULL_TREE;
4540             }
4541           /* Other values, like integer constants, might be valid
4542              non-type arguments of some other type.  */
4543           return error_mark_node;
4544         }
4545       else
4546         {
4547           tree decl;
4548
4549           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4550                   ? TREE_OPERAND (expr, 0) : expr);
4551           if (TREE_CODE (decl) != VAR_DECL)
4552             {
4553               error ("%qE is not a valid template argument of type %qT "
4554                      "because %qE is not a variable",
4555                      expr, type, decl);
4556               return NULL_TREE;
4557             }
4558           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4559             {
4560               error ("%qE is not a valid template argument of type %qT "
4561                      "because %qD does not have external linkage",
4562                      expr, type, decl);
4563               return NULL_TREE;
4564             }
4565         }
4566
4567       expr = decay_conversion (expr);
4568       if (expr == error_mark_node)
4569         return error_mark_node;
4570
4571       expr = perform_qualification_conversions (type, expr);
4572       if (expr == error_mark_node)
4573         return error_mark_node;
4574     }
4575   /* [temp.arg.nontype]/5, bullet 3
4576
4577      For a non-type template-parameter of type reference to object, no
4578      conversions apply. The type referred to by the reference may be more
4579      cv-qualified than the (otherwise identical) type of the
4580      template-argument. The template-parameter is bound directly to the
4581      template-argument, which must be an lvalue.  */
4582   else if (TYPE_REF_OBJ_P (type))
4583     {
4584       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4585                                                       expr_type))
4586         return error_mark_node;
4587
4588       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4589         {
4590           error ("%qE is not a valid template argument for type %qT "
4591                  "because of conflicts in cv-qualification", expr, type);
4592           return NULL_TREE;
4593         }
4594
4595       if (!real_lvalue_p (expr))
4596         {
4597           error ("%qE is not a valid template argument for type %qT "
4598                  "because it is not an lvalue", expr, type);
4599           return NULL_TREE;
4600         }
4601
4602       /* [temp.arg.nontype]/1
4603
4604          A template-argument for a non-type, non-template template-parameter
4605          shall be one of: [...]
4606
4607          -- the address of an object or function with external linkage.  */
4608       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4609         {
4610           error ("%qE is not a valid template argument for type %qT "
4611                  "because object %qD has not external linkage",
4612                  expr, type, expr);
4613           return NULL_TREE;
4614         }
4615
4616       expr = build_nop (type, build_address (expr));
4617     }
4618   /* [temp.arg.nontype]/5, bullet 4
4619
4620      For a non-type template-parameter of type pointer to function, only
4621      the function-to-pointer conversion (_conv.func_) is applied. If the
4622      template-argument represents a set of overloaded functions (or a
4623      pointer to such), the matching function is selected from the set
4624      (_over.over_).  */
4625   else if (TYPE_PTRFN_P (type))
4626     {
4627       /* If the argument is a template-id, we might not have enough
4628          context information to decay the pointer.  */
4629       if (!type_unknown_p (expr_type))
4630         {
4631           expr = decay_conversion (expr);
4632           if (expr == error_mark_node)
4633             return error_mark_node;
4634         }
4635
4636       expr = convert_nontype_argument_function (type, expr);
4637       if (!expr || expr == error_mark_node)
4638         return expr;
4639
4640       if (TREE_CODE (expr) != ADDR_EXPR)
4641         {
4642           error ("%qE is not a valid template argument for type %qT", expr, type);
4643           error ("it must be the address of a function with external linkage");
4644           return NULL_TREE;
4645         }
4646     }
4647   /* [temp.arg.nontype]/5, bullet 5
4648
4649      For a non-type template-parameter of type reference to function, no
4650      conversions apply. If the template-argument represents a set of
4651      overloaded functions, the matching function is selected from the set
4652      (_over.over_).  */
4653   else if (TYPE_REFFN_P (type))
4654     {
4655       if (TREE_CODE (expr) == ADDR_EXPR)
4656         {
4657           error ("%qE is not a valid template argument for type %qT "
4658                  "because it is a pointer", expr, type);
4659           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4660           return NULL_TREE;
4661         }
4662
4663       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4664       if (!expr || expr == error_mark_node)
4665         return expr;
4666
4667       expr = build_nop (type, build_address (expr));
4668     }
4669   /* [temp.arg.nontype]/5, bullet 6
4670
4671      For a non-type template-parameter of type pointer to member function,
4672      no conversions apply. If the template-argument represents a set of
4673      overloaded member functions, the matching member function is selected
4674      from the set (_over.over_).  */
4675   else if (TYPE_PTRMEMFUNC_P (type))
4676     {
4677       expr = instantiate_type (type, expr, tf_none);
4678       if (expr == error_mark_node)
4679         return error_mark_node;
4680
4681       /* [temp.arg.nontype] bullet 1 says the pointer to member
4682          expression must be a pointer-to-member constant.  */
4683       if (!check_valid_ptrmem_cst_expr (type, expr))
4684         return error_mark_node;
4685
4686       /* There is no way to disable standard conversions in
4687          resolve_address_of_overloaded_function (called by
4688          instantiate_type). It is possible that the call succeeded by
4689          converting &B::I to &D::I (where B is a base of D), so we need
4690          to reject this conversion here.
4691
4692          Actually, even if there was a way to disable standard conversions,
4693          it would still be better to reject them here so that we can
4694          provide a superior diagnostic.  */
4695       if (!same_type_p (TREE_TYPE (expr), type))
4696         {
4697           /* Make sure we are just one standard conversion off.  */
4698           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4699           error ("%qE is not a valid template argument for type %qT "
4700                  "because it is of type %qT", expr, type,
4701                  TREE_TYPE (expr));
4702           inform (input_location, "standard conversions are not allowed in this context");
4703           return NULL_TREE;
4704         }
4705     }
4706   /* [temp.arg.nontype]/5, bullet 7
4707
4708      For a non-type template-parameter of type pointer to data member,
4709      qualification conversions (_conv.qual_) are applied.  */
4710   else if (TYPE_PTRMEM_P (type))
4711     {
4712       /* [temp.arg.nontype] bullet 1 says the pointer to member
4713          expression must be a pointer-to-member constant.  */
4714       if (!check_valid_ptrmem_cst_expr (type, expr))
4715         return error_mark_node;
4716
4717       expr = perform_qualification_conversions (type, expr);
4718       if (expr == error_mark_node)
4719         return expr;
4720     }
4721   /* A template non-type parameter must be one of the above.  */
4722   else
4723     gcc_unreachable ();
4724
4725   /* Sanity check: did we actually convert the argument to the
4726      right type?  */
4727   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4728   return expr;
4729 }
4730
4731 /* Subroutine of coerce_template_template_parms, which returns 1 if
4732    PARM_PARM and ARG_PARM match using the rule for the template
4733    parameters of template template parameters. Both PARM and ARG are
4734    template parameters; the rest of the arguments are the same as for
4735    coerce_template_template_parms.
4736  */
4737 static int
4738 coerce_template_template_parm (tree parm,
4739                               tree arg,
4740                               tsubst_flags_t complain,
4741                               tree in_decl,
4742                               tree outer_args)
4743 {
4744   if (arg == NULL_TREE || arg == error_mark_node
4745       || parm == NULL_TREE || parm == error_mark_node)
4746     return 0;
4747   
4748   if (TREE_CODE (arg) != TREE_CODE (parm))
4749     return 0;
4750   
4751   switch (TREE_CODE (parm))
4752     {
4753     case TEMPLATE_DECL:
4754       /* We encounter instantiations of templates like
4755          template <template <template <class> class> class TT>
4756          class C;  */
4757       {
4758         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4759         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4760         
4761         if (!coerce_template_template_parms
4762             (parmparm, argparm, complain, in_decl, outer_args))
4763           return 0;
4764       }
4765       /* Fall through.  */
4766       
4767     case TYPE_DECL:
4768       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
4769           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4770         /* Argument is a parameter pack but parameter is not.  */
4771         return 0;
4772       break;
4773       
4774     case PARM_DECL:
4775       /* The tsubst call is used to handle cases such as
4776          
4777            template <int> class C {};
4778            template <class T, template <T> class TT> class D {};
4779            D<int, C> d;
4780
4781          i.e. the parameter list of TT depends on earlier parameters.  */
4782       if (!uses_template_parms (TREE_TYPE (arg))
4783           && !same_type_p
4784                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4785                  TREE_TYPE (arg)))
4786         return 0;
4787       
4788       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
4789           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4790         /* Argument is a parameter pack but parameter is not.  */
4791         return 0;
4792       
4793       break;
4794
4795     default:
4796       gcc_unreachable ();
4797     }
4798
4799   return 1;
4800 }
4801
4802
4803 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4804    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4805    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4806    or PARM_DECL.
4807
4808    Consider the example:
4809      template <class T> class A;
4810      template<template <class U> class TT> class B;
4811
4812    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4813    the parameters to A, and OUTER_ARGS contains A.  */
4814
4815 static int
4816 coerce_template_template_parms (tree parm_parms,
4817                                 tree arg_parms,
4818                                 tsubst_flags_t complain,
4819                                 tree in_decl,
4820                                 tree outer_args)
4821 {
4822   int nparms, nargs, i;
4823   tree parm, arg;
4824   int variadic_p = 0;
4825
4826   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4827   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4828
4829   nparms = TREE_VEC_LENGTH (parm_parms);
4830   nargs = TREE_VEC_LENGTH (arg_parms);
4831
4832   /* Determine whether we have a parameter pack at the end of the
4833      template template parameter's template parameter list.  */
4834   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
4835     {
4836       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
4837       
4838       if (parm == error_mark_node)
4839         return 0;
4840
4841       switch (TREE_CODE (parm))
4842         {
4843         case TEMPLATE_DECL:
4844         case TYPE_DECL:
4845           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4846             variadic_p = 1;
4847           break;
4848           
4849         case PARM_DECL:
4850           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4851             variadic_p = 1;
4852           break;
4853           
4854         default:
4855           gcc_unreachable ();
4856         }
4857     }
4858  
4859   if (nargs != nparms
4860       && !(variadic_p && nargs >= nparms - 1))
4861     return 0;
4862
4863   /* Check all of the template parameters except the parameter pack at
4864      the end (if any).  */
4865   for (i = 0; i < nparms - variadic_p; ++i)
4866     {
4867       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4868           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4869         continue;
4870
4871       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4872       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4873
4874       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4875                                           outer_args))
4876         return 0;
4877
4878     }
4879
4880   if (variadic_p)
4881     {
4882       /* Check each of the template parameters in the template
4883          argument against the template parameter pack at the end of
4884          the template template parameter.  */
4885       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
4886         return 0;
4887
4888       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4889
4890       for (; i < nargs; ++i)
4891         {
4892           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4893             continue;
4894  
4895           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4896  
4897           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4898                                               outer_args))
4899             return 0;
4900         }
4901     }
4902
4903   return 1;
4904 }
4905
4906 /* Verifies that the deduced template arguments (in TARGS) for the
4907    template template parameters (in TPARMS) represent valid bindings,
4908    by comparing the template parameter list of each template argument
4909    to the template parameter list of its corresponding template
4910    template parameter, in accordance with DR150. This
4911    routine can only be called after all template arguments have been
4912    deduced. It will return TRUE if all of the template template
4913    parameter bindings are okay, FALSE otherwise.  */
4914 bool 
4915 template_template_parm_bindings_ok_p (tree tparms, tree targs)
4916 {
4917   int i, ntparms = TREE_VEC_LENGTH (tparms);
4918   bool ret = true;
4919
4920   /* We're dealing with template parms in this process.  */
4921   ++processing_template_decl;
4922
4923   targs = INNERMOST_TEMPLATE_ARGS (targs);
4924
4925   for (i = 0; i < ntparms; ++i)
4926     {
4927       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
4928       tree targ = TREE_VEC_ELT (targs, i);
4929
4930       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
4931         {
4932           tree packed_args = NULL_TREE;
4933           int idx, len = 1;
4934
4935           if (ARGUMENT_PACK_P (targ))
4936             {
4937               /* Look inside the argument pack.  */
4938               packed_args = ARGUMENT_PACK_ARGS (targ);
4939               len = TREE_VEC_LENGTH (packed_args);
4940             }
4941
4942           for (idx = 0; idx < len; ++idx)
4943             {
4944               tree targ_parms = NULL_TREE;
4945
4946               if (packed_args)
4947                 /* Extract the next argument from the argument
4948                    pack.  */
4949                 targ = TREE_VEC_ELT (packed_args, idx);
4950
4951               if (PACK_EXPANSION_P (targ))
4952                 /* Look at the pattern of the pack expansion.  */
4953                 targ = PACK_EXPANSION_PATTERN (targ);
4954
4955               /* Extract the template parameters from the template
4956                  argument.  */
4957               if (TREE_CODE (targ) == TEMPLATE_DECL)
4958                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
4959               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
4960                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
4961
4962               /* Verify that we can coerce the template template
4963                  parameters from the template argument to the template
4964                  parameter.  This requires an exact match.  */
4965               if (targ_parms
4966                   && !coerce_template_template_parms
4967                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
4968                         targ_parms,
4969                         tf_none,
4970                         tparm,
4971                         targs))
4972                 {
4973                   ret = false;
4974                   goto out;
4975                 }
4976             }
4977         }
4978     }
4979
4980  out:
4981
4982   --processing_template_decl;
4983   return ret;
4984 }
4985
4986 /* Convert the indicated template ARG as necessary to match the
4987    indicated template PARM.  Returns the converted ARG, or
4988    error_mark_node if the conversion was unsuccessful.  Error and
4989    warning messages are issued under control of COMPLAIN.  This
4990    conversion is for the Ith parameter in the parameter list.  ARGS is
4991    the full set of template arguments deduced so far.  */
4992
4993 static tree
4994 convert_template_argument (tree parm,
4995                            tree arg,
4996                            tree args,
4997                            tsubst_flags_t complain,
4998                            int i,
4999                            tree in_decl)
5000 {
5001   tree orig_arg;
5002   tree val;
5003   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5004
5005   if (TREE_CODE (arg) == TREE_LIST
5006       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5007     {
5008       /* The template argument was the name of some
5009          member function.  That's usually
5010          invalid, but static members are OK.  In any
5011          case, grab the underlying fields/functions
5012          and issue an error later if required.  */
5013       orig_arg = TREE_VALUE (arg);
5014       TREE_TYPE (arg) = unknown_type_node;
5015     }
5016
5017   orig_arg = arg;
5018
5019   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5020   requires_type = (TREE_CODE (parm) == TYPE_DECL
5021                    || requires_tmpl_type);
5022
5023   /* When determining whether an argument pack expansion is a template,
5024      look at the pattern.  */
5025   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5026     arg = PACK_EXPANSION_PATTERN (arg);
5027
5028   is_tmpl_type = 
5029     ((TREE_CODE (arg) == TEMPLATE_DECL
5030       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5031      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5032      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5033
5034   if (is_tmpl_type
5035       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5036           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5037     arg = TYPE_STUB_DECL (arg);
5038
5039   is_type = TYPE_P (arg) || is_tmpl_type;
5040
5041   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5042       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5043     {
5044       permerror (input_location, "to refer to a type member of a template parameter, "
5045                  "use %<typename %E%>", orig_arg);
5046
5047       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5048                                      TREE_OPERAND (arg, 1),
5049                                      typename_type,
5050                                      complain & tf_error);
5051       arg = orig_arg;
5052       is_type = 1;
5053     }
5054   if (is_type != requires_type)
5055     {
5056       if (in_decl)
5057         {
5058           if (complain & tf_error)
5059             {
5060               error ("type/value mismatch at argument %d in template "
5061                      "parameter list for %qD",
5062                      i + 1, in_decl);
5063               if (is_type)
5064                 error ("  expected a constant of type %qT, got %qT",
5065                        TREE_TYPE (parm),
5066                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5067               else if (requires_tmpl_type)
5068                 error ("  expected a class template, got %qE", orig_arg);
5069               else
5070                 error ("  expected a type, got %qE", orig_arg);
5071             }
5072         }
5073       return error_mark_node;
5074     }
5075   if (is_tmpl_type ^ requires_tmpl_type)
5076     {
5077       if (in_decl && (complain & tf_error))
5078         {
5079           error ("type/value mismatch at argument %d in template "
5080                  "parameter list for %qD",
5081                  i + 1, in_decl);
5082           if (is_tmpl_type)
5083             error ("  expected a type, got %qT", DECL_NAME (arg));
5084           else
5085             error ("  expected a class template, got %qT", orig_arg);
5086         }
5087       return error_mark_node;
5088     }
5089
5090   if (is_type)
5091     {
5092       if (requires_tmpl_type)
5093         {
5094           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5095             /* The number of argument required is not known yet.
5096                Just accept it for now.  */
5097             val = TREE_TYPE (arg);
5098           else
5099             {
5100               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5101               tree argparm;
5102
5103               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5104
5105               if (coerce_template_template_parms (parmparm, argparm,
5106                                                   complain, in_decl,
5107                                                   args))
5108                 {
5109                   val = orig_arg;
5110
5111                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5112                      TEMPLATE_DECL.  */
5113                   if (val != error_mark_node)
5114                     {
5115                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5116                         val = TREE_TYPE (val);
5117                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5118                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5119                         {
5120                           val = TREE_TYPE (arg);
5121                           val = make_pack_expansion (val);
5122                         }
5123                     }
5124                 }
5125               else
5126                 {
5127                   if (in_decl && (complain & tf_error))
5128                     {
5129                       error ("type/value mismatch at argument %d in "
5130                              "template parameter list for %qD",
5131                              i + 1, in_decl);
5132                       error ("  expected a template of type %qD, got %qT",
5133                              parm, orig_arg);
5134                     }
5135
5136                   val = error_mark_node;
5137                 }
5138             }
5139         }
5140       else
5141         val = orig_arg;
5142       /* We only form one instance of each template specialization.
5143          Therefore, if we use a non-canonical variant (i.e., a
5144          typedef), any future messages referring to the type will use
5145          the typedef, which is confusing if those future uses do not
5146          themselves also use the typedef.  */
5147       if (TYPE_P (val))
5148         val = canonical_type_variant (val);
5149     }
5150   else
5151     {
5152       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5153
5154       if (invalid_nontype_parm_type_p (t, complain))
5155         return error_mark_node;
5156
5157       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5158         {
5159           if (same_type_p (t, TREE_TYPE (orig_arg)))
5160             val = orig_arg;
5161           else
5162             {
5163               /* Not sure if this is reachable, but it doesn't hurt
5164                  to be robust.  */
5165               error ("type mismatch in nontype parameter pack");
5166               val = error_mark_node;
5167             }
5168         }
5169       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5170         /* We used to call digest_init here.  However, digest_init
5171            will report errors, which we don't want when complain
5172            is zero.  More importantly, digest_init will try too
5173            hard to convert things: for example, `0' should not be
5174            converted to pointer type at this point according to
5175            the standard.  Accepting this is not merely an
5176            extension, since deciding whether or not these
5177            conversions can occur is part of determining which
5178            function template to call, or whether a given explicit
5179            argument specification is valid.  */
5180         val = convert_nontype_argument (t, orig_arg);
5181       else
5182         val = orig_arg;
5183
5184       if (val == NULL_TREE)
5185         val = error_mark_node;
5186       else if (val == error_mark_node && (complain & tf_error))
5187         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5188     }
5189
5190   return val;
5191 }
5192
5193 /* Coerces the remaining template arguments in INNER_ARGS (from
5194    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5195    Returns the coerced argument pack. PARM_IDX is the position of this
5196    parameter in the template parameter list. ARGS is the original
5197    template argument list.  */
5198 static tree
5199 coerce_template_parameter_pack (tree parms,
5200                                 int parm_idx,
5201                                 tree args,
5202                                 tree inner_args,
5203                                 int arg_idx,
5204                                 tree new_args,
5205                                 int* lost,
5206                                 tree in_decl,
5207                                 tsubst_flags_t complain)
5208 {
5209   tree parm = TREE_VEC_ELT (parms, parm_idx);
5210   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5211   tree packed_args;
5212   tree argument_pack;
5213   tree packed_types = NULL_TREE;
5214
5215   if (arg_idx > nargs)
5216     arg_idx = nargs;
5217
5218   packed_args = make_tree_vec (nargs - arg_idx);
5219
5220   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5221       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5222     {
5223       /* When the template parameter is a non-type template
5224          parameter pack whose type uses parameter packs, we need
5225          to look at each of the template arguments
5226          separately. Build a vector of the types for these
5227          non-type template parameters in PACKED_TYPES.  */
5228       tree expansion 
5229         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5230       packed_types = tsubst_pack_expansion (expansion, args,
5231                                             complain, in_decl);
5232
5233       if (packed_types == error_mark_node)
5234         return error_mark_node;
5235
5236       /* Check that we have the right number of arguments.  */
5237       if (arg_idx < nargs
5238           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5239           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5240         {
5241           int needed_parms 
5242             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5243           error ("wrong number of template arguments (%d, should be %d)",
5244                  nargs, needed_parms);
5245           return error_mark_node;
5246         }
5247
5248       /* If we aren't able to check the actual arguments now
5249          (because they haven't been expanded yet), we can at least
5250          verify that all of the types used for the non-type
5251          template parameter pack are, in fact, valid for non-type
5252          template parameters.  */
5253       if (arg_idx < nargs 
5254           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5255         {
5256           int j, len = TREE_VEC_LENGTH (packed_types);
5257           for (j = 0; j < len; ++j)
5258             {
5259               tree t = TREE_VEC_ELT (packed_types, j);
5260               if (invalid_nontype_parm_type_p (t, complain))
5261                 return error_mark_node;
5262             }
5263         }
5264     }
5265
5266   /* Convert the remaining arguments, which will be a part of the
5267      parameter pack "parm".  */
5268   for (; arg_idx < nargs; ++arg_idx)
5269     {
5270       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5271       tree actual_parm = TREE_VALUE (parm);
5272
5273       if (packed_types && !PACK_EXPANSION_P (arg))
5274         {
5275           /* When we have a vector of types (corresponding to the
5276              non-type template parameter pack that uses parameter
5277              packs in its type, as mention above), and the
5278              argument is not an expansion (which expands to a
5279              currently unknown number of arguments), clone the
5280              parm and give it the next type in PACKED_TYPES.  */
5281           actual_parm = copy_node (actual_parm);
5282           TREE_TYPE (actual_parm) = 
5283             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5284         }
5285
5286       if (arg != error_mark_node)
5287         arg = convert_template_argument (actual_parm, 
5288                                          arg, new_args, complain, parm_idx,
5289                                          in_decl);
5290       if (arg == error_mark_node)
5291         (*lost)++;
5292       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5293     }
5294
5295   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5296       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5297     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5298   else
5299     {
5300       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5301       TREE_TYPE (argument_pack) 
5302         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5303       TREE_CONSTANT (argument_pack) = 1;
5304     }
5305
5306   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5307   return argument_pack;
5308 }
5309
5310 /* Convert all template arguments to their appropriate types, and
5311    return a vector containing the innermost resulting template
5312    arguments.  If any error occurs, return error_mark_node. Error and
5313    warning messages are issued under control of COMPLAIN.
5314
5315    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5316    for arguments not specified in ARGS.  Otherwise, if
5317    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5318    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5319    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5320    ARGS.  */
5321
5322 static tree
5323 coerce_template_parms (tree parms,
5324                        tree args,
5325                        tree in_decl,
5326                        tsubst_flags_t complain,
5327                        bool require_all_args,
5328                        bool use_default_args)
5329 {
5330   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5331   tree inner_args;
5332   tree new_args;
5333   tree new_inner_args;
5334   bool saved_skip_evaluation;
5335
5336   /* When used as a boolean value, indicates whether this is a
5337      variadic template parameter list. Since it's an int, we can also
5338      subtract it from nparms to get the number of non-variadic
5339      parameters.  */
5340   int variadic_p = 0;
5341
5342   nparms = TREE_VEC_LENGTH (parms);
5343
5344   /* Determine if there are any parameter packs.  */
5345   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5346     {
5347       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5348       if (template_parameter_pack_p (tparm))
5349         ++variadic_p;
5350     }
5351
5352   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5353   /* If there are 0 or 1 parameter packs, we need to expand any argument
5354      packs so that we can deduce a parameter pack from some non-packed args
5355      followed by an argument pack, as in variadic85.C.  If there are more
5356      than that, we need to leave argument packs intact so the arguments are
5357      assigned to the right parameter packs.  This should only happen when
5358      dealing with a nested class inside a partial specialization of a class
5359      template, as in variadic92.C.  */
5360   if (variadic_p <= 1)
5361     inner_args = expand_template_argument_pack (inner_args);
5362
5363   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5364   if ((nargs > nparms && !variadic_p)
5365       || (nargs < nparms - variadic_p
5366           && require_all_args
5367           && (!use_default_args
5368               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5369                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5370     {
5371       if (complain & tf_error)
5372         {
5373           const char *or_more = "";
5374           if (variadic_p)
5375             {
5376               or_more = " or more";
5377               --nparms;
5378             }
5379
5380           error ("wrong number of template arguments (%d, should be %d%s)",
5381                  nargs, nparms, or_more);
5382
5383           if (in_decl)
5384             error ("provided for %q+D", in_decl);
5385         }
5386
5387       return error_mark_node;
5388     }
5389
5390   /* We need to evaluate the template arguments, even though this
5391      template-id may be nested within a "sizeof".  */
5392   saved_skip_evaluation = skip_evaluation;
5393   skip_evaluation = false;
5394   new_inner_args = make_tree_vec (nparms);
5395   new_args = add_outermost_template_args (args, new_inner_args);
5396   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5397     {
5398       tree arg;
5399       tree parm;
5400
5401       /* Get the Ith template parameter.  */
5402       parm = TREE_VEC_ELT (parms, parm_idx);
5403  
5404       if (parm == error_mark_node)
5405       {
5406         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5407         continue;
5408       }
5409
5410       /* Calculate the next argument.  */
5411       if (arg_idx < nargs)
5412         arg = TREE_VEC_ELT (inner_args, arg_idx);
5413       else
5414         arg = NULL_TREE;
5415
5416       if (template_parameter_pack_p (TREE_VALUE (parm))
5417           && !(arg && ARGUMENT_PACK_P (arg)))
5418         {
5419           /* All remaining arguments will be placed in the
5420              template parameter pack PARM.  */
5421           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5422                                                 inner_args, arg_idx,
5423                                                 new_args, &lost,
5424                                                 in_decl, complain);
5425
5426           /* Store this argument.  */
5427           if (arg == error_mark_node)
5428             lost++;
5429           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5430
5431           /* We are done with all of the arguments.  */
5432           arg_idx = nargs;
5433           
5434           continue;
5435         }
5436       else if (arg)
5437         {
5438           if (PACK_EXPANSION_P (arg))
5439             {
5440               if (complain & tf_error)
5441                 {
5442                   /* FIXME this restriction was removed by N2555; see
5443                      bug 35722.  */
5444                   /* If ARG is a pack expansion, but PARM is not a
5445                      template parameter pack (if it were, we would have
5446                      handled it above), we're trying to expand into a
5447                      fixed-length argument list.  */
5448                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5449                     sorry ("cannot expand %<%E%> into a fixed-length "
5450                            "argument list", arg);
5451                   else
5452                     sorry ("cannot expand %<%T%> into a fixed-length "
5453                            "argument list", arg);
5454                 }
5455               return error_mark_node;
5456             }
5457         }
5458       else if (require_all_args)
5459         /* There must be a default arg in this case.  */
5460         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5461                                    complain, in_decl);
5462       else
5463         break;
5464
5465       if (arg == error_mark_node)
5466         {
5467           if (complain & tf_error)
5468             error ("template argument %d is invalid", arg_idx + 1);
5469         }
5470       else if (!arg)
5471         /* This only occurs if there was an error in the template
5472            parameter list itself (which we would already have
5473            reported) that we are trying to recover from, e.g., a class
5474            template with a parameter list such as
5475            template<typename..., typename>.  */
5476         return error_mark_node;
5477       else
5478         arg = convert_template_argument (TREE_VALUE (parm),
5479                                          arg, new_args, complain, 
5480                                          parm_idx, in_decl);
5481
5482       if (arg == error_mark_node)
5483         lost++;
5484       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5485     }
5486   skip_evaluation = saved_skip_evaluation;
5487
5488   if (lost)
5489     return error_mark_node;
5490
5491   return new_inner_args;
5492 }
5493
5494 /* Returns 1 if template args OT and NT are equivalent.  */
5495
5496 static int
5497 template_args_equal (tree ot, tree nt)
5498 {
5499   if (nt == ot)
5500     return 1;
5501
5502   if (TREE_CODE (nt) == TREE_VEC)
5503     /* For member templates */
5504     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5505   else if (PACK_EXPANSION_P (ot))
5506     return PACK_EXPANSION_P (nt) 
5507       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5508                               PACK_EXPANSION_PATTERN (nt));
5509   else if (ARGUMENT_PACK_P (ot))
5510     {
5511       int i, len;
5512       tree opack, npack;
5513
5514       if (!ARGUMENT_PACK_P (nt))
5515         return 0;
5516
5517       opack = ARGUMENT_PACK_ARGS (ot);
5518       npack = ARGUMENT_PACK_ARGS (nt);
5519       len = TREE_VEC_LENGTH (opack);
5520       if (TREE_VEC_LENGTH (npack) != len)
5521         return 0;
5522       for (i = 0; i < len; ++i)
5523         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5524                                   TREE_VEC_ELT (npack, i)))
5525           return 0;
5526       return 1;
5527     }
5528   else if (TYPE_P (nt))
5529     return TYPE_P (ot) && same_type_p (ot, nt);
5530   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5531     return 0;
5532   else
5533     return cp_tree_equal (ot, nt);
5534 }
5535
5536 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5537    of template arguments.  Returns 0 otherwise.  */
5538
5539 int
5540 comp_template_args (tree oldargs, tree newargs)
5541 {
5542   int i;
5543
5544   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5545     return 0;
5546
5547   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5548     {
5549       tree nt = TREE_VEC_ELT (newargs, i);
5550       tree ot = TREE_VEC_ELT (oldargs, i);
5551
5552       if (! template_args_equal (ot, nt))
5553         return 0;
5554     }
5555   return 1;
5556 }
5557
5558 static void
5559 add_pending_template (tree d)
5560 {
5561   tree ti = (TYPE_P (d)
5562              ? CLASSTYPE_TEMPLATE_INFO (d)
5563              : DECL_TEMPLATE_INFO (d));
5564   struct pending_template *pt;
5565   int level;
5566
5567   if (TI_PENDING_TEMPLATE_FLAG (ti))
5568     return;
5569
5570   /* We are called both from instantiate_decl, where we've already had a
5571      tinst_level pushed, and instantiate_template, where we haven't.
5572      Compensate.  */
5573   level = !current_tinst_level || current_tinst_level->decl != d;
5574
5575   if (level)
5576     push_tinst_level (d);
5577
5578   pt = GGC_NEW (struct pending_template);
5579   pt->next = NULL;
5580   pt->tinst = current_tinst_level;
5581   if (last_pending_template)
5582     last_pending_template->next = pt;
5583   else
5584     pending_templates = pt;
5585
5586   last_pending_template = pt;
5587
5588   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5589
5590   if (level)
5591     pop_tinst_level ();
5592 }
5593
5594
5595 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5596    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5597    documentation for TEMPLATE_ID_EXPR.  */
5598
5599 tree
5600 lookup_template_function (tree fns, tree arglist)
5601 {
5602   tree type;
5603
5604   if (fns == error_mark_node || arglist == error_mark_node)
5605     return error_mark_node;
5606
5607   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5608   gcc_assert (fns && (is_overloaded_fn (fns)
5609                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5610
5611   if (BASELINK_P (fns))
5612     {
5613       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5614                                          unknown_type_node,
5615                                          BASELINK_FUNCTIONS (fns),
5616                                          arglist);
5617       return fns;
5618     }
5619
5620   type = TREE_TYPE (fns);
5621   if (TREE_CODE (fns) == OVERLOAD || !type)
5622     type = unknown_type_node;
5623
5624   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5625 }
5626
5627 /* Within the scope of a template class S<T>, the name S gets bound
5628    (in build_self_reference) to a TYPE_DECL for the class, not a
5629    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5630    or one of its enclosing classes, and that type is a template,
5631    return the associated TEMPLATE_DECL.  Otherwise, the original
5632    DECL is returned.  */
5633
5634 tree
5635 maybe_get_template_decl_from_type_decl (tree decl)
5636 {
5637   return (decl != NULL_TREE
5638           && TREE_CODE (decl) == TYPE_DECL
5639           && DECL_ARTIFICIAL (decl)
5640           && CLASS_TYPE_P (TREE_TYPE (decl))
5641           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5642     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5643 }
5644
5645 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5646    parameters, find the desired type.
5647
5648    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5649
5650    IN_DECL, if non-NULL, is the template declaration we are trying to
5651    instantiate.
5652
5653    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5654    the class we are looking up.
5655
5656    Issue error and warning messages under control of COMPLAIN.
5657
5658    If the template class is really a local class in a template
5659    function, then the FUNCTION_CONTEXT is the function in which it is
5660    being instantiated.
5661
5662    ??? Note that this function is currently called *twice* for each
5663    template-id: the first time from the parser, while creating the
5664    incomplete type (finish_template_type), and the second type during the
5665    real instantiation (instantiate_template_class). This is surely something
5666    that we want to avoid. It also causes some problems with argument
5667    coercion (see convert_nontype_argument for more information on this).  */
5668
5669 tree
5670 lookup_template_class (tree d1,
5671                        tree arglist,
5672                        tree in_decl,
5673                        tree context,
5674                        int entering_scope,
5675                        tsubst_flags_t complain)
5676 {
5677   tree templ = NULL_TREE, parmlist;
5678   tree t;
5679
5680   timevar_push (TV_NAME_LOOKUP);
5681
5682   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5683     {
5684       tree value = innermost_non_namespace_value (d1);
5685       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5686         templ = value;
5687       else
5688         {
5689           if (context)
5690             push_decl_namespace (context);
5691           templ = lookup_name (d1);
5692           templ = maybe_get_template_decl_from_type_decl (templ);
5693           if (context)
5694             pop_decl_namespace ();
5695         }
5696       if (templ)
5697         context = DECL_CONTEXT (templ);
5698     }
5699   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
5700     {
5701       tree type = TREE_TYPE (d1);
5702
5703       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5704          an implicit typename for the second A.  Deal with it.  */
5705       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5706         type = TREE_TYPE (type);
5707
5708       if (CLASSTYPE_TEMPLATE_INFO (type))
5709         {
5710           templ = CLASSTYPE_TI_TEMPLATE (type);
5711           d1 = DECL_NAME (templ);
5712         }
5713     }
5714   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5715            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
5716     {
5717       templ = TYPE_TI_TEMPLATE (d1);
5718       d1 = DECL_NAME (templ);
5719     }
5720   else if (TREE_CODE (d1) == TEMPLATE_DECL
5721            && DECL_TEMPLATE_RESULT (d1)
5722            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5723     {
5724       templ = d1;
5725       d1 = DECL_NAME (templ);
5726       context = DECL_CONTEXT (templ);
5727     }
5728
5729   /* Issue an error message if we didn't find a template.  */
5730   if (! templ)
5731     {
5732       if (complain & tf_error)
5733         error ("%qT is not a template", d1);
5734       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5735     }
5736
5737   if (TREE_CODE (templ) != TEMPLATE_DECL
5738          /* Make sure it's a user visible template, if it was named by
5739             the user.  */
5740       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
5741           && !PRIMARY_TEMPLATE_P (templ)))
5742     {
5743       if (complain & tf_error)
5744         {
5745           error ("non-template type %qT used as a template", d1);
5746           if (in_decl)
5747             error ("for template declaration %q+D", in_decl);
5748         }
5749       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5750     }
5751
5752   complain &= ~tf_user;
5753
5754   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
5755     {
5756       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5757          template arguments */
5758
5759       tree parm;
5760       tree arglist2;
5761       tree outer;
5762
5763       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
5764
5765       /* Consider an example where a template template parameter declared as
5766
5767            template <class T, class U = std::allocator<T> > class TT
5768
5769          The template parameter level of T and U are one level larger than
5770          of TT.  To proper process the default argument of U, say when an
5771          instantiation `TT<int>' is seen, we need to build the full
5772          arguments containing {int} as the innermost level.  Outer levels,
5773          available when not appearing as default template argument, can be
5774          obtained from the arguments of the enclosing template.
5775
5776          Suppose that TT is later substituted with std::vector.  The above
5777          instantiation is `TT<int, std::allocator<T> >' with TT at
5778          level 1, and T at level 2, while the template arguments at level 1
5779          becomes {std::vector} and the inner level 2 is {int}.  */
5780
5781       outer = DECL_CONTEXT (templ);
5782       if (outer)
5783         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5784       else if (current_template_parms)
5785         /* This is an argument of the current template, so we haven't set
5786            DECL_CONTEXT yet.  */
5787         outer = current_template_args ();
5788
5789       if (outer)
5790         arglist = add_to_template_args (outer, arglist);
5791
5792       arglist2 = coerce_template_parms (parmlist, arglist, templ,
5793                                         complain,
5794                                         /*require_all_args=*/true,
5795                                         /*use_default_args=*/true);
5796       if (arglist2 == error_mark_node
5797           || (!uses_template_parms (arglist2)
5798               && check_instantiated_args (templ, arglist2, complain)))
5799         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5800
5801       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
5802       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5803     }
5804   else
5805     {
5806       tree template_type = TREE_TYPE (templ);
5807       tree gen_tmpl;
5808       tree type_decl;
5809       tree found = NULL_TREE;
5810       int arg_depth;
5811       int parm_depth;
5812       int is_partial_instantiation;
5813
5814       gen_tmpl = most_general_template (templ);
5815       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5816       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5817       arg_depth = TMPL_ARGS_DEPTH (arglist);
5818
5819       if (arg_depth == 1 && parm_depth > 1)
5820         {
5821           /* We've been given an incomplete set of template arguments.
5822              For example, given:
5823
5824                template <class T> struct S1 {
5825                  template <class U> struct S2 {};
5826                  template <class U> struct S2<U*> {};
5827                 };
5828
5829              we will be called with an ARGLIST of `U*', but the
5830              TEMPLATE will be `template <class T> template
5831              <class U> struct S1<T>::S2'.  We must fill in the missing
5832              arguments.  */
5833           arglist
5834             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
5835                                            arglist);
5836           arg_depth = TMPL_ARGS_DEPTH (arglist);
5837         }
5838
5839       /* Now we should have enough arguments.  */
5840       gcc_assert (parm_depth == arg_depth);
5841
5842       /* From here on, we're only interested in the most general
5843          template.  */
5844       templ = gen_tmpl;
5845
5846       /* Calculate the BOUND_ARGS.  These will be the args that are
5847          actually tsubst'd into the definition to create the
5848          instantiation.  */
5849       if (parm_depth > 1)
5850         {
5851           /* We have multiple levels of arguments to coerce, at once.  */
5852           int i;
5853           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5854
5855           tree bound_args = make_tree_vec (parm_depth);
5856
5857           for (i = saved_depth,
5858                  t = DECL_TEMPLATE_PARMS (templ);
5859                i > 0 && t != NULL_TREE;
5860                --i, t = TREE_CHAIN (t))
5861             {
5862               tree a = coerce_template_parms (TREE_VALUE (t),
5863                                               arglist, templ,
5864                                               complain,
5865                                               /*require_all_args=*/true,
5866                                               /*use_default_args=*/true);
5867
5868               /* Don't process further if one of the levels fails.  */
5869               if (a == error_mark_node)
5870                 {
5871                   /* Restore the ARGLIST to its full size.  */
5872                   TREE_VEC_LENGTH (arglist) = saved_depth;
5873                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5874                 }
5875
5876               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5877
5878               /* We temporarily reduce the length of the ARGLIST so
5879                  that coerce_template_parms will see only the arguments
5880                  corresponding to the template parameters it is
5881                  examining.  */
5882               TREE_VEC_LENGTH (arglist)--;
5883             }
5884
5885           /* Restore the ARGLIST to its full size.  */
5886           TREE_VEC_LENGTH (arglist) = saved_depth;
5887
5888           arglist = bound_args;
5889         }
5890       else
5891         arglist
5892           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5893                                    INNERMOST_TEMPLATE_ARGS (arglist),
5894                                    templ,
5895                                    complain,
5896                                    /*require_all_args=*/true,
5897                                    /*use_default_args=*/true);
5898
5899       if (arglist == error_mark_node)
5900         /* We were unable to bind the arguments.  */
5901         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5902
5903       /* In the scope of a template class, explicit references to the
5904          template class refer to the type of the template, not any
5905          instantiation of it.  For example, in:
5906
5907            template <class T> class C { void f(C<T>); }
5908
5909          the `C<T>' is just the same as `C'.  Outside of the
5910          class, however, such a reference is an instantiation.  */
5911       if (comp_template_args (TYPE_TI_ARGS (template_type),
5912                               arglist))
5913         {
5914           found = template_type;
5915
5916           if (!entering_scope && PRIMARY_TEMPLATE_P (templ))
5917             {
5918               tree ctx;
5919
5920               for (ctx = current_class_type;
5921                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5922                    ctx = (TYPE_P (ctx)
5923                           ? TYPE_CONTEXT (ctx)
5924                           : DECL_CONTEXT (ctx)))
5925                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5926                   goto found_ctx;
5927
5928               /* We're not in the scope of the class, so the
5929                  TEMPLATE_TYPE is not the type we want after all.  */
5930               found = NULL_TREE;
5931             found_ctx:;
5932             }
5933         }
5934       if (found)
5935         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5936
5937       /* If we already have this specialization, return it.  */
5938       found = retrieve_specialization (templ, arglist,
5939                                        /*class_specializations_p=*/false);
5940       if (found)
5941         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5942
5943       /* This type is a "partial instantiation" if any of the template
5944          arguments still involve template parameters.  Note that we set
5945          IS_PARTIAL_INSTANTIATION for partial specializations as
5946          well.  */
5947       is_partial_instantiation = uses_template_parms (arglist);
5948
5949       /* If the deduced arguments are invalid, then the binding
5950          failed.  */
5951       if (!is_partial_instantiation
5952           && check_instantiated_args (templ,
5953                                       INNERMOST_TEMPLATE_ARGS (arglist),
5954                                       complain))
5955         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5956
5957       if (!is_partial_instantiation
5958           && !PRIMARY_TEMPLATE_P (templ)
5959           && TREE_CODE (CP_DECL_CONTEXT (templ)) == NAMESPACE_DECL)
5960         {
5961           found = xref_tag_from_type (TREE_TYPE (templ),
5962                                       DECL_NAME (templ),
5963                                       /*tag_scope=*/ts_global);
5964           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5965         }
5966
5967       context = tsubst (DECL_CONTEXT (templ), arglist,
5968                         complain, in_decl);
5969       if (!context)
5970         context = global_namespace;
5971
5972       /* Create the type.  */
5973       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5974         {
5975           if (!is_partial_instantiation)
5976             {
5977               set_current_access_from_decl (TYPE_NAME (template_type));
5978               t = start_enum (TYPE_IDENTIFIER (template_type),
5979                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
5980                                       arglist, complain, in_decl),
5981                               SCOPED_ENUM_P (template_type));
5982             }
5983           else
5984             {
5985               /* We don't want to call start_enum for this type, since
5986                  the values for the enumeration constants may involve
5987                  template parameters.  And, no one should be interested
5988                  in the enumeration constants for such a type.  */
5989               t = make_node (ENUMERAL_TYPE);
5990               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
5991             }
5992         }
5993       else
5994         {
5995           t = make_class_type (TREE_CODE (template_type));
5996           CLASSTYPE_DECLARED_CLASS (t)
5997             = CLASSTYPE_DECLARED_CLASS (template_type);
5998           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5999           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6000
6001           /* A local class.  Make sure the decl gets registered properly.  */
6002           if (context == current_function_decl)
6003             pushtag (DECL_NAME (templ), t, /*tag_scope=*/ts_current);
6004
6005           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6006             /* This instantiation is another name for the primary
6007                template type. Set the TYPE_CANONICAL field
6008                appropriately. */
6009             TYPE_CANONICAL (t) = template_type;
6010           else if (any_template_arguments_need_structural_equality_p (arglist))
6011             /* Some of the template arguments require structural
6012                equality testing, so this template class requires
6013                structural equality testing. */
6014             SET_TYPE_STRUCTURAL_EQUALITY (t);
6015         }
6016
6017       /* If we called start_enum or pushtag above, this information
6018          will already be set up.  */
6019       if (!TYPE_NAME (t))
6020         {
6021           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6022
6023           type_decl = create_implicit_typedef (DECL_NAME (templ), t);
6024           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6025           TYPE_STUB_DECL (t) = type_decl;
6026           DECL_SOURCE_LOCATION (type_decl)
6027             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6028         }
6029       else
6030         type_decl = TYPE_NAME (t);
6031
6032       TREE_PRIVATE (type_decl)
6033         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6034       TREE_PROTECTED (type_decl)
6035         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6036       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6037         {
6038           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6039           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6040         }
6041
6042       /* Set up the template information.  We have to figure out which
6043          template is the immediate parent if this is a full
6044          instantiation.  */
6045       if (parm_depth == 1 || is_partial_instantiation
6046           || !PRIMARY_TEMPLATE_P (templ))
6047         /* This case is easy; there are no member templates involved.  */
6048         found = templ;
6049       else
6050         {
6051           /* This is a full instantiation of a member template.  Look
6052              for a partial instantiation of which this is an instance.  */
6053
6054           for (found = DECL_TEMPLATE_INSTANTIATIONS (templ);
6055                found; found = TREE_CHAIN (found))
6056             {
6057               int success;
6058               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
6059
6060               /* We only want partial instantiations, here, not
6061                  specializations or full instantiations.  */
6062               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
6063                   || !uses_template_parms (TREE_VALUE (found)))
6064                 continue;
6065
6066               /* Temporarily reduce by one the number of levels in the
6067                  ARGLIST and in FOUND so as to avoid comparing the
6068                  last set of arguments.  */
6069               TREE_VEC_LENGTH (arglist)--;
6070               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
6071
6072               /* See if the arguments match.  If they do, then TMPL is
6073                  the partial instantiation we want.  */
6074               success = comp_template_args (TREE_PURPOSE (found), arglist);
6075
6076               /* Restore the argument vectors to their full size.  */
6077               TREE_VEC_LENGTH (arglist)++;
6078               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
6079
6080               if (success)
6081                 {
6082                   found = tmpl;
6083                   break;
6084                 }
6085             }
6086
6087           if (!found)
6088             {
6089               /* There was no partial instantiation. This happens
6090                  where C<T> is a member template of A<T> and it's used
6091                  in something like
6092
6093                   template <typename T> struct B { A<T>::C<int> m; };
6094                   B<float>;
6095
6096                  Create the partial instantiation.
6097                */
6098               TREE_VEC_LENGTH (arglist)--;
6099               found = tsubst (templ, arglist, complain, NULL_TREE);
6100               TREE_VEC_LENGTH (arglist)++;
6101             }
6102         }
6103
6104       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6105       DECL_TEMPLATE_INSTANTIATIONS (templ)
6106         = tree_cons (arglist, t,
6107                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6108
6109       if (TREE_CODE (t) == ENUMERAL_TYPE
6110           && !is_partial_instantiation)
6111         /* Now that the type has been registered on the instantiations
6112            list, we set up the enumerators.  Because the enumeration
6113            constants may involve the enumeration type itself, we make
6114            sure to register the type first, and then create the
6115            constants.  That way, doing tsubst_expr for the enumeration
6116            constants won't result in recursive calls here; we'll find
6117            the instantiation and exit above.  */
6118         tsubst_enum (template_type, t, arglist);
6119
6120       if (is_partial_instantiation)
6121         /* If the type makes use of template parameters, the
6122            code that generates debugging information will crash.  */
6123         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6124
6125       /* Possibly limit visibility based on template args.  */
6126       TREE_PUBLIC (type_decl) = 1;
6127       determine_visibility (type_decl);
6128
6129       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6130     }
6131   timevar_pop (TV_NAME_LOOKUP);
6132 }
6133 \f
6134 struct pair_fn_data
6135 {
6136   tree_fn_t fn;
6137   void *data;
6138   /* True when we should also visit template parameters that occur in
6139      non-deduced contexts.  */
6140   bool include_nondeduced_p;
6141   struct pointer_set_t *visited;
6142 };
6143
6144 /* Called from for_each_template_parm via walk_tree.  */
6145
6146 static tree
6147 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6148 {
6149   tree t = *tp;
6150   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6151   tree_fn_t fn = pfd->fn;
6152   void *data = pfd->data;
6153
6154   if (TYPE_P (t)
6155       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6156       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6157                                  pfd->include_nondeduced_p))
6158     return error_mark_node;
6159
6160   switch (TREE_CODE (t))
6161     {
6162     case RECORD_TYPE:
6163       if (TYPE_PTRMEMFUNC_P (t))
6164         break;
6165       /* Fall through.  */
6166
6167     case UNION_TYPE:
6168     case ENUMERAL_TYPE:
6169       if (!TYPE_TEMPLATE_INFO (t))
6170         *walk_subtrees = 0;
6171       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6172                                        fn, data, pfd->visited, 
6173                                        pfd->include_nondeduced_p))
6174         return error_mark_node;
6175       break;
6176
6177     case INTEGER_TYPE:
6178       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6179                                   fn, data, pfd->visited, 
6180                                   pfd->include_nondeduced_p)
6181           || for_each_template_parm (TYPE_MAX_VALUE (t),
6182                                      fn, data, pfd->visited,
6183                                      pfd->include_nondeduced_p))
6184         return error_mark_node;
6185       break;
6186
6187     case METHOD_TYPE:
6188       /* Since we're not going to walk subtrees, we have to do this
6189          explicitly here.  */
6190       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6191                                   pfd->visited, pfd->include_nondeduced_p))
6192         return error_mark_node;
6193       /* Fall through.  */
6194
6195     case FUNCTION_TYPE:
6196       /* Check the return type.  */
6197       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6198                                   pfd->include_nondeduced_p))
6199         return error_mark_node;
6200
6201       /* Check the parameter types.  Since default arguments are not
6202          instantiated until they are needed, the TYPE_ARG_TYPES may
6203          contain expressions that involve template parameters.  But,
6204          no-one should be looking at them yet.  And, once they're
6205          instantiated, they don't contain template parameters, so
6206          there's no point in looking at them then, either.  */
6207       {
6208         tree parm;
6209
6210         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6211           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6212                                       pfd->visited, pfd->include_nondeduced_p))
6213             return error_mark_node;
6214
6215         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6216            want walk_tree walking into them itself.  */
6217         *walk_subtrees = 0;
6218       }
6219       break;
6220
6221     case TYPEOF_TYPE:
6222       if (pfd->include_nondeduced_p
6223           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6224                                      pfd->visited, 
6225                                      pfd->include_nondeduced_p))
6226         return error_mark_node;
6227       break;
6228
6229     case FUNCTION_DECL:
6230     case VAR_DECL:
6231       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6232           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6233                                      pfd->visited, pfd->include_nondeduced_p))
6234         return error_mark_node;
6235       /* Fall through.  */
6236
6237     case PARM_DECL:
6238     case CONST_DECL:
6239       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6240           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6241                                      pfd->visited, pfd->include_nondeduced_p))
6242         return error_mark_node;
6243       if (DECL_CONTEXT (t)
6244           && pfd->include_nondeduced_p
6245           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6246                                      pfd->visited, pfd->include_nondeduced_p))
6247         return error_mark_node;
6248       break;
6249
6250     case BOUND_TEMPLATE_TEMPLATE_PARM:
6251       /* Record template parameters such as `T' inside `TT<T>'.  */
6252       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6253                                   pfd->include_nondeduced_p))
6254         return error_mark_node;
6255       /* Fall through.  */
6256
6257     case TEMPLATE_TEMPLATE_PARM:
6258     case TEMPLATE_TYPE_PARM:
6259     case TEMPLATE_PARM_INDEX:
6260       if (fn && (*fn)(t, data))
6261         return error_mark_node;
6262       else if (!fn)
6263         return error_mark_node;
6264       break;
6265
6266     case TEMPLATE_DECL:
6267       /* A template template parameter is encountered.  */
6268       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6269           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6270                                      pfd->include_nondeduced_p))
6271         return error_mark_node;
6272
6273       /* Already substituted template template parameter */
6274       *walk_subtrees = 0;
6275       break;
6276
6277     case TYPENAME_TYPE:
6278       if (!fn
6279           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6280                                      data, pfd->visited, 
6281                                      pfd->include_nondeduced_p))
6282         return error_mark_node;
6283       break;
6284
6285     case CONSTRUCTOR:
6286       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6287           && pfd->include_nondeduced_p
6288           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6289                                      (TREE_TYPE (t)), fn, data,
6290                                      pfd->visited, pfd->include_nondeduced_p))
6291         return error_mark_node;
6292       break;
6293
6294     case INDIRECT_REF:
6295     case COMPONENT_REF:
6296       /* If there's no type, then this thing must be some expression
6297          involving template parameters.  */
6298       if (!fn && !TREE_TYPE (t))
6299         return error_mark_node;
6300       break;
6301
6302     case MODOP_EXPR:
6303     case CAST_EXPR:
6304     case REINTERPRET_CAST_EXPR:
6305     case CONST_CAST_EXPR:
6306     case STATIC_CAST_EXPR:
6307     case DYNAMIC_CAST_EXPR:
6308     case ARROW_EXPR:
6309     case DOTSTAR_EXPR:
6310     case TYPEID_EXPR:
6311     case PSEUDO_DTOR_EXPR:
6312       if (!fn)
6313         return error_mark_node;
6314       break;
6315
6316     default:
6317       break;
6318     }
6319
6320   /* We didn't find any template parameters we liked.  */
6321   return NULL_TREE;
6322 }
6323
6324 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6325    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6326    call FN with the parameter and the DATA.
6327    If FN returns nonzero, the iteration is terminated, and
6328    for_each_template_parm returns 1.  Otherwise, the iteration
6329    continues.  If FN never returns a nonzero value, the value
6330    returned by for_each_template_parm is 0.  If FN is NULL, it is
6331    considered to be the function which always returns 1.
6332
6333    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6334    parameters that occur in non-deduced contexts.  When false, only
6335    visits those template parameters that can be deduced.  */
6336
6337 static int
6338 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6339                         struct pointer_set_t *visited,
6340                         bool include_nondeduced_p)
6341 {
6342   struct pair_fn_data pfd;
6343   int result;
6344
6345   /* Set up.  */
6346   pfd.fn = fn;
6347   pfd.data = data;
6348   pfd.include_nondeduced_p = include_nondeduced_p;
6349
6350   /* Walk the tree.  (Conceptually, we would like to walk without
6351      duplicates, but for_each_template_parm_r recursively calls
6352      for_each_template_parm, so we would need to reorganize a fair
6353      bit to use walk_tree_without_duplicates, so we keep our own
6354      visited list.)  */
6355   if (visited)
6356     pfd.visited = visited;
6357   else
6358     pfd.visited = pointer_set_create ();
6359   result = cp_walk_tree (&t,
6360                          for_each_template_parm_r,
6361                          &pfd,
6362                          pfd.visited) != NULL_TREE;
6363
6364   /* Clean up.  */
6365   if (!visited)
6366     {
6367       pointer_set_destroy (pfd.visited);
6368       pfd.visited = 0;
6369     }
6370
6371   return result;
6372 }
6373
6374 /* Returns true if T depends on any template parameter.  */
6375
6376 int
6377 uses_template_parms (tree t)
6378 {
6379   bool dependent_p;
6380   int saved_processing_template_decl;
6381
6382   saved_processing_template_decl = processing_template_decl;
6383   if (!saved_processing_template_decl)
6384     processing_template_decl = 1;
6385   if (TYPE_P (t))
6386     dependent_p = dependent_type_p (t);
6387   else if (TREE_CODE (t) == TREE_VEC)
6388     dependent_p = any_dependent_template_arguments_p (t);
6389   else if (TREE_CODE (t) == TREE_LIST)
6390     dependent_p = (uses_template_parms (TREE_VALUE (t))
6391                    || uses_template_parms (TREE_CHAIN (t)));
6392   else if (TREE_CODE (t) == TYPE_DECL)
6393     dependent_p = dependent_type_p (TREE_TYPE (t));
6394   else if (DECL_P (t)
6395            || EXPR_P (t)
6396            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6397            || TREE_CODE (t) == OVERLOAD
6398            || TREE_CODE (t) == BASELINK
6399            || TREE_CODE (t) == IDENTIFIER_NODE
6400            || TREE_CODE (t) == TRAIT_EXPR
6401            || TREE_CODE (t) == CONSTRUCTOR
6402            || CONSTANT_CLASS_P (t))
6403     dependent_p = (type_dependent_expression_p (t)
6404                    || value_dependent_expression_p (t));
6405   else
6406     {
6407       gcc_assert (t == error_mark_node);
6408       dependent_p = false;
6409     }
6410
6411   processing_template_decl = saved_processing_template_decl;
6412
6413   return dependent_p;
6414 }
6415
6416 /* Returns true if T depends on any template parameter with level LEVEL.  */
6417
6418 int
6419 uses_template_parms_level (tree t, int level)
6420 {
6421   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6422                                  /*include_nondeduced_p=*/true);
6423 }
6424
6425 static int tinst_depth;
6426 extern int max_tinst_depth;
6427 #ifdef GATHER_STATISTICS
6428 int depth_reached;
6429 #endif
6430 static int tinst_level_tick;
6431 static int last_template_error_tick;
6432
6433 /* We're starting to instantiate D; record the template instantiation context
6434    for diagnostics and to restore it later.  */
6435
6436 static int
6437 push_tinst_level (tree d)
6438 {
6439   struct tinst_level *new_level;
6440
6441   if (tinst_depth >= max_tinst_depth)
6442     {
6443       /* If the instantiation in question still has unbound template parms,
6444          we don't really care if we can't instantiate it, so just return.
6445          This happens with base instantiation for implicit `typename'.  */
6446       if (uses_template_parms (d))
6447         return 0;
6448
6449       last_template_error_tick = tinst_level_tick;
6450       error ("template instantiation depth exceeds maximum of %d (use "
6451              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6452              max_tinst_depth, d);
6453
6454       print_instantiation_context ();
6455
6456       return 0;
6457     }
6458
6459   new_level = GGC_NEW (struct tinst_level);
6460   new_level->decl = d;
6461   new_level->locus = input_location;
6462   new_level->in_system_header_p = in_system_header;
6463   new_level->next = current_tinst_level;
6464   current_tinst_level = new_level;
6465
6466   ++tinst_depth;
6467 #ifdef GATHER_STATISTICS
6468   if (tinst_depth > depth_reached)
6469     depth_reached = tinst_depth;
6470 #endif
6471
6472   ++tinst_level_tick;
6473   return 1;
6474 }
6475
6476 /* We're done instantiating this template; return to the instantiation
6477    context.  */
6478
6479 static void
6480 pop_tinst_level (void)
6481 {
6482   /* Restore the filename and line number stashed away when we started
6483      this instantiation.  */
6484   input_location = current_tinst_level->locus;
6485   current_tinst_level = current_tinst_level->next;
6486   --tinst_depth;
6487   ++tinst_level_tick;
6488 }
6489
6490 /* We're instantiating a deferred template; restore the template
6491    instantiation context in which the instantiation was requested, which
6492    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6493
6494 static tree
6495 reopen_tinst_level (struct tinst_level *level)
6496 {
6497   struct tinst_level *t;
6498
6499   tinst_depth = 0;
6500   for (t = level; t; t = t->next)
6501     ++tinst_depth;
6502
6503   current_tinst_level = level;
6504   pop_tinst_level ();
6505   return level->decl;
6506 }
6507
6508 /* Returns the TINST_LEVEL which gives the original instantiation
6509    context.  */
6510
6511 struct tinst_level *
6512 outermost_tinst_level (void)
6513 {
6514   struct tinst_level *level = current_tinst_level;
6515   if (level)
6516     while (level->next)
6517       level = level->next;
6518   return level;
6519 }
6520
6521 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6522
6523 bool
6524 parameter_of_template_p (tree parm, tree templ)
6525 {
6526   tree parms;
6527   int i;
6528
6529   if (!parm || !templ)
6530     return false;
6531
6532   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6533   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6534
6535   parms = DECL_TEMPLATE_PARMS (templ);
6536   parms = INNERMOST_TEMPLATE_PARMS (parms);
6537
6538   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6539     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6540       return true;
6541
6542   return false;
6543 }
6544
6545 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6546    vector of template arguments, as for tsubst.
6547
6548    Returns an appropriate tsubst'd friend declaration.  */
6549
6550 static tree
6551 tsubst_friend_function (tree decl, tree args)
6552 {
6553   tree new_friend;
6554
6555   if (TREE_CODE (decl) == FUNCTION_DECL
6556       && DECL_TEMPLATE_INSTANTIATION (decl)
6557       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6558     /* This was a friend declared with an explicit template
6559        argument list, e.g.:
6560
6561        friend void f<>(T);
6562
6563        to indicate that f was a template instantiation, not a new
6564        function declaration.  Now, we have to figure out what
6565        instantiation of what template.  */
6566     {
6567       tree template_id, arglist, fns;
6568       tree new_args;
6569       tree tmpl;
6570       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6571
6572       /* Friend functions are looked up in the containing namespace scope.
6573          We must enter that scope, to avoid finding member functions of the
6574          current class with same name.  */
6575       push_nested_namespace (ns);
6576       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6577                          tf_warning_or_error, NULL_TREE,
6578                          /*integral_constant_expression_p=*/false);
6579       pop_nested_namespace (ns);
6580       arglist = tsubst (DECL_TI_ARGS (decl), args,
6581                         tf_warning_or_error, NULL_TREE);
6582       template_id = lookup_template_function (fns, arglist);
6583
6584       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6585       tmpl = determine_specialization (template_id, new_friend,
6586                                        &new_args,
6587                                        /*need_member_template=*/0,
6588                                        TREE_VEC_LENGTH (args),
6589                                        tsk_none);
6590       return instantiate_template (tmpl, new_args, tf_error);
6591     }
6592
6593   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6594
6595   /* The NEW_FRIEND will look like an instantiation, to the
6596      compiler, but is not an instantiation from the point of view of
6597      the language.  For example, we might have had:
6598
6599      template <class T> struct S {
6600        template <class U> friend void f(T, U);
6601      };
6602
6603      Then, in S<int>, template <class U> void f(int, U) is not an
6604      instantiation of anything.  */
6605   if (new_friend == error_mark_node)
6606     return error_mark_node;
6607
6608   DECL_USE_TEMPLATE (new_friend) = 0;
6609   if (TREE_CODE (decl) == TEMPLATE_DECL)
6610     {
6611       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6612       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6613         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6614     }
6615
6616   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6617      is not a template instantiation and should not be mangled like
6618      one.  Therefore, we forget the mangling here; we'll recompute it
6619      later if we need it.  */
6620   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6621     {
6622       SET_DECL_RTL (new_friend, NULL_RTX);
6623       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6624     }
6625
6626   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6627     {
6628       tree old_decl;
6629       tree new_friend_template_info;
6630       tree new_friend_result_template_info;
6631       tree ns;
6632       int  new_friend_is_defn;
6633
6634       /* We must save some information from NEW_FRIEND before calling
6635          duplicate decls since that function will free NEW_FRIEND if
6636          possible.  */
6637       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6638       new_friend_is_defn =
6639             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6640                            (template_for_substitution (new_friend)))
6641              != NULL_TREE);
6642       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6643         {
6644           /* This declaration is a `primary' template.  */
6645           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6646
6647           new_friend_result_template_info
6648             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6649         }
6650       else
6651         new_friend_result_template_info = NULL_TREE;
6652
6653       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6654       if (new_friend_is_defn)
6655         DECL_INITIAL (new_friend) = error_mark_node;
6656
6657       /* Inside pushdecl_namespace_level, we will push into the
6658          current namespace. However, the friend function should go
6659          into the namespace of the template.  */
6660       ns = decl_namespace_context (new_friend);
6661       push_nested_namespace (ns);
6662       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6663       pop_nested_namespace (ns);
6664
6665       if (old_decl == error_mark_node)
6666         return error_mark_node;
6667
6668       if (old_decl != new_friend)
6669         {
6670           /* This new friend declaration matched an existing
6671              declaration.  For example, given:
6672
6673                template <class T> void f(T);
6674                template <class U> class C {
6675                  template <class T> friend void f(T) {}
6676                };
6677
6678              the friend declaration actually provides the definition
6679              of `f', once C has been instantiated for some type.  So,
6680              old_decl will be the out-of-class template declaration,
6681              while new_friend is the in-class definition.
6682
6683              But, if `f' was called before this point, the
6684              instantiation of `f' will have DECL_TI_ARGS corresponding
6685              to `T' but not to `U', references to which might appear
6686              in the definition of `f'.  Previously, the most general
6687              template for an instantiation of `f' was the out-of-class
6688              version; now it is the in-class version.  Therefore, we
6689              run through all specialization of `f', adding to their
6690              DECL_TI_ARGS appropriately.  In particular, they need a
6691              new set of outer arguments, corresponding to the
6692              arguments for this class instantiation.
6693
6694              The same situation can arise with something like this:
6695
6696                friend void f(int);
6697                template <class T> class C {
6698                  friend void f(T) {}
6699                };
6700
6701              when `C<int>' is instantiated.  Now, `f(int)' is defined
6702              in the class.  */
6703
6704           if (!new_friend_is_defn)
6705             /* On the other hand, if the in-class declaration does
6706                *not* provide a definition, then we don't want to alter
6707                existing definitions.  We can just leave everything
6708                alone.  */
6709             ;
6710           else
6711             {
6712               /* Overwrite whatever template info was there before, if
6713                  any, with the new template information pertaining to
6714                  the declaration.  */
6715               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6716
6717               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6718                 reregister_specialization (new_friend,
6719                                            most_general_template (old_decl),
6720                                            old_decl);
6721               else
6722                 {
6723                   tree t;
6724                   tree new_friend_args;
6725
6726                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6727                     = new_friend_result_template_info;
6728
6729                   new_friend_args = TI_ARGS (new_friend_template_info);
6730                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6731                        t != NULL_TREE;
6732                        t = TREE_CHAIN (t))
6733                     {
6734                       tree spec = TREE_VALUE (t);
6735
6736                       DECL_TI_ARGS (spec)
6737                         = add_outermost_template_args (new_friend_args,
6738                                                        DECL_TI_ARGS (spec));
6739                     }
6740
6741                   /* Now, since specializations are always supposed to
6742                      hang off of the most general template, we must move
6743                      them.  */
6744                   t = most_general_template (old_decl);
6745                   if (t != old_decl)
6746                     {
6747                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6748                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6749                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6750                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6751                     }
6752                 }
6753             }
6754
6755           /* The information from NEW_FRIEND has been merged into OLD_DECL
6756              by duplicate_decls.  */
6757           new_friend = old_decl;
6758         }
6759     }
6760   else
6761     {
6762       tree context = DECL_CONTEXT (new_friend);
6763       bool dependent_p;
6764
6765       /* In the code
6766            template <class T> class C {
6767              template <class U> friend void C1<U>::f (); // case 1
6768              friend void C2<T>::f ();                    // case 2
6769            };
6770          we only need to make sure CONTEXT is a complete type for
6771          case 2.  To distinguish between the two cases, we note that
6772          CONTEXT of case 1 remains dependent type after tsubst while
6773          this isn't true for case 2.  */
6774       ++processing_template_decl;
6775       dependent_p = dependent_type_p (context);
6776       --processing_template_decl;
6777
6778       if (!dependent_p
6779           && !complete_type_or_else (context, NULL_TREE))
6780         return error_mark_node;
6781
6782       if (COMPLETE_TYPE_P (context))
6783         {
6784           /* Check to see that the declaration is really present, and,
6785              possibly obtain an improved declaration.  */
6786           tree fn = check_classfn (context,
6787                                    new_friend, NULL_TREE);
6788
6789           if (fn)
6790             new_friend = fn;
6791         }
6792     }
6793
6794   return new_friend;
6795 }
6796
6797 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6798    template arguments, as for tsubst.
6799
6800    Returns an appropriate tsubst'd friend type or error_mark_node on
6801    failure.  */
6802
6803 static tree
6804 tsubst_friend_class (tree friend_tmpl, tree args)
6805 {
6806   tree friend_type;
6807   tree tmpl;
6808   tree context;
6809
6810   context = DECL_CONTEXT (friend_tmpl);
6811
6812   if (context)
6813     {
6814       if (TREE_CODE (context) == NAMESPACE_DECL)
6815         push_nested_namespace (context);
6816       else
6817         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6818     }
6819
6820   /* Look for a class template declaration.  We look for hidden names
6821      because two friend declarations of the same template are the
6822      same.  For example, in:
6823
6824        struct A { 
6825          template <typename> friend class F;
6826        };
6827        template <typename> struct B { 
6828          template <typename> friend class F;
6829        };
6830
6831      both F templates are the same.  */
6832   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6833                            /*block_p=*/true, 0, 
6834                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6835
6836   /* But, if we don't find one, it might be because we're in a
6837      situation like this:
6838
6839        template <class T>
6840        struct S {
6841          template <class U>
6842          friend struct S;
6843        };
6844
6845      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6846      for `S<int>', not the TEMPLATE_DECL.  */
6847   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6848     {
6849       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6850       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6851     }
6852
6853   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6854     {
6855       /* The friend template has already been declared.  Just
6856          check to see that the declarations match, and install any new
6857          default parameters.  We must tsubst the default parameters,
6858          of course.  We only need the innermost template parameters
6859          because that is all that redeclare_class_template will look
6860          at.  */
6861       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6862           > TMPL_ARGS_DEPTH (args))
6863         {
6864           tree parms;
6865           location_t saved_input_location;
6866           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6867                                          args, tf_warning_or_error);
6868
6869           saved_input_location = input_location;
6870           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6871           redeclare_class_template (TREE_TYPE (tmpl), parms);
6872           input_location = saved_input_location;
6873           
6874         }
6875
6876       friend_type = TREE_TYPE (tmpl);
6877     }
6878   else
6879     {
6880       /* The friend template has not already been declared.  In this
6881          case, the instantiation of the template class will cause the
6882          injection of this template into the global scope.  */
6883       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6884       if (tmpl == error_mark_node)
6885         return error_mark_node;
6886
6887       /* The new TMPL is not an instantiation of anything, so we
6888          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6889          the new type because that is supposed to be the corresponding
6890          template decl, i.e., TMPL.  */
6891       DECL_USE_TEMPLATE (tmpl) = 0;
6892       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6893       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6894       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6895         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6896
6897       /* Inject this template into the global scope.  */
6898       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6899     }
6900
6901   if (context)
6902     {
6903       if (TREE_CODE (context) == NAMESPACE_DECL)
6904         pop_nested_namespace (context);
6905       else
6906         pop_nested_class ();
6907     }
6908
6909   return friend_type;
6910 }
6911
6912 /* Returns zero if TYPE cannot be completed later due to circularity.
6913    Otherwise returns one.  */
6914
6915 static int
6916 can_complete_type_without_circularity (tree type)
6917 {
6918   if (type == NULL_TREE || type == error_mark_node)
6919     return 0;
6920   else if (COMPLETE_TYPE_P (type))
6921     return 1;
6922   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6923     return can_complete_type_without_circularity (TREE_TYPE (type));
6924   else if (CLASS_TYPE_P (type)
6925            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6926     return 0;
6927   else
6928     return 1;
6929 }
6930
6931 /* Apply any attributes which had to be deferred until instantiation
6932    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6933    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6934
6935 static void
6936 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6937                                 tree args, tsubst_flags_t complain, tree in_decl)
6938 {
6939   tree last_dep = NULL_TREE;
6940   tree t;
6941   tree *p;
6942
6943   for (t = attributes; t; t = TREE_CHAIN (t))
6944     if (ATTR_IS_DEPENDENT (t))
6945       {
6946         last_dep = t;
6947         attributes = copy_list (attributes);
6948         break;
6949       }
6950
6951   if (DECL_P (*decl_p))
6952     {
6953       if (TREE_TYPE (*decl_p) == error_mark_node)
6954         return;
6955       p = &DECL_ATTRIBUTES (*decl_p);
6956     }
6957   else
6958     p = &TYPE_ATTRIBUTES (*decl_p);
6959
6960   if (last_dep)
6961     {
6962       tree late_attrs = NULL_TREE;
6963       tree *q = &late_attrs;
6964
6965       for (*p = attributes; *p; )
6966         {
6967           t = *p;
6968           if (ATTR_IS_DEPENDENT (t))
6969             {
6970               *p = TREE_CHAIN (t);
6971               TREE_CHAIN (t) = NULL_TREE;
6972               /* If the first attribute argument is an identifier, don't
6973                  pass it through tsubst.  Attributes like mode, format,
6974                  cleanup and several target specific attributes expect it
6975                  unmodified.  */
6976               if (TREE_VALUE (t)
6977                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
6978                   && TREE_VALUE (TREE_VALUE (t))
6979                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
6980                       == IDENTIFIER_NODE))
6981                 {
6982                   tree chain
6983                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
6984                                    in_decl,
6985                                    /*integral_constant_expression_p=*/false);
6986                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
6987                     TREE_VALUE (t)
6988                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
6989                                    chain);
6990                 }
6991               else
6992                 TREE_VALUE (t)
6993                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6994                                  /*integral_constant_expression_p=*/false);
6995               *q = t;
6996               q = &TREE_CHAIN (t);
6997             }
6998           else
6999             p = &TREE_CHAIN (t);
7000         }
7001
7002       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7003     }
7004 }
7005
7006 tree
7007 instantiate_class_template (tree type)
7008 {
7009   tree templ, args, pattern, t, member;
7010   tree typedecl;
7011   tree pbinfo;
7012   tree base_list;
7013
7014   if (type == error_mark_node)
7015     return error_mark_node;
7016
7017   if (TYPE_BEING_DEFINED (type)
7018       || COMPLETE_TYPE_P (type)
7019       || dependent_type_p (type))
7020     return type;
7021
7022   /* Figure out which template is being instantiated.  */
7023   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7024   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7025
7026   /* Determine what specialization of the original template to
7027      instantiate.  */
7028   t = most_specialized_class (type, templ);
7029   if (t == error_mark_node)
7030     {
7031       TYPE_BEING_DEFINED (type) = 1;
7032       return error_mark_node;
7033     }
7034   else if (t)
7035     {
7036       /* This TYPE is actually an instantiation of a partial
7037          specialization.  We replace the innermost set of ARGS with
7038          the arguments appropriate for substitution.  For example,
7039          given:
7040
7041            template <class T> struct S {};
7042            template <class T> struct S<T*> {};
7043
7044          and supposing that we are instantiating S<int*>, ARGS will
7045          presently be {int*} -- but we need {int}.  */
7046       pattern = TREE_TYPE (t);
7047       args = TREE_PURPOSE (t);
7048     }
7049   else
7050     {
7051       pattern = TREE_TYPE (templ);
7052       args = CLASSTYPE_TI_ARGS (type);
7053     }
7054
7055   /* If the template we're instantiating is incomplete, then clearly
7056      there's nothing we can do.  */
7057   if (!COMPLETE_TYPE_P (pattern))
7058     return type;
7059
7060   /* If we've recursively instantiated too many templates, stop.  */
7061   if (! push_tinst_level (type))
7062     return type;
7063
7064   /* Now we're really doing the instantiation.  Mark the type as in
7065      the process of being defined.  */
7066   TYPE_BEING_DEFINED (type) = 1;
7067
7068   /* We may be in the middle of deferred access check.  Disable
7069      it now.  */
7070   push_deferring_access_checks (dk_no_deferred);
7071
7072   push_to_top_level ();
7073
7074   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7075
7076   /* Set the input location to the template definition. This is needed
7077      if tsubsting causes an error.  */
7078   typedecl = TYPE_MAIN_DECL (type);
7079   input_location = DECL_SOURCE_LOCATION (typedecl);
7080
7081   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7082   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7083   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7084   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7085   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7086   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7087   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7088   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7089   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7090   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7091   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7092   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7093   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7094   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7095   if (ANON_AGGR_TYPE_P (pattern))
7096     SET_ANON_AGGR_TYPE_P (type);
7097   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7098     {
7099       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7100       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7101     }
7102
7103   pbinfo = TYPE_BINFO (pattern);
7104
7105   /* We should never instantiate a nested class before its enclosing
7106      class; we need to look up the nested class by name before we can
7107      instantiate it, and that lookup should instantiate the enclosing
7108      class.  */
7109   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7110               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7111               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7112
7113   base_list = NULL_TREE;
7114   if (BINFO_N_BASE_BINFOS (pbinfo))
7115     {
7116       tree pbase_binfo;
7117       tree context = TYPE_CONTEXT (type);
7118       tree pushed_scope;
7119       int i;
7120
7121       /* We must enter the scope containing the type, as that is where
7122          the accessibility of types named in dependent bases are
7123          looked up from.  */
7124       pushed_scope = push_scope (context ? context : global_namespace);
7125
7126       /* Substitute into each of the bases to determine the actual
7127          basetypes.  */
7128       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7129         {
7130           tree base;
7131           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7132           tree expanded_bases = NULL_TREE;
7133           int idx, len = 1;
7134
7135           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7136             {
7137               expanded_bases = 
7138                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7139                                        args, tf_error, NULL_TREE);
7140               if (expanded_bases == error_mark_node)
7141                 continue;
7142
7143               len = TREE_VEC_LENGTH (expanded_bases);
7144             }
7145
7146           for (idx = 0; idx < len; idx++)
7147             {
7148               if (expanded_bases)
7149                 /* Extract the already-expanded base class.  */
7150                 base = TREE_VEC_ELT (expanded_bases, idx);
7151               else
7152                 /* Substitute to figure out the base class.  */
7153                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7154                                NULL_TREE);
7155
7156               if (base == error_mark_node)
7157                 continue;
7158
7159               base_list = tree_cons (access, base, base_list);
7160               if (BINFO_VIRTUAL_P (pbase_binfo))
7161                 TREE_TYPE (base_list) = integer_type_node;
7162             }
7163         }
7164
7165       /* The list is now in reverse order; correct that.  */
7166       base_list = nreverse (base_list);
7167
7168       if (pushed_scope)
7169         pop_scope (pushed_scope);
7170     }
7171   /* Now call xref_basetypes to set up all the base-class
7172      information.  */
7173   xref_basetypes (type, base_list);
7174
7175   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7176                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7177                                   args, tf_error, NULL_TREE);
7178
7179   /* Now that our base classes are set up, enter the scope of the
7180      class, so that name lookups into base classes, etc. will work
7181      correctly.  This is precisely analogous to what we do in
7182      begin_class_definition when defining an ordinary non-template
7183      class, except we also need to push the enclosing classes.  */
7184   push_nested_class (type);
7185
7186   /* Now members are processed in the order of declaration.  */
7187   for (member = CLASSTYPE_DECL_LIST (pattern);
7188        member; member = TREE_CHAIN (member))
7189     {
7190       tree t = TREE_VALUE (member);
7191
7192       if (TREE_PURPOSE (member))
7193         {
7194           if (TYPE_P (t))
7195             {
7196               /* Build new CLASSTYPE_NESTED_UTDS.  */
7197
7198               tree newtag;
7199               bool class_template_p;
7200
7201               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7202                                   && TYPE_LANG_SPECIFIC (t)
7203                                   && CLASSTYPE_IS_TEMPLATE (t));
7204               /* If the member is a class template, then -- even after
7205                  substitution -- there may be dependent types in the
7206                  template argument list for the class.  We increment
7207                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7208                  that function will assume that no types are dependent
7209                  when outside of a template.  */
7210               if (class_template_p)
7211                 ++processing_template_decl;
7212               newtag = tsubst (t, args, tf_error, NULL_TREE);
7213               if (class_template_p)
7214                 --processing_template_decl;
7215               if (newtag == error_mark_node)
7216                 continue;
7217
7218               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7219                 {
7220                   tree name = TYPE_IDENTIFIER (t);
7221
7222                   if (class_template_p)
7223                     /* Unfortunately, lookup_template_class sets
7224                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7225                        instantiation (i.e., for the type of a member
7226                        template class nested within a template class.)
7227                        This behavior is required for
7228                        maybe_process_partial_specialization to work
7229                        correctly, but is not accurate in this case;
7230                        the TAG is not an instantiation of anything.
7231                        (The corresponding TEMPLATE_DECL is an
7232                        instantiation, but the TYPE is not.) */
7233                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7234
7235                   /* Now, we call pushtag to put this NEWTAG into the scope of
7236                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7237                      pushtag calling push_template_decl.  We don't have to do
7238                      this for enums because it will already have been done in
7239                      tsubst_enum.  */
7240                   if (name)
7241                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7242                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7243                 }
7244             }
7245           else if (TREE_CODE (t) == FUNCTION_DECL
7246                    || DECL_FUNCTION_TEMPLATE_P (t))
7247             {
7248               /* Build new TYPE_METHODS.  */
7249               tree r;
7250
7251               if (TREE_CODE (t) == TEMPLATE_DECL)
7252                 ++processing_template_decl;
7253               r = tsubst (t, args, tf_error, NULL_TREE);
7254               if (TREE_CODE (t) == TEMPLATE_DECL)
7255                 --processing_template_decl;
7256               set_current_access_from_decl (r);
7257               finish_member_declaration (r);
7258             }
7259           else
7260             {
7261               /* Build new TYPE_FIELDS.  */
7262               if (TREE_CODE (t) == STATIC_ASSERT)
7263                 {
7264                   tree condition = 
7265                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7266                                  tf_warning_or_error, NULL_TREE,
7267                                  /*integral_constant_expression_p=*/true);
7268                   finish_static_assert (condition,
7269                                         STATIC_ASSERT_MESSAGE (t), 
7270                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7271                                         /*member_p=*/true);
7272                 }
7273               else if (TREE_CODE (t) != CONST_DECL)
7274                 {
7275                   tree r;
7276
7277                   /* The file and line for this declaration, to
7278                      assist in error message reporting.  Since we
7279                      called push_tinst_level above, we don't need to
7280                      restore these.  */
7281                   input_location = DECL_SOURCE_LOCATION (t);
7282
7283                   if (TREE_CODE (t) == TEMPLATE_DECL)
7284                     ++processing_template_decl;
7285                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7286                   if (TREE_CODE (t) == TEMPLATE_DECL)
7287                     --processing_template_decl;
7288                   if (TREE_CODE (r) == VAR_DECL)
7289                     {
7290                       /* In [temp.inst]:
7291
7292                            [t]he initialization (and any associated
7293                            side-effects) of a static data member does
7294                            not occur unless the static data member is
7295                            itself used in a way that requires the
7296                            definition of the static data member to
7297                            exist.
7298
7299                          Therefore, we do not substitute into the
7300                          initialized for the static data member here.  */
7301                       finish_static_data_member_decl
7302                         (r,
7303                          /*init=*/NULL_TREE,
7304                          /*init_const_expr_p=*/false,
7305                          /*asmspec_tree=*/NULL_TREE,
7306                          /*flags=*/0);
7307                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7308                         check_static_variable_definition (r, TREE_TYPE (r));
7309                     }
7310                   else if (TREE_CODE (r) == FIELD_DECL)
7311                     {
7312                       /* Determine whether R has a valid type and can be
7313                          completed later.  If R is invalid, then it is
7314                          replaced by error_mark_node so that it will not be
7315                          added to TYPE_FIELDS.  */
7316                       tree rtype = TREE_TYPE (r);
7317                       if (can_complete_type_without_circularity (rtype))
7318                         complete_type (rtype);
7319
7320                       if (!COMPLETE_TYPE_P (rtype))
7321                         {
7322                           cxx_incomplete_type_error (r, rtype);
7323                           r = error_mark_node;
7324                         }
7325                     }
7326
7327                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7328                      such a thing will already have been added to the field
7329                      list by tsubst_enum in finish_member_declaration in the
7330                      CLASSTYPE_NESTED_UTDS case above.  */
7331                   if (!(TREE_CODE (r) == TYPE_DECL
7332                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7333                         && DECL_ARTIFICIAL (r)))
7334                     {
7335                       set_current_access_from_decl (r);
7336                       finish_member_declaration (r);
7337                     }
7338                 }
7339             }
7340         }
7341       else
7342         {
7343           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7344             {
7345               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7346
7347               tree friend_type = t;
7348               bool adjust_processing_template_decl = false;
7349
7350               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7351                 {
7352                   /* template <class T> friend class C;  */
7353                   friend_type = tsubst_friend_class (friend_type, args);
7354                   adjust_processing_template_decl = true;
7355                 }
7356               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7357                 {
7358                   /* template <class T> friend class C::D;  */
7359                   friend_type = tsubst (friend_type, args,
7360                                         tf_warning_or_error, NULL_TREE);
7361                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7362                     friend_type = TREE_TYPE (friend_type);
7363                   adjust_processing_template_decl = true;
7364                 }
7365               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7366                 {
7367                   /* This could be either
7368
7369                        friend class T::C;
7370
7371                      when dependent_type_p is false or
7372
7373                        template <class U> friend class T::C;
7374
7375                      otherwise.  */
7376                   friend_type = tsubst (friend_type, args,
7377                                         tf_warning_or_error, NULL_TREE);
7378                   /* Bump processing_template_decl for correct
7379                      dependent_type_p calculation.  */
7380                   ++processing_template_decl;
7381                   if (dependent_type_p (friend_type))
7382                     adjust_processing_template_decl = true;
7383                   --processing_template_decl;
7384                 }
7385               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7386                        && hidden_name_p (TYPE_NAME (friend_type)))
7387                 {
7388                   /* friend class C;
7389
7390                      where C hasn't been declared yet.  Let's lookup name
7391                      from namespace scope directly, bypassing any name that
7392                      come from dependent base class.  */
7393                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7394
7395                   /* The call to xref_tag_from_type does injection for friend
7396                      classes.  */
7397                   push_nested_namespace (ns);
7398                   friend_type =
7399                     xref_tag_from_type (friend_type, NULL_TREE,
7400                                         /*tag_scope=*/ts_current);
7401                   pop_nested_namespace (ns);
7402                 }
7403               else if (uses_template_parms (friend_type))
7404                 /* friend class C<T>;  */
7405                 friend_type = tsubst (friend_type, args,
7406                                       tf_warning_or_error, NULL_TREE);
7407               /* Otherwise it's
7408
7409                    friend class C;
7410
7411                  where C is already declared or
7412
7413                    friend class C<int>;
7414
7415                  We don't have to do anything in these cases.  */
7416
7417               if (adjust_processing_template_decl)
7418                 /* Trick make_friend_class into realizing that the friend
7419                    we're adding is a template, not an ordinary class.  It's
7420                    important that we use make_friend_class since it will
7421                    perform some error-checking and output cross-reference
7422                    information.  */
7423                 ++processing_template_decl;
7424
7425               if (friend_type != error_mark_node)
7426                 make_friend_class (type, friend_type, /*complain=*/false);
7427
7428               if (adjust_processing_template_decl)
7429                 --processing_template_decl;
7430             }
7431           else
7432             {
7433               /* Build new DECL_FRIENDLIST.  */
7434               tree r;
7435
7436               /* The file and line for this declaration, to
7437                  assist in error message reporting.  Since we
7438                  called push_tinst_level above, we don't need to
7439                  restore these.  */
7440               input_location = DECL_SOURCE_LOCATION (t);
7441
7442               if (TREE_CODE (t) == TEMPLATE_DECL)
7443                 {
7444                   ++processing_template_decl;
7445                   push_deferring_access_checks (dk_no_check);
7446                 }
7447
7448               r = tsubst_friend_function (t, args);
7449               add_friend (type, r, /*complain=*/false);
7450               if (TREE_CODE (t) == TEMPLATE_DECL)
7451                 {
7452                   pop_deferring_access_checks ();
7453                   --processing_template_decl;
7454                 }
7455             }
7456         }
7457     }
7458
7459   /* Set the file and line number information to whatever is given for
7460      the class itself.  This puts error messages involving generated
7461      implicit functions at a predictable point, and the same point
7462      that would be used for non-template classes.  */
7463   input_location = DECL_SOURCE_LOCATION (typedecl);
7464
7465   unreverse_member_declarations (type);
7466   finish_struct_1 (type);
7467   TYPE_BEING_DEFINED (type) = 0;
7468
7469   /* Now that the class is complete, instantiate default arguments for
7470      any member functions.  We don't do this earlier because the
7471      default arguments may reference members of the class.  */
7472   if (!PRIMARY_TEMPLATE_P (templ))
7473     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7474       if (TREE_CODE (t) == FUNCTION_DECL
7475           /* Implicitly generated member functions will not have template
7476              information; they are not instantiations, but instead are
7477              created "fresh" for each instantiation.  */
7478           && DECL_TEMPLATE_INFO (t))
7479         tsubst_default_arguments (t);
7480
7481   pop_nested_class ();
7482   pop_from_top_level ();
7483   pop_deferring_access_checks ();
7484   pop_tinst_level ();
7485
7486   /* The vtable for a template class can be emitted in any translation
7487      unit in which the class is instantiated.  When there is no key
7488      method, however, finish_struct_1 will already have added TYPE to
7489      the keyed_classes list.  */
7490   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7491     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7492
7493   return type;
7494 }
7495
7496 static tree
7497 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7498 {
7499   tree r;
7500
7501   if (!t)
7502     r = t;
7503   else if (TYPE_P (t))
7504     r = tsubst (t, args, complain, in_decl);
7505   else
7506     {
7507       r = tsubst_expr (t, args, complain, in_decl,
7508                        /*integral_constant_expression_p=*/true);
7509       r = fold_non_dependent_expr (r);
7510     }
7511   return r;
7512 }
7513
7514 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7515    NONTYPE_ARGUMENT_PACK.  */
7516
7517 static tree
7518 make_fnparm_pack (tree spec_parm)
7519 {
7520   /* Collect all of the extra "packed" parameters into an
7521      argument pack.  */
7522   tree parmvec;
7523   tree parmtypevec;
7524   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7525   tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
7526   int i, len = list_length (spec_parm);
7527
7528   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7529   parmvec = make_tree_vec (len);
7530   parmtypevec = make_tree_vec (len);
7531   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7532     {
7533       TREE_VEC_ELT (parmvec, i) = spec_parm;
7534       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7535     }
7536
7537   /* Build the argument packs.  */
7538   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7539   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7540   TREE_TYPE (argpack) = argtypepack;
7541
7542   return argpack;
7543 }        
7544
7545 /* Substitute ARGS into T, which is an pack expansion
7546    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7547    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7548    (if only a partial substitution could be performed) or
7549    ERROR_MARK_NODE if there was an error.  */
7550 tree
7551 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7552                        tree in_decl)
7553 {
7554   tree pattern;
7555   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7556   tree first_arg_pack; int i, len = -1;
7557   tree result;
7558   int incomplete = 0;
7559   bool very_local_specializations = false;
7560
7561   gcc_assert (PACK_EXPANSION_P (t));
7562   pattern = PACK_EXPANSION_PATTERN (t);
7563
7564   /* Determine the argument packs that will instantiate the parameter
7565      packs used in the expansion expression. While we're at it,
7566      compute the number of arguments to be expanded and make sure it
7567      is consistent.  */
7568   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7569        pack = TREE_CHAIN (pack))
7570     {
7571       tree parm_pack = TREE_VALUE (pack);
7572       tree arg_pack = NULL_TREE;
7573       tree orig_arg = NULL_TREE;
7574
7575       if (TREE_CODE (parm_pack) == PARM_DECL)
7576         {
7577           arg_pack = retrieve_local_specialization (parm_pack);
7578           if (arg_pack == NULL_TREE)
7579             {
7580               /* This can happen for a parameter name used later in a function
7581                  declaration (such as in a late-specified return type).  Just
7582                  make a dummy decl, since it's only used for its type.  */
7583               gcc_assert (skip_evaluation);
7584               arg_pack = tsubst_decl (parm_pack, args, complain);
7585               arg_pack = make_fnparm_pack (arg_pack);
7586             }
7587         }
7588       else
7589         {
7590           int level, idx, levels;
7591           template_parm_level_and_index (parm_pack, &level, &idx);
7592
7593           levels = TMPL_ARGS_DEPTH (args);
7594           if (level <= levels)
7595             arg_pack = TMPL_ARG (args, level, idx);
7596         }
7597
7598       orig_arg = arg_pack;
7599       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7600         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7601       
7602       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7603         /* This can only happen if we forget to expand an argument
7604            pack somewhere else. Just return an error, silently.  */
7605         {
7606           result = make_tree_vec (1);
7607           TREE_VEC_ELT (result, 0) = error_mark_node;
7608           return result;
7609         }
7610
7611       if (arg_pack
7612           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7613           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7614         {
7615           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7616           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7617           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7618               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7619             /* The argument pack that the parameter maps to is just an
7620                expansion of the parameter itself, such as one would
7621                find in the implicit typedef of a class inside the
7622                class itself.  Consider this parameter "unsubstituted",
7623                so that we will maintain the outer pack expansion.  */
7624             arg_pack = NULL_TREE;
7625         }
7626           
7627       if (arg_pack)
7628         {
7629           int my_len = 
7630             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7631
7632           /* It's all-or-nothing with incomplete argument packs.  */
7633           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7634             return error_mark_node;
7635           
7636           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7637             incomplete = 1;
7638
7639           if (len < 0)
7640             {
7641               len = my_len;
7642               first_arg_pack = arg_pack;
7643             }
7644           else if (len != my_len)
7645             {
7646               if (incomplete)
7647                 /* We got explicit args for some packs but not others;
7648                    do nothing now and try again after deduction.  */
7649                 return t;
7650               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7651                 error ("mismatched argument pack lengths while expanding "
7652                        "%<%T%>",
7653                        pattern);
7654               else
7655                 error ("mismatched argument pack lengths while expanding "
7656                        "%<%E%>",
7657                        pattern);
7658               return error_mark_node;
7659             }
7660
7661           /* Keep track of the parameter packs and their corresponding
7662              argument packs.  */
7663           packs = tree_cons (parm_pack, arg_pack, packs);
7664           TREE_TYPE (packs) = orig_arg;
7665         }
7666       else
7667         /* We can't substitute for this parameter pack.  */
7668         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7669                                          TREE_VALUE (pack),
7670                                          unsubstituted_packs);
7671     }
7672
7673   /* We cannot expand this expansion expression, because we don't have
7674      all of the argument packs we need. Substitute into the pattern
7675      and return a PACK_EXPANSION_*. The caller will need to deal with
7676      that.  */
7677   if (unsubstituted_packs)
7678     {
7679       tree new_pat;
7680       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7681         new_pat = tsubst_expr (pattern, args, complain, in_decl,
7682                                /*integral_constant_expression_p=*/false);
7683       else
7684         new_pat = tsubst (pattern, args, complain, in_decl);
7685       return make_pack_expansion (new_pat);
7686     }
7687
7688   /* We could not find any argument packs that work.  */
7689   if (len < 0)
7690     return error_mark_node;
7691
7692   if (!local_specializations)
7693     {
7694       /* We're in a late-specified return type, so we don't have a local
7695          specializations table.  Create one for doing this expansion.  */
7696       very_local_specializations = true;
7697       local_specializations = htab_create (37,
7698                                            hash_local_specialization,
7699                                            eq_local_specializations,
7700                                            NULL);
7701     }
7702
7703   /* For each argument in each argument pack, substitute into the
7704      pattern.  */
7705   result = make_tree_vec (len + incomplete);
7706   for (i = 0; i < len + incomplete; ++i)
7707     {
7708       /* For parameter pack, change the substitution of the parameter
7709          pack to the ith argument in its argument pack, then expand
7710          the pattern.  */
7711       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7712         {
7713           tree parm = TREE_PURPOSE (pack);
7714
7715           if (TREE_CODE (parm) == PARM_DECL)
7716             {
7717               /* Select the Ith argument from the pack.  */
7718               tree arg = make_node (ARGUMENT_PACK_SELECT);
7719               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7720               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7721               mark_used (parm);
7722               register_local_specialization (arg, parm);
7723             }
7724           else
7725             {
7726               tree value = parm;
7727               int idx, level;
7728               template_parm_level_and_index (parm, &level, &idx);
7729               
7730               if (i < len) 
7731                 {
7732                   /* Select the Ith argument from the pack. */
7733                   value = make_node (ARGUMENT_PACK_SELECT);
7734                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7735                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7736                 }
7737
7738               /* Update the corresponding argument.  */
7739               TMPL_ARG (args, level, idx) = value;
7740             }
7741         }
7742
7743       /* Substitute into the PATTERN with the altered arguments.  */
7744       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7745         TREE_VEC_ELT (result, i) = 
7746           tsubst_expr (pattern, args, complain, in_decl,
7747                        /*integral_constant_expression_p=*/false);
7748       else
7749         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7750
7751       if (i == len)
7752         /* When we have incomplete argument packs, the last "expanded"
7753            result is itself a pack expansion, which allows us
7754            to deduce more arguments.  */
7755         TREE_VEC_ELT (result, i) = 
7756           make_pack_expansion (TREE_VEC_ELT (result, i));
7757
7758       if (TREE_VEC_ELT (result, i) == error_mark_node)
7759         {
7760           result = error_mark_node;
7761           break;
7762         }
7763     }
7764
7765   /* Update ARGS to restore the substitution from parameter packs to
7766      their argument packs.  */
7767   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7768     {
7769       tree parm = TREE_PURPOSE (pack);
7770
7771       if (TREE_CODE (parm) == PARM_DECL)
7772         register_local_specialization (TREE_TYPE (pack), parm);
7773       else
7774         {
7775           int idx, level;
7776           template_parm_level_and_index (parm, &level, &idx);
7777           
7778           /* Update the corresponding argument.  */
7779           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7780             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7781               TREE_TYPE (pack);
7782           else
7783             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7784         }
7785     }
7786
7787   if (very_local_specializations)
7788     {
7789       htab_delete (local_specializations);
7790       local_specializations = NULL;
7791     }
7792   
7793   return result;
7794 }
7795
7796 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
7797    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
7798    parameter packs; all parms generated from a function parameter pack will
7799    have the same DECL_PARM_INDEX.  */
7800
7801 tree
7802 get_pattern_parm (tree parm, tree tmpl)
7803 {
7804   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
7805   tree patparm;
7806
7807   if (DECL_ARTIFICIAL (parm))
7808     {
7809       for (patparm = DECL_ARGUMENTS (pattern);
7810            patparm; patparm = TREE_CHAIN (patparm))
7811         if (DECL_ARTIFICIAL (patparm)
7812             && DECL_NAME (parm) == DECL_NAME (patparm))
7813           break;
7814     }
7815   else
7816     {
7817       for (patparm = FUNCTION_FIRST_USER_PARM (pattern);
7818            patparm; patparm = TREE_CHAIN (patparm))
7819         {
7820           if (DECL_NAME (patparm) == DECL_NAME (parm))
7821             break;
7822           if (FUNCTION_PARAMETER_PACK_P (patparm)
7823               /* OK, this is a hack. We know that if PARAM_DECL is expanded
7824                  from PACK, its name (built with make_ith_pack_parameter_name)
7825                  is the string "<foo>#N" where <foo> is the name of PACK
7826                  and N is a number.
7827                  So we just check that naming pattern.  */
7828               && (IDENTIFIER_LENGTH (DECL_NAME (patparm))
7829                   < IDENTIFIER_LENGTH (DECL_NAME (parm)))
7830               && ! strncmp (IDENTIFIER_POINTER (DECL_NAME (parm)),
7831                             IDENTIFIER_POINTER (DECL_NAME (patparm)),
7832                             IDENTIFIER_LENGTH (DECL_NAME (patparm)))
7833               && (IDENTIFIER_POINTER (DECL_NAME (parm))
7834                   [IDENTIFIER_LENGTH (DECL_NAME (patparm))]
7835                   == '#'))
7836             break;
7837         }
7838     }
7839
7840   return patparm;
7841 }
7842
7843 /* Substitute ARGS into the vector or list of template arguments T.  */
7844
7845 static tree
7846 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7847 {
7848   tree orig_t = t;
7849   int len = TREE_VEC_LENGTH (t);
7850   int need_new = 0, i, expanded_len_adjust = 0, out;
7851   tree *elts = (tree *) alloca (len * sizeof (tree));
7852
7853   for (i = 0; i < len; i++)
7854     {
7855       tree orig_arg = TREE_VEC_ELT (t, i);
7856       tree new_arg;
7857
7858       if (TREE_CODE (orig_arg) == TREE_VEC)
7859         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7860       else if (PACK_EXPANSION_P (orig_arg))
7861         {
7862           /* Substitute into an expansion expression.  */
7863           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7864
7865           if (TREE_CODE (new_arg) == TREE_VEC)
7866             /* Add to the expanded length adjustment the number of
7867                expanded arguments. We subtract one from this
7868                measurement, because the argument pack expression
7869                itself is already counted as 1 in
7870                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7871                the argument pack is empty.  */
7872             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7873         }
7874       else if (ARGUMENT_PACK_P (orig_arg))
7875         {
7876           /* Substitute into each of the arguments.  */
7877           new_arg = make_node (TREE_CODE (orig_arg));
7878           
7879           SET_ARGUMENT_PACK_ARGS (
7880             new_arg,
7881             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7882                                   args, complain, in_decl));
7883
7884           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7885             new_arg = error_mark_node;
7886
7887           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7888             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7889                                           complain, in_decl);
7890             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7891
7892             if (TREE_TYPE (new_arg) == error_mark_node)
7893               new_arg = error_mark_node;
7894           }
7895         }
7896       else
7897         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7898
7899       if (new_arg == error_mark_node)
7900         return error_mark_node;
7901
7902       elts[i] = new_arg;
7903       if (new_arg != orig_arg)
7904         need_new = 1;
7905     }
7906
7907   if (!need_new)
7908     return t;
7909
7910   /* Make space for the expanded arguments coming from template
7911      argument packs.  */
7912   t = make_tree_vec (len + expanded_len_adjust);
7913   for (i = 0, out = 0; i < len; i++)
7914     {
7915       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7916            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7917           && TREE_CODE (elts[i]) == TREE_VEC)
7918         {
7919           int idx;
7920
7921           /* Now expand the template argument pack "in place".  */
7922           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7923             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7924         }
7925       else
7926         {
7927           TREE_VEC_ELT (t, out) = elts[i];
7928           out++;
7929         }
7930     }
7931
7932   return t;
7933 }
7934
7935 /* Return the result of substituting ARGS into the template parameters
7936    given by PARMS.  If there are m levels of ARGS and m + n levels of
7937    PARMS, then the result will contain n levels of PARMS.  For
7938    example, if PARMS is `template <class T> template <class U>
7939    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7940    result will be `template <int*, double, class V>'.  */
7941
7942 static tree
7943 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7944 {
7945   tree r = NULL_TREE;
7946   tree* new_parms;
7947
7948   /* When substituting into a template, we must set
7949      PROCESSING_TEMPLATE_DECL as the template parameters may be
7950      dependent if they are based on one-another, and the dependency
7951      predicates are short-circuit outside of templates.  */
7952   ++processing_template_decl;
7953
7954   for (new_parms = &r;
7955        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7956        new_parms = &(TREE_CHAIN (*new_parms)),
7957          parms = TREE_CHAIN (parms))
7958     {
7959       tree new_vec =
7960         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7961       int i;
7962
7963       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7964         {
7965           tree tuple;
7966           tree default_value;
7967           tree parm_decl;
7968
7969           if (parms == error_mark_node)
7970             continue;
7971
7972           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7973
7974           if (tuple == error_mark_node)
7975             continue;
7976
7977           default_value = TREE_PURPOSE (tuple);
7978           parm_decl = TREE_VALUE (tuple);
7979
7980           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7981           if (TREE_CODE (parm_decl) == PARM_DECL
7982               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7983             parm_decl = error_mark_node;
7984           default_value = tsubst_template_arg (default_value, args,
7985                                                complain, NULL_TREE);
7986
7987           tuple = build_tree_list (default_value, parm_decl);
7988           TREE_VEC_ELT (new_vec, i) = tuple;
7989         }
7990
7991       *new_parms =
7992         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7993                              - TMPL_ARGS_DEPTH (args)),
7994                    new_vec, NULL_TREE);
7995     }
7996
7997   --processing_template_decl;
7998
7999   return r;
8000 }
8001
8002 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8003    type T.  If T is not an aggregate or enumeration type, it is
8004    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8005    ENTERING_SCOPE is nonzero, T is the context for a template which
8006    we are presently tsubst'ing.  Return the substituted value.  */
8007
8008 static tree
8009 tsubst_aggr_type (tree t,
8010                   tree args,
8011                   tsubst_flags_t complain,
8012                   tree in_decl,
8013                   int entering_scope)
8014 {
8015   if (t == NULL_TREE)
8016     return NULL_TREE;
8017
8018   switch (TREE_CODE (t))
8019     {
8020     case RECORD_TYPE:
8021       if (TYPE_PTRMEMFUNC_P (t))
8022         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8023
8024       /* Else fall through.  */
8025     case ENUMERAL_TYPE:
8026     case UNION_TYPE:
8027       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8028         {
8029           tree argvec;
8030           tree context;
8031           tree r;
8032           bool saved_skip_evaluation;
8033
8034           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8035           saved_skip_evaluation = skip_evaluation;
8036           skip_evaluation = false;
8037
8038           /* First, determine the context for the type we are looking
8039              up.  */
8040           context = TYPE_CONTEXT (t);
8041           if (context)
8042             {
8043               context = tsubst_aggr_type (context, args, complain,
8044                                           in_decl, /*entering_scope=*/1);
8045               /* If context is a nested class inside a class template,
8046                  it may still need to be instantiated (c++/33959).  */
8047               if (TYPE_P (context))
8048                 context = complete_type (context);
8049             }
8050
8051           /* Then, figure out what arguments are appropriate for the
8052              type we are trying to find.  For example, given:
8053
8054                template <class T> struct S;
8055                template <class T, class U> void f(T, U) { S<U> su; }
8056
8057              and supposing that we are instantiating f<int, double>,
8058              then our ARGS will be {int, double}, but, when looking up
8059              S we only want {double}.  */
8060           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8061                                          complain, in_decl);
8062           if (argvec == error_mark_node)
8063             r = error_mark_node;
8064           else
8065             {
8066               r = lookup_template_class (t, argvec, in_decl, context,
8067                                          entering_scope, complain);
8068               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8069             }
8070
8071           skip_evaluation = saved_skip_evaluation;
8072
8073           return r;
8074         }
8075       else
8076         /* This is not a template type, so there's nothing to do.  */
8077         return t;
8078
8079     default:
8080       return tsubst (t, args, complain, in_decl);
8081     }
8082 }
8083
8084 /* Substitute into the default argument ARG (a default argument for
8085    FN), which has the indicated TYPE.  */
8086
8087 tree
8088 tsubst_default_argument (tree fn, tree type, tree arg)
8089 {
8090   tree saved_class_ptr = NULL_TREE;
8091   tree saved_class_ref = NULL_TREE;
8092
8093   /* This default argument came from a template.  Instantiate the
8094      default argument here, not in tsubst.  In the case of
8095      something like:
8096
8097        template <class T>
8098        struct S {
8099          static T t();
8100          void f(T = t());
8101        };
8102
8103      we must be careful to do name lookup in the scope of S<T>,
8104      rather than in the current class.  */
8105   push_access_scope (fn);
8106   /* The "this" pointer is not valid in a default argument.  */
8107   if (cfun)
8108     {
8109       saved_class_ptr = current_class_ptr;
8110       cp_function_chain->x_current_class_ptr = NULL_TREE;
8111       saved_class_ref = current_class_ref;
8112       cp_function_chain->x_current_class_ref = NULL_TREE;
8113     }
8114
8115   push_deferring_access_checks(dk_no_deferred);
8116   /* The default argument expression may cause implicitly defined
8117      member functions to be synthesized, which will result in garbage
8118      collection.  We must treat this situation as if we were within
8119      the body of function so as to avoid collecting live data on the
8120      stack.  */
8121   ++function_depth;
8122   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8123                      tf_warning_or_error, NULL_TREE,
8124                      /*integral_constant_expression_p=*/false);
8125   --function_depth;
8126   pop_deferring_access_checks();
8127
8128   /* Restore the "this" pointer.  */
8129   if (cfun)
8130     {
8131       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8132       cp_function_chain->x_current_class_ref = saved_class_ref;
8133     }
8134
8135   /* Make sure the default argument is reasonable.  */
8136   arg = check_default_argument (type, arg);
8137
8138   pop_access_scope (fn);
8139
8140   return arg;
8141 }
8142
8143 /* Substitute into all the default arguments for FN.  */
8144
8145 static void
8146 tsubst_default_arguments (tree fn)
8147 {
8148   tree arg;
8149   tree tmpl_args;
8150
8151   tmpl_args = DECL_TI_ARGS (fn);
8152
8153   /* If this function is not yet instantiated, we certainly don't need
8154      its default arguments.  */
8155   if (uses_template_parms (tmpl_args))
8156     return;
8157
8158   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8159        arg;
8160        arg = TREE_CHAIN (arg))
8161     if (TREE_PURPOSE (arg))
8162       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8163                                                     TREE_VALUE (arg),
8164                                                     TREE_PURPOSE (arg));
8165 }
8166
8167 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8168    result of the substitution.  Issue error and warning messages under
8169    control of COMPLAIN.  */
8170
8171 static tree
8172 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8173 {
8174   location_t saved_loc;
8175   tree r = NULL_TREE;
8176   tree in_decl = t;
8177
8178   /* Set the filename and linenumber to improve error-reporting.  */
8179   saved_loc = input_location;
8180   input_location = DECL_SOURCE_LOCATION (t);
8181
8182   switch (TREE_CODE (t))
8183     {
8184     case TEMPLATE_DECL:
8185       {
8186         /* We can get here when processing a member function template,
8187            member class template, or template template parameter.  */
8188         tree decl = DECL_TEMPLATE_RESULT (t);
8189         tree spec;
8190         tree tmpl_args;
8191         tree full_args;
8192
8193         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8194           {
8195             /* Template template parameter is treated here.  */
8196             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8197             if (new_type == error_mark_node)
8198               return error_mark_node;
8199
8200             r = copy_decl (t);
8201             TREE_CHAIN (r) = NULL_TREE;
8202             TREE_TYPE (r) = new_type;
8203             DECL_TEMPLATE_RESULT (r)
8204               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
8205             DECL_TEMPLATE_PARMS (r)
8206               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8207                                        complain);
8208             TYPE_NAME (new_type) = r;
8209             break;
8210           }
8211
8212         /* We might already have an instance of this template.
8213            The ARGS are for the surrounding class type, so the
8214            full args contain the tsubst'd args for the context,
8215            plus the innermost args from the template decl.  */
8216         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8217           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8218           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8219         /* Because this is a template, the arguments will still be
8220            dependent, even after substitution.  If
8221            PROCESSING_TEMPLATE_DECL is not set, the dependency
8222            predicates will short-circuit.  */
8223         ++processing_template_decl;
8224         full_args = tsubst_template_args (tmpl_args, args,
8225                                           complain, in_decl);
8226         --processing_template_decl;
8227         if (full_args == error_mark_node)
8228           return error_mark_node;
8229
8230         /* If this is a default template template argument,
8231            tsubst might not have changed anything.  */
8232         if (full_args == tmpl_args)
8233           return t;
8234
8235         spec = retrieve_specialization (t, full_args,
8236                                         /*class_specializations_p=*/true);
8237         if (spec != NULL_TREE)
8238           {
8239             r = spec;
8240             break;
8241           }
8242
8243         /* Make a new template decl.  It will be similar to the
8244            original, but will record the current template arguments.
8245            We also create a new function declaration, which is just
8246            like the old one, but points to this new template, rather
8247            than the old one.  */
8248         r = copy_decl (t);
8249         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8250         TREE_CHAIN (r) = NULL_TREE;
8251
8252         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8253
8254         if (TREE_CODE (decl) == TYPE_DECL)
8255           {
8256             tree new_type;
8257             ++processing_template_decl;
8258             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8259             --processing_template_decl;
8260             if (new_type == error_mark_node)
8261               return error_mark_node;
8262
8263             TREE_TYPE (r) = new_type;
8264             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8265             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8266             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8267             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8268           }
8269         else
8270           {
8271             tree new_decl;
8272             ++processing_template_decl;
8273             new_decl = tsubst (decl, args, complain, in_decl);
8274             --processing_template_decl;
8275             if (new_decl == error_mark_node)
8276               return error_mark_node;
8277
8278             DECL_TEMPLATE_RESULT (r) = new_decl;
8279             DECL_TI_TEMPLATE (new_decl) = r;
8280             TREE_TYPE (r) = TREE_TYPE (new_decl);
8281             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8282             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8283           }
8284
8285         SET_DECL_IMPLICIT_INSTANTIATION (r);
8286         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8287         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8288
8289         /* The template parameters for this new template are all the
8290            template parameters for the old template, except the
8291            outermost level of parameters.  */
8292         DECL_TEMPLATE_PARMS (r)
8293           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8294                                    complain);
8295
8296         if (PRIMARY_TEMPLATE_P (t))
8297           DECL_PRIMARY_TEMPLATE (r) = r;
8298
8299         if (TREE_CODE (decl) != TYPE_DECL)
8300           /* Record this non-type partial instantiation.  */
8301           register_specialization (r, t,
8302                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8303                                    false);
8304       }
8305       break;
8306
8307     case FUNCTION_DECL:
8308       {
8309         tree ctx;
8310         tree argvec = NULL_TREE;
8311         tree *friends;
8312         tree gen_tmpl;
8313         tree type;
8314         int member;
8315         int args_depth;
8316         int parms_depth;
8317
8318         /* Nobody should be tsubst'ing into non-template functions.  */
8319         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8320
8321         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8322           {
8323             tree spec;
8324             bool dependent_p;
8325
8326             /* If T is not dependent, just return it.  We have to
8327                increment PROCESSING_TEMPLATE_DECL because
8328                value_dependent_expression_p assumes that nothing is
8329                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8330             ++processing_template_decl;
8331             dependent_p = value_dependent_expression_p (t);
8332             --processing_template_decl;
8333             if (!dependent_p)
8334               return t;
8335
8336             /* Calculate the most general template of which R is a
8337                specialization, and the complete set of arguments used to
8338                specialize R.  */
8339             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8340             argvec = tsubst_template_args (DECL_TI_ARGS
8341                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8342                                            args, complain, in_decl);
8343
8344             /* Check to see if we already have this specialization.  */
8345             spec = retrieve_specialization (gen_tmpl, argvec,
8346                                             /*class_specializations_p=*/false);
8347
8348             if (spec)
8349               {
8350                 r = spec;
8351                 break;
8352               }
8353
8354             /* We can see more levels of arguments than parameters if
8355                there was a specialization of a member template, like
8356                this:
8357
8358                  template <class T> struct S { template <class U> void f(); }
8359                  template <> template <class U> void S<int>::f(U);
8360
8361                Here, we'll be substituting into the specialization,
8362                because that's where we can find the code we actually
8363                want to generate, but we'll have enough arguments for
8364                the most general template.
8365
8366                We also deal with the peculiar case:
8367
8368                  template <class T> struct S {
8369                    template <class U> friend void f();
8370                  };
8371                  template <class U> void f() {}
8372                  template S<int>;
8373                  template void f<double>();
8374
8375                Here, the ARGS for the instantiation of will be {int,
8376                double}.  But, we only need as many ARGS as there are
8377                levels of template parameters in CODE_PATTERN.  We are
8378                careful not to get fooled into reducing the ARGS in
8379                situations like:
8380
8381                  template <class T> struct S { template <class U> void f(U); }
8382                  template <class T> template <> void S<T>::f(int) {}
8383
8384                which we can spot because the pattern will be a
8385                specialization in this case.  */
8386             args_depth = TMPL_ARGS_DEPTH (args);
8387             parms_depth =
8388               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8389             if (args_depth > parms_depth
8390                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8391               args = get_innermost_template_args (args, parms_depth);
8392           }
8393         else
8394           {
8395             /* This special case arises when we have something like this:
8396
8397                  template <class T> struct S {
8398                    friend void f<int>(int, double);
8399                  };
8400
8401                Here, the DECL_TI_TEMPLATE for the friend declaration
8402                will be an IDENTIFIER_NODE.  We are being called from
8403                tsubst_friend_function, and we want only to create a
8404                new decl (R) with appropriate types so that we can call
8405                determine_specialization.  */
8406             gen_tmpl = NULL_TREE;
8407           }
8408
8409         if (DECL_CLASS_SCOPE_P (t))
8410           {
8411             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8412               member = 2;
8413             else
8414               member = 1;
8415             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8416                                     complain, t, /*entering_scope=*/1);
8417           }
8418         else
8419           {
8420             member = 0;
8421             ctx = DECL_CONTEXT (t);
8422           }
8423         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8424         if (type == error_mark_node)
8425           return error_mark_node;
8426
8427         /* We do NOT check for matching decls pushed separately at this
8428            point, as they may not represent instantiations of this
8429            template, and in any case are considered separate under the
8430            discrete model.  */
8431         r = copy_decl (t);
8432         DECL_USE_TEMPLATE (r) = 0;
8433         TREE_TYPE (r) = type;
8434         /* Clear out the mangled name and RTL for the instantiation.  */
8435         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8436         SET_DECL_RTL (r, NULL_RTX);
8437         /* Leave DECL_INITIAL set on deleted instantiations.  */
8438         if (!DECL_DELETED_FN (r))
8439           DECL_INITIAL (r) = NULL_TREE;
8440         DECL_CONTEXT (r) = ctx;
8441
8442         if (member && DECL_CONV_FN_P (r))
8443           /* Type-conversion operator.  Reconstruct the name, in
8444              case it's the name of one of the template's parameters.  */
8445           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8446
8447         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8448                                      complain, t);
8449         DECL_RESULT (r) = NULL_TREE;
8450
8451         TREE_STATIC (r) = 0;
8452         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8453         DECL_EXTERNAL (r) = 1;
8454         /* If this is an instantiation of a function with internal
8455            linkage, we already know what object file linkage will be
8456            assigned to the instantiation.  */
8457         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8458         DECL_DEFER_OUTPUT (r) = 0;
8459         TREE_CHAIN (r) = NULL_TREE;
8460         DECL_PENDING_INLINE_INFO (r) = 0;
8461         DECL_PENDING_INLINE_P (r) = 0;
8462         DECL_SAVED_TREE (r) = NULL_TREE;
8463         DECL_STRUCT_FUNCTION (r) = NULL;
8464         TREE_USED (r) = 0;
8465         if (DECL_CLONED_FUNCTION (r))
8466           {
8467             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
8468                                                args, complain, t);
8469             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
8470             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
8471           }
8472
8473         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8474            this in the special friend case mentioned above where
8475            GEN_TMPL is NULL.  */
8476         if (gen_tmpl)
8477           {
8478             DECL_TEMPLATE_INFO (r)
8479               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8480             SET_DECL_IMPLICIT_INSTANTIATION (r);
8481             register_specialization (r, gen_tmpl, argvec, false);
8482
8483             /* We're not supposed to instantiate default arguments
8484                until they are called, for a template.  But, for a
8485                declaration like:
8486
8487                  template <class T> void f ()
8488                  { extern void g(int i = T()); }
8489
8490                we should do the substitution when the template is
8491                instantiated.  We handle the member function case in
8492                instantiate_class_template since the default arguments
8493                might refer to other members of the class.  */
8494             if (!member
8495                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8496                 && !uses_template_parms (argvec))
8497               tsubst_default_arguments (r);
8498           }
8499         else
8500           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8501
8502         /* Copy the list of befriending classes.  */
8503         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8504              *friends;
8505              friends = &TREE_CHAIN (*friends))
8506           {
8507             *friends = copy_node (*friends);
8508             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8509                                             args, complain,
8510                                             in_decl);
8511           }
8512
8513         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8514           {
8515             maybe_retrofit_in_chrg (r);
8516             if (DECL_CONSTRUCTOR_P (r))
8517               grok_ctor_properties (ctx, r);
8518             /* If this is an instantiation of a member template, clone it.
8519                If it isn't, that'll be handled by
8520                clone_constructors_and_destructors.  */
8521             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8522               clone_function_decl (r, /*update_method_vec_p=*/0);
8523           }
8524         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8525                  && !grok_op_properties (r, (complain & tf_error) != 0))
8526           return error_mark_node;
8527
8528         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8529           SET_DECL_FRIEND_CONTEXT (r,
8530                                    tsubst (DECL_FRIEND_CONTEXT (t),
8531                                             args, complain, in_decl));
8532
8533         /* Possibly limit visibility based on template args.  */
8534         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8535         if (DECL_VISIBILITY_SPECIFIED (t))
8536           {
8537             DECL_VISIBILITY_SPECIFIED (r) = 0;
8538             DECL_ATTRIBUTES (r)
8539               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8540           }
8541         determine_visibility (r);
8542
8543         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8544                                         args, complain, in_decl);
8545       }
8546       break;
8547
8548     case PARM_DECL:
8549       {
8550         tree type = NULL_TREE;
8551         int i, len = 1;
8552         tree expanded_types = NULL_TREE;
8553         tree prev_r = NULL_TREE;
8554         tree first_r = NULL_TREE;
8555
8556         if (FUNCTION_PARAMETER_PACK_P (t))
8557           {
8558             /* If there is a local specialization that isn't a
8559                parameter pack, it means that we're doing a "simple"
8560                substitution from inside tsubst_pack_expansion. Just
8561                return the local specialization (which will be a single
8562                parm).  */
8563             tree spec = retrieve_local_specialization (t);
8564             if (spec 
8565                 && TREE_CODE (spec) == PARM_DECL
8566                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8567               return spec;
8568
8569             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8570                the parameters in this function parameter pack.  */
8571             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8572                                                     complain, in_decl);
8573             if (TREE_CODE (expanded_types) == TREE_VEC)
8574               {
8575                 len = TREE_VEC_LENGTH (expanded_types);
8576
8577                 /* Zero-length parameter packs are boring. Just substitute
8578                    into the chain.  */
8579                 if (len == 0)
8580                   return tsubst (TREE_CHAIN (t), args, complain, 
8581                                  TREE_CHAIN (t));
8582               }
8583             else
8584               {
8585                 /* All we did was update the type. Make a note of that.  */
8586                 type = expanded_types;
8587                 expanded_types = NULL_TREE;
8588               }
8589           }
8590
8591         /* Loop through all of the parameter's we'll build. When T is
8592            a function parameter pack, LEN is the number of expanded
8593            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8594         r = NULL_TREE;
8595         for (i = 0; i < len; ++i)
8596           {
8597             prev_r = r;
8598             r = copy_node (t);
8599             if (DECL_TEMPLATE_PARM_P (t))
8600               SET_DECL_TEMPLATE_PARM_P (r);
8601
8602             if (expanded_types)
8603               /* We're on the Ith parameter of the function parameter
8604                  pack.  */
8605               {
8606                 /* Get the Ith type.  */
8607                 type = TREE_VEC_ELT (expanded_types, i);
8608
8609                 if (DECL_NAME (r))
8610                   /* Rename the parameter to include the index.  */
8611                   DECL_NAME (r) =
8612                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8613               }
8614             else if (!type)
8615               /* We're dealing with a normal parameter.  */
8616               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8617
8618             type = type_decays_to (type);
8619             TREE_TYPE (r) = type;
8620             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8621
8622             if (DECL_INITIAL (r))
8623               {
8624                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8625                   DECL_INITIAL (r) = TREE_TYPE (r);
8626                 else
8627                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8628                                              complain, in_decl);
8629               }
8630
8631             DECL_CONTEXT (r) = NULL_TREE;
8632
8633             if (!DECL_TEMPLATE_PARM_P (r))
8634               DECL_ARG_TYPE (r) = type_passed_as (type);
8635
8636             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8637                                             args, complain, in_decl);
8638
8639             /* Keep track of the first new parameter we
8640                generate. That's what will be returned to the
8641                caller.  */
8642             if (!first_r)
8643               first_r = r;
8644
8645             /* Build a proper chain of parameters when substituting
8646                into a function parameter pack.  */
8647             if (prev_r)
8648               TREE_CHAIN (prev_r) = r;
8649           }
8650
8651         if (TREE_CHAIN (t))
8652           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8653                                    complain, TREE_CHAIN (t));
8654
8655         /* FIRST_R contains the start of the chain we've built.  */
8656         r = first_r;
8657       }
8658       break;
8659
8660     case FIELD_DECL:
8661       {
8662         tree type;
8663
8664         r = copy_decl (t);
8665         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8666         if (type == error_mark_node)
8667           return error_mark_node;
8668         TREE_TYPE (r) = type;
8669         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8670
8671         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8672         DECL_INITIAL (r)
8673           = tsubst_expr (DECL_INITIAL (t), args,
8674                          complain, in_decl,
8675                          /*integral_constant_expression_p=*/true);
8676         /* We don't have to set DECL_CONTEXT here; it is set by
8677            finish_member_declaration.  */
8678         TREE_CHAIN (r) = NULL_TREE;
8679         if (VOID_TYPE_P (type))
8680           error ("instantiation of %q+D as type %qT", r, type);
8681
8682         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8683                                         args, complain, in_decl);
8684       }
8685       break;
8686
8687     case USING_DECL:
8688       /* We reach here only for member using decls.  */
8689       if (DECL_DEPENDENT_P (t))
8690         {
8691           r = do_class_using_decl
8692             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8693              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8694           if (!r)
8695             r = error_mark_node;
8696           else
8697             {
8698               TREE_PROTECTED (r) = TREE_PROTECTED (t);
8699               TREE_PRIVATE (r) = TREE_PRIVATE (t);
8700             }
8701         }
8702       else
8703         {
8704           r = copy_node (t);
8705           TREE_CHAIN (r) = NULL_TREE;
8706         }
8707       break;
8708
8709     case TYPE_DECL:
8710     case VAR_DECL:
8711       {
8712         tree argvec = NULL_TREE;
8713         tree gen_tmpl = NULL_TREE;
8714         tree spec;
8715         tree tmpl = NULL_TREE;
8716         tree ctx;
8717         tree type = NULL_TREE;
8718         bool local_p;
8719
8720         if (TREE_CODE (t) == TYPE_DECL
8721             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8722           {
8723             /* If this is the canonical decl, we don't have to
8724                mess with instantiations, and often we can't (for
8725                typename, template type parms and such).  Note that
8726                TYPE_NAME is not correct for the above test if
8727                we've copied the type for a typedef.  */
8728             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8729             if (type == error_mark_node)
8730               return error_mark_node;
8731             r = TYPE_NAME (type);
8732             break;
8733           }
8734
8735         /* Check to see if we already have the specialization we
8736            need.  */
8737         spec = NULL_TREE;
8738         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8739           {
8740             /* T is a static data member or namespace-scope entity.
8741                We have to substitute into namespace-scope variables
8742                (even though such entities are never templates) because
8743                of cases like:
8744                
8745                  template <class T> void f() { extern T t; }
8746
8747                where the entity referenced is not known until
8748                instantiation time.  */
8749             local_p = false;
8750             ctx = DECL_CONTEXT (t);
8751             if (DECL_CLASS_SCOPE_P (t))
8752               {
8753                 ctx = tsubst_aggr_type (ctx, args,
8754                                         complain,
8755                                         in_decl, /*entering_scope=*/1);
8756                 /* If CTX is unchanged, then T is in fact the
8757                    specialization we want.  That situation occurs when
8758                    referencing a static data member within in its own
8759                    class.  We can use pointer equality, rather than
8760                    same_type_p, because DECL_CONTEXT is always
8761                    canonical.  */
8762                 if (ctx == DECL_CONTEXT (t))
8763                   spec = t;
8764               }
8765
8766             if (!spec)
8767               {
8768                 tmpl = DECL_TI_TEMPLATE (t);
8769                 gen_tmpl = most_general_template (tmpl);
8770                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8771                 spec = (retrieve_specialization 
8772                         (gen_tmpl, argvec,
8773                          /*class_specializations_p=*/false));
8774               }
8775           }
8776         else
8777           {
8778             /* A local variable.  */
8779             local_p = true;
8780             /* Subsequent calls to pushdecl will fill this in.  */
8781             ctx = NULL_TREE;
8782             spec = retrieve_local_specialization (t);
8783           }
8784         /* If we already have the specialization we need, there is
8785            nothing more to do.  */ 
8786         if (spec)
8787           {
8788             r = spec;
8789             break;
8790           }
8791
8792         /* Create a new node for the specialization we need.  */
8793         r = copy_decl (t);
8794         if (type == NULL_TREE)
8795           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8796         if (TREE_CODE (r) == VAR_DECL)
8797           {
8798             /* Even if the original location is out of scope, the
8799                newly substituted one is not.  */
8800             DECL_DEAD_FOR_LOCAL (r) = 0;
8801             DECL_INITIALIZED_P (r) = 0;
8802             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8803             if (type == error_mark_node)
8804               return error_mark_node;
8805             if (TREE_CODE (type) == FUNCTION_TYPE)
8806               {
8807                 /* It may seem that this case cannot occur, since:
8808
8809                      typedef void f();
8810                      void g() { f x; }
8811
8812                    declares a function, not a variable.  However:
8813       
8814                      typedef void f();
8815                      template <typename T> void g() { T t; }
8816                      template void g<f>();
8817
8818                    is an attempt to declare a variable with function
8819                    type.  */
8820                 error ("variable %qD has function type",
8821                        /* R is not yet sufficiently initialized, so we
8822                           just use its name.  */
8823                        DECL_NAME (r));
8824                 return error_mark_node;
8825               }
8826             type = complete_type (type);
8827             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8828               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8829             type = check_var_type (DECL_NAME (r), type);
8830
8831             if (DECL_HAS_VALUE_EXPR_P (t))
8832               {
8833                 tree ve = DECL_VALUE_EXPR (t);
8834                 ve = tsubst_expr (ve, args, complain, in_decl,
8835                                   /*constant_expression_p=*/false);
8836                 SET_DECL_VALUE_EXPR (r, ve);
8837               }
8838           }
8839         else if (DECL_SELF_REFERENCE_P (t))
8840           SET_DECL_SELF_REFERENCE_P (r);
8841         TREE_TYPE (r) = type;
8842         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8843         DECL_CONTEXT (r) = ctx;
8844         /* Clear out the mangled name and RTL for the instantiation.  */
8845         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8846         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8847           SET_DECL_RTL (r, NULL_RTX);
8848         /* The initializer must not be expanded until it is required;
8849            see [temp.inst].  */
8850         DECL_INITIAL (r) = NULL_TREE;
8851         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8852           SET_DECL_RTL (r, NULL_RTX);
8853         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8854         if (TREE_CODE (r) == VAR_DECL)
8855           {
8856             /* Possibly limit visibility based on template args.  */
8857             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8858             if (DECL_VISIBILITY_SPECIFIED (t))
8859               {
8860                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8861                 DECL_ATTRIBUTES (r)
8862                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8863               }
8864             determine_visibility (r);
8865           }
8866         /* Preserve a typedef that names a type.  */
8867         else if (TREE_CODE (r) == TYPE_DECL
8868                  && DECL_ORIGINAL_TYPE (t)
8869                  && type != error_mark_node)
8870           {
8871             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8872                                              args, complain, in_decl);
8873             TREE_TYPE (r) = type = build_variant_type_copy (type);
8874             TYPE_NAME (type) = r;
8875           }
8876
8877         if (!local_p)
8878           {
8879             /* A static data member declaration is always marked
8880                external when it is declared in-class, even if an
8881                initializer is present.  We mimic the non-template
8882                processing here.  */
8883             DECL_EXTERNAL (r) = 1;
8884
8885             register_specialization (r, gen_tmpl, argvec, false);
8886             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8887             SET_DECL_IMPLICIT_INSTANTIATION (r);
8888           }
8889         else
8890           register_local_specialization (r, t);
8891
8892         TREE_CHAIN (r) = NULL_TREE;
8893
8894         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
8895                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
8896                                         args, complain, in_decl);
8897         layout_decl (r, 0);
8898       }
8899       break;
8900
8901     default:
8902       gcc_unreachable ();
8903     }
8904
8905   /* Restore the file and line information.  */
8906   input_location = saved_loc;
8907
8908   return r;
8909 }
8910
8911 /* Substitute into the ARG_TYPES of a function type.  */
8912
8913 static tree
8914 tsubst_arg_types (tree arg_types,
8915                   tree args,
8916                   tsubst_flags_t complain,
8917                   tree in_decl)
8918 {
8919   tree remaining_arg_types;
8920   tree type = NULL_TREE;
8921   int i = 1;
8922   tree expanded_args = NULL_TREE;
8923   tree default_arg;
8924
8925   if (!arg_types || arg_types == void_list_node)
8926     return arg_types;
8927
8928   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8929                                           args, complain, in_decl);
8930   if (remaining_arg_types == error_mark_node)
8931     return error_mark_node;
8932
8933   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8934     {
8935       /* For a pack expansion, perform substitution on the
8936          entire expression. Later on, we'll handle the arguments
8937          one-by-one.  */
8938       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8939                                             args, complain, in_decl);
8940
8941       if (TREE_CODE (expanded_args) == TREE_VEC)
8942         /* So that we'll spin through the parameters, one by one.  */
8943         i = TREE_VEC_LENGTH (expanded_args);
8944       else
8945         {
8946           /* We only partially substituted into the parameter
8947              pack. Our type is TYPE_PACK_EXPANSION.  */
8948           type = expanded_args;
8949           expanded_args = NULL_TREE;
8950         }
8951     }
8952
8953   while (i > 0) {
8954     --i;
8955     
8956     if (expanded_args)
8957       type = TREE_VEC_ELT (expanded_args, i);
8958     else if (!type)
8959       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8960
8961     if (type == error_mark_node)
8962       return error_mark_node;
8963     if (VOID_TYPE_P (type))
8964       {
8965         if (complain & tf_error)
8966           {
8967             error ("invalid parameter type %qT", type);
8968             if (in_decl)
8969               error ("in declaration %q+D", in_decl);
8970           }
8971         return error_mark_node;
8972     }
8973     
8974     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8975        top-level qualifiers as required.  */
8976     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8977
8978     /* We do not substitute into default arguments here.  The standard
8979        mandates that they be instantiated only when needed, which is
8980        done in build_over_call.  */
8981     default_arg = TREE_PURPOSE (arg_types);
8982
8983     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8984       {
8985         /* We've instantiated a template before its default arguments
8986            have been parsed.  This can happen for a nested template
8987            class, and is not an error unless we require the default
8988            argument in a call of this function.  */
8989         remaining_arg_types = 
8990           tree_cons (default_arg, type, remaining_arg_types);
8991         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8992                        remaining_arg_types);
8993       }
8994     else
8995       remaining_arg_types = 
8996         hash_tree_cons (default_arg, type, remaining_arg_types);
8997   }
8998         
8999   return remaining_arg_types;
9000 }
9001
9002 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9003    *not* handle the exception-specification for FNTYPE, because the
9004    initial substitution of explicitly provided template parameters
9005    during argument deduction forbids substitution into the
9006    exception-specification:
9007
9008      [temp.deduct]
9009
9010      All references in the function type of the function template to  the
9011      corresponding template parameters are replaced by the specified tem-
9012      plate argument values.  If a substitution in a template parameter or
9013      in  the function type of the function template results in an invalid
9014      type, type deduction fails.  [Note: The equivalent  substitution  in
9015      exception specifications is done only when the function is instanti-
9016      ated, at which point a program is  ill-formed  if  the  substitution
9017      results in an invalid type.]  */
9018
9019 static tree
9020 tsubst_function_type (tree t,
9021                       tree args,
9022                       tsubst_flags_t complain,
9023                       tree in_decl)
9024 {
9025   tree return_type;
9026   tree arg_types;
9027   tree fntype;
9028
9029   /* The TYPE_CONTEXT is not used for function/method types.  */
9030   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9031
9032   /* Substitute the return type.  */
9033   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9034   if (return_type == error_mark_node)
9035     return error_mark_node;
9036   /* The standard does not presently indicate that creation of a
9037      function type with an invalid return type is a deduction failure.
9038      However, that is clearly analogous to creating an array of "void"
9039      or a reference to a reference.  This is core issue #486.  */
9040   if (TREE_CODE (return_type) == ARRAY_TYPE
9041       || TREE_CODE (return_type) == FUNCTION_TYPE)
9042     {
9043       if (complain & tf_error)
9044         {
9045           if (TREE_CODE (return_type) == ARRAY_TYPE)
9046             error ("function returning an array");
9047           else
9048             error ("function returning a function");
9049         }
9050       return error_mark_node;
9051     }
9052
9053   /* Substitute the argument types.  */
9054   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9055                                 complain, in_decl);
9056   if (arg_types == error_mark_node)
9057     return error_mark_node;
9058
9059   /* Construct a new type node and return it.  */
9060   if (TREE_CODE (t) == FUNCTION_TYPE)
9061     fntype = build_function_type (return_type, arg_types);
9062   else
9063     {
9064       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9065       if (! MAYBE_CLASS_TYPE_P (r))
9066         {
9067           /* [temp.deduct]
9068
9069              Type deduction may fail for any of the following
9070              reasons:
9071
9072              -- Attempting to create "pointer to member of T" when T
9073              is not a class type.  */
9074           if (complain & tf_error)
9075             error ("creating pointer to member function of non-class type %qT",
9076                       r);
9077           return error_mark_node;
9078         }
9079
9080       fntype = build_method_type_directly (r, return_type,
9081                                            TREE_CHAIN (arg_types));
9082     }
9083   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9084   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9085
9086   return fntype;
9087 }
9088
9089 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9090    ARGS into that specification, and return the substituted
9091    specification.  If there is no specification, return NULL_TREE.  */
9092
9093 static tree
9094 tsubst_exception_specification (tree fntype,
9095                                 tree args,
9096                                 tsubst_flags_t complain,
9097                                 tree in_decl)
9098 {
9099   tree specs;
9100   tree new_specs;
9101
9102   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9103   new_specs = NULL_TREE;
9104   if (specs)
9105     {
9106       if (! TREE_VALUE (specs))
9107         new_specs = specs;
9108       else
9109         while (specs)
9110           {
9111             tree spec;
9112             int i, len = 1;
9113             tree expanded_specs = NULL_TREE;
9114
9115             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9116               {
9117                 /* Expand the pack expansion type.  */
9118                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9119                                                        args, complain,
9120                                                        in_decl);
9121
9122                 if (expanded_specs == error_mark_node)
9123                   return error_mark_node;
9124                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9125                   len = TREE_VEC_LENGTH (expanded_specs);
9126                 else
9127                   {
9128                     /* We're substituting into a member template, so
9129                        we got a TYPE_PACK_EXPANSION back.  Add that
9130                        expansion and move on.  */
9131                     gcc_assert (TREE_CODE (expanded_specs) 
9132                                 == TYPE_PACK_EXPANSION);
9133                     new_specs = add_exception_specifier (new_specs,
9134                                                          expanded_specs,
9135                                                          complain);
9136                     specs = TREE_CHAIN (specs);
9137                     continue;
9138                   }
9139               }
9140
9141             for (i = 0; i < len; ++i)
9142               {
9143                 if (expanded_specs)
9144                   spec = TREE_VEC_ELT (expanded_specs, i);
9145                 else
9146                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9147                 if (spec == error_mark_node)
9148                   return spec;
9149                 new_specs = add_exception_specifier (new_specs, spec, 
9150                                                      complain);
9151               }
9152
9153             specs = TREE_CHAIN (specs);
9154           }
9155     }
9156   return new_specs;
9157 }
9158
9159 /* Take the tree structure T and replace template parameters used
9160    therein with the argument vector ARGS.  IN_DECL is an associated
9161    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9162    Issue error and warning messages under control of COMPLAIN.  Note
9163    that we must be relatively non-tolerant of extensions here, in
9164    order to preserve conformance; if we allow substitutions that
9165    should not be allowed, we may allow argument deductions that should
9166    not succeed, and therefore report ambiguous overload situations
9167    where there are none.  In theory, we could allow the substitution,
9168    but indicate that it should have failed, and allow our caller to
9169    make sure that the right thing happens, but we don't try to do this
9170    yet.
9171
9172    This function is used for dealing with types, decls and the like;
9173    for expressions, use tsubst_expr or tsubst_copy.  */
9174
9175 static tree
9176 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9177 {
9178   tree type, r;
9179
9180   if (t == NULL_TREE || t == error_mark_node
9181       || t == integer_type_node
9182       || t == void_type_node
9183       || t == char_type_node
9184       || t == unknown_type_node
9185       || TREE_CODE (t) == NAMESPACE_DECL)
9186     return t;
9187
9188   if (DECL_P (t))
9189     return tsubst_decl (t, args, complain);
9190
9191   if (args == NULL_TREE)
9192     return t;
9193
9194   if (TREE_CODE (t) == IDENTIFIER_NODE)
9195     type = IDENTIFIER_TYPE_VALUE (t);
9196   else
9197     type = TREE_TYPE (t);
9198
9199   gcc_assert (type != unknown_type_node);
9200
9201   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9202      such as attribute aligned.  */
9203   if (TYPE_P (t)
9204       && TYPE_NAME (t)
9205       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9206     {
9207       tree decl = TYPE_NAME (t);
9208       
9209       if (DECL_CLASS_SCOPE_P (decl)
9210           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9211           && uses_template_parms (DECL_CONTEXT (decl)))
9212         {
9213           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9214           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9215           r = retrieve_specialization (tmpl, gen_args, false);
9216         }
9217       else if (DECL_FUNCTION_SCOPE_P (decl)
9218                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9219                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9220         r = retrieve_local_specialization (decl);
9221       else
9222         /* The typedef is from a non-template context.  */
9223         return t;
9224
9225       if (r)
9226         {
9227           r = TREE_TYPE (r);
9228           r = cp_build_qualified_type_real
9229             (r, cp_type_quals (t) | cp_type_quals (r),
9230              complain | tf_ignore_bad_quals);
9231           return r;
9232         }
9233       /* Else we must be instantiating the typedef, so fall through.  */
9234     }
9235
9236   if (type
9237       && TREE_CODE (t) != TYPENAME_TYPE
9238       && TREE_CODE (t) != IDENTIFIER_NODE
9239       && TREE_CODE (t) != FUNCTION_TYPE
9240       && TREE_CODE (t) != METHOD_TYPE)
9241     type = tsubst (type, args, complain, in_decl);
9242   if (type == error_mark_node)
9243     return error_mark_node;
9244
9245   switch (TREE_CODE (t))
9246     {
9247     case RECORD_TYPE:
9248     case UNION_TYPE:
9249     case ENUMERAL_TYPE:
9250       return tsubst_aggr_type (t, args, complain, in_decl,
9251                                /*entering_scope=*/0);
9252
9253     case ERROR_MARK:
9254     case IDENTIFIER_NODE:
9255     case VOID_TYPE:
9256     case REAL_TYPE:
9257     case COMPLEX_TYPE:
9258     case VECTOR_TYPE:
9259     case BOOLEAN_TYPE:
9260     case INTEGER_CST:
9261     case REAL_CST:
9262     case STRING_CST:
9263       return t;
9264
9265     case INTEGER_TYPE:
9266       if (t == integer_type_node)
9267         return t;
9268
9269       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9270           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9271         return t;
9272
9273       {
9274         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9275
9276         max = tsubst_expr (omax, args, complain, in_decl,
9277                            /*integral_constant_expression_p=*/false);
9278
9279         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9280            needed.  */
9281         if (TREE_CODE (max) == NOP_EXPR
9282             && TREE_SIDE_EFFECTS (omax)
9283             && !TREE_TYPE (max))
9284           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9285
9286         max = fold_decl_constant_value (max);
9287
9288         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9289            with TREE_SIDE_EFFECTS that indicates this is not an integral
9290            constant expression.  */
9291         if (processing_template_decl
9292             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9293           {
9294             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9295             TREE_SIDE_EFFECTS (max) = 1;
9296           }
9297
9298         if (TREE_CODE (max) != INTEGER_CST
9299             && !at_function_scope_p ()
9300             && !TREE_SIDE_EFFECTS (max)
9301             && !value_dependent_expression_p (max))
9302           {
9303             if (complain & tf_error)
9304               error ("array bound is not an integer constant");
9305             return error_mark_node;
9306           }
9307
9308         /* [temp.deduct]
9309
9310            Type deduction may fail for any of the following
9311            reasons:
9312
9313              Attempting to create an array with a size that is
9314              zero or negative.  */
9315         if (integer_zerop (max) && !(complain & tf_error))
9316           /* We must fail if performing argument deduction (as
9317              indicated by the state of complain), so that
9318              another substitution can be found.  */
9319           return error_mark_node;
9320         else if (TREE_CODE (max) == INTEGER_CST
9321                  && INT_CST_LT (max, integer_zero_node))
9322           {
9323             if (complain & tf_error)
9324               error ("creating array with negative size (%qE)", max);
9325
9326             return error_mark_node;
9327           }
9328
9329         return compute_array_index_type (NULL_TREE, max);
9330       }
9331
9332     case TEMPLATE_TYPE_PARM:
9333     case TEMPLATE_TEMPLATE_PARM:
9334     case BOUND_TEMPLATE_TEMPLATE_PARM:
9335     case TEMPLATE_PARM_INDEX:
9336       {
9337         int idx;
9338         int level;
9339         int levels;
9340         tree arg = NULL_TREE;
9341
9342         r = NULL_TREE;
9343
9344         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9345         template_parm_level_and_index (t, &level, &idx); 
9346
9347         levels = TMPL_ARGS_DEPTH (args);
9348         if (level <= levels)
9349           {
9350             arg = TMPL_ARG (args, level, idx);
9351
9352             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9353               /* See through ARGUMENT_PACK_SELECT arguments. */
9354               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9355           }
9356
9357         if (arg == error_mark_node)
9358           return error_mark_node;
9359         else if (arg != NULL_TREE)
9360           {
9361             if (ARGUMENT_PACK_P (arg))
9362               /* If ARG is an argument pack, we don't actually want to
9363                  perform a substitution here, because substitutions
9364                  for argument packs are only done
9365                  element-by-element. We can get to this point when
9366                  substituting the type of a non-type template
9367                  parameter pack, when that type actually contains
9368                  template parameter packs from an outer template, e.g.,
9369
9370                  template<typename... Types> struct A {
9371                    template<Types... Values> struct B { };
9372                  };  */
9373               return t;
9374
9375             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9376               {
9377                 int quals;
9378                 gcc_assert (TYPE_P (arg));
9379
9380                 /* cv-quals from the template are discarded when
9381                    substituting in a function or reference type.  */
9382                 if (TREE_CODE (arg) == FUNCTION_TYPE
9383                     || TREE_CODE (arg) == METHOD_TYPE
9384                     || TREE_CODE (arg) == REFERENCE_TYPE)
9385                   quals = cp_type_quals (arg);
9386                 else
9387                   quals = cp_type_quals (arg) | cp_type_quals (t);
9388                   
9389                 return cp_build_qualified_type_real
9390                   (arg, quals, complain | tf_ignore_bad_quals);
9391               }
9392             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9393               {
9394                 /* We are processing a type constructed from a
9395                    template template parameter.  */
9396                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9397                                       args, complain, in_decl);
9398                 if (argvec == error_mark_node)
9399                   return error_mark_node;
9400
9401                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9402                    are resolving nested-types in the signature of a
9403                    member function templates.  Otherwise ARG is a
9404                    TEMPLATE_DECL and is the real template to be
9405                    instantiated.  */
9406                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9407                   arg = TYPE_NAME (arg);
9408
9409                 r = lookup_template_class (arg,
9410                                            argvec, in_decl,
9411                                            DECL_CONTEXT (arg),
9412                                             /*entering_scope=*/0,
9413                                            complain);
9414                 return cp_build_qualified_type_real
9415                   (r, TYPE_QUALS (t), complain);
9416               }
9417             else
9418               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9419               return arg;
9420           }
9421
9422         if (level == 1)
9423           /* This can happen during the attempted tsubst'ing in
9424              unify.  This means that we don't yet have any information
9425              about the template parameter in question.  */
9426           return t;
9427
9428         /* If we get here, we must have been looking at a parm for a
9429            more deeply nested template.  Make a new version of this
9430            template parameter, but with a lower level.  */
9431         switch (TREE_CODE (t))
9432           {
9433           case TEMPLATE_TYPE_PARM:
9434           case TEMPLATE_TEMPLATE_PARM:
9435           case BOUND_TEMPLATE_TEMPLATE_PARM:
9436             if (cp_type_quals (t))
9437               {
9438                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9439                 r = cp_build_qualified_type_real
9440                   (r, cp_type_quals (t),
9441                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9442                                ? tf_ignore_bad_quals : 0));
9443               }
9444             else
9445               {
9446                 r = copy_type (t);
9447                 TEMPLATE_TYPE_PARM_INDEX (r)
9448                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9449                                                 r, levels, args, complain);
9450                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9451                 TYPE_MAIN_VARIANT (r) = r;
9452                 TYPE_POINTER_TO (r) = NULL_TREE;
9453                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9454
9455                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9456                   /* We have reduced the level of the template
9457                      template parameter, but not the levels of its
9458                      template parameters, so canonical_type_parameter
9459                      will not be able to find the canonical template
9460                      template parameter for this level. Thus, we
9461                      require structural equality checking to compare
9462                      TEMPLATE_TEMPLATE_PARMs. */
9463                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9464                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9465                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9466                 else
9467                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9468
9469                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9470                   {
9471                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9472                                           complain, in_decl);
9473                     if (argvec == error_mark_node)
9474                       return error_mark_node;
9475
9476                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9477                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9478                   }
9479               }
9480             break;
9481
9482           case TEMPLATE_PARM_INDEX:
9483             r = reduce_template_parm_level (t, type, levels, args, complain);
9484             break;
9485
9486           default:
9487             gcc_unreachable ();
9488           }
9489
9490         return r;
9491       }
9492
9493     case TREE_LIST:
9494       {
9495         tree purpose, value, chain;
9496
9497         if (t == void_list_node)
9498           return t;
9499
9500         purpose = TREE_PURPOSE (t);
9501         if (purpose)
9502           {
9503             purpose = tsubst (purpose, args, complain, in_decl);
9504             if (purpose == error_mark_node)
9505               return error_mark_node;
9506           }
9507         value = TREE_VALUE (t);
9508         if (value)
9509           {
9510             value = tsubst (value, args, complain, in_decl);
9511             if (value == error_mark_node)
9512               return error_mark_node;
9513           }
9514         chain = TREE_CHAIN (t);
9515         if (chain && chain != void_type_node)
9516           {
9517             chain = tsubst (chain, args, complain, in_decl);
9518             if (chain == error_mark_node)
9519               return error_mark_node;
9520           }
9521         if (purpose == TREE_PURPOSE (t)
9522             && value == TREE_VALUE (t)
9523             && chain == TREE_CHAIN (t))
9524           return t;
9525         return hash_tree_cons (purpose, value, chain);
9526       }
9527
9528     case TREE_BINFO:
9529       /* We should never be tsubsting a binfo.  */
9530       gcc_unreachable ();
9531
9532     case TREE_VEC:
9533       /* A vector of template arguments.  */
9534       gcc_assert (!type);
9535       return tsubst_template_args (t, args, complain, in_decl);
9536
9537     case POINTER_TYPE:
9538     case REFERENCE_TYPE:
9539       {
9540         enum tree_code code;
9541
9542         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9543           return t;
9544
9545         code = TREE_CODE (t);
9546
9547
9548         /* [temp.deduct]
9549
9550            Type deduction may fail for any of the following
9551            reasons:
9552
9553            -- Attempting to create a pointer to reference type.
9554            -- Attempting to create a reference to a reference type or
9555               a reference to void.
9556
9557           Core issue 106 says that creating a reference to a reference
9558           during instantiation is no longer a cause for failure. We
9559           only enforce this check in strict C++98 mode.  */
9560         if ((TREE_CODE (type) == REFERENCE_TYPE
9561              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9562             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9563           {
9564             static location_t last_loc;
9565
9566             /* We keep track of the last time we issued this error
9567                message to avoid spewing a ton of messages during a
9568                single bad template instantiation.  */
9569             if (complain & tf_error
9570                 && last_loc != input_location)
9571               {
9572                 if (TREE_CODE (type) == VOID_TYPE)
9573                   error ("forming reference to void");
9574                 else
9575                   error ("forming %s to reference type %qT",
9576                          (code == POINTER_TYPE) ? "pointer" : "reference",
9577                          type);
9578                 last_loc = input_location;
9579               }
9580
9581             return error_mark_node;
9582           }
9583         else if (code == POINTER_TYPE)
9584           {
9585             r = build_pointer_type (type);
9586             if (TREE_CODE (type) == METHOD_TYPE)
9587               r = build_ptrmemfunc_type (r);
9588           }
9589         else if (TREE_CODE (type) == REFERENCE_TYPE)
9590           /* In C++0x, during template argument substitution, when there is an
9591              attempt to create a reference to a reference type, reference
9592              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9593
9594              "If a template-argument for a template-parameter T names a type
9595              that is a reference to a type A, an attempt to create the type
9596              'lvalue reference to cv T' creates the type 'lvalue reference to
9597              A,' while an attempt to create the type type rvalue reference to
9598              cv T' creates the type T"
9599           */
9600           r = cp_build_reference_type
9601               (TREE_TYPE (type),
9602                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9603         else
9604           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9605         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9606
9607         if (r != error_mark_node)
9608           /* Will this ever be needed for TYPE_..._TO values?  */
9609           layout_type (r);
9610
9611         return r;
9612       }
9613     case OFFSET_TYPE:
9614       {
9615         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9616         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9617           {
9618             /* [temp.deduct]
9619
9620                Type deduction may fail for any of the following
9621                reasons:
9622
9623                -- Attempting to create "pointer to member of T" when T
9624                   is not a class type.  */
9625             if (complain & tf_error)
9626               error ("creating pointer to member of non-class type %qT", r);
9627             return error_mark_node;
9628           }
9629         if (TREE_CODE (type) == REFERENCE_TYPE)
9630           {
9631             if (complain & tf_error)
9632               error ("creating pointer to member reference type %qT", type);
9633             return error_mark_node;
9634           }
9635         if (TREE_CODE (type) == VOID_TYPE)
9636           {
9637             if (complain & tf_error)
9638               error ("creating pointer to member of type void");
9639             return error_mark_node;
9640           }
9641         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9642         if (TREE_CODE (type) == FUNCTION_TYPE)
9643           {
9644             /* The type of the implicit object parameter gets its
9645                cv-qualifiers from the FUNCTION_TYPE. */
9646             tree memptr;
9647             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
9648             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9649             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9650                                                  complain);
9651           }
9652         else
9653           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9654                                                TYPE_QUALS (t),
9655                                                complain);
9656       }
9657     case FUNCTION_TYPE:
9658     case METHOD_TYPE:
9659       {
9660         tree fntype;
9661         tree specs;
9662         fntype = tsubst_function_type (t, args, complain, in_decl);
9663         if (fntype == error_mark_node)
9664           return error_mark_node;
9665
9666         /* Substitute the exception specification.  */
9667         specs = tsubst_exception_specification (t, args, complain,
9668                                                 in_decl);
9669         if (specs == error_mark_node)
9670           return error_mark_node;
9671         if (specs)
9672           fntype = build_exception_variant (fntype, specs);
9673         return fntype;
9674       }
9675     case ARRAY_TYPE:
9676       {
9677         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9678         if (domain == error_mark_node)
9679           return error_mark_node;
9680
9681         /* As an optimization, we avoid regenerating the array type if
9682            it will obviously be the same as T.  */
9683         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9684           return t;
9685
9686         /* These checks should match the ones in grokdeclarator.
9687
9688            [temp.deduct]
9689
9690            The deduction may fail for any of the following reasons:
9691
9692            -- Attempting to create an array with an element type that
9693               is void, a function type, or a reference type, or [DR337]
9694               an abstract class type.  */
9695         if (TREE_CODE (type) == VOID_TYPE
9696             || TREE_CODE (type) == FUNCTION_TYPE
9697             || TREE_CODE (type) == REFERENCE_TYPE)
9698           {
9699             if (complain & tf_error)
9700               error ("creating array of %qT", type);
9701             return error_mark_node;
9702           }
9703         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9704           {
9705             if (complain & tf_error)
9706               error ("creating array of %qT, which is an abstract class type",
9707                      type);
9708             return error_mark_node;
9709           }
9710
9711         r = build_cplus_array_type (type, domain);
9712
9713         if (TYPE_USER_ALIGN (t))
9714           {
9715             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9716             TYPE_USER_ALIGN (r) = 1;
9717           }
9718
9719         return r;
9720       }
9721
9722     case PLUS_EXPR:
9723     case MINUS_EXPR:
9724       {
9725         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9726         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9727
9728         if (e1 == error_mark_node || e2 == error_mark_node)
9729           return error_mark_node;
9730
9731         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9732       }
9733
9734     case NEGATE_EXPR:
9735     case NOP_EXPR:
9736       {
9737         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9738         if (e == error_mark_node)
9739           return error_mark_node;
9740
9741         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9742       }
9743
9744     case TYPENAME_TYPE:
9745       {
9746         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9747                                      in_decl, /*entering_scope=*/1);
9748         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9749                               complain, in_decl);
9750         int quals;
9751
9752         if (ctx == error_mark_node || f == error_mark_node)
9753           return error_mark_node;
9754
9755         if (!MAYBE_CLASS_TYPE_P (ctx))
9756           {
9757             if (complain & tf_error)
9758               error ("%qT is not a class, struct, or union type", ctx);
9759             return error_mark_node;
9760           }
9761         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9762           {
9763             /* Normally, make_typename_type does not require that the CTX
9764                have complete type in order to allow things like:
9765
9766                  template <class T> struct S { typename S<T>::X Y; };
9767
9768                But, such constructs have already been resolved by this
9769                point, so here CTX really should have complete type, unless
9770                it's a partial instantiation.  */
9771             ctx = complete_type (ctx);
9772             if (!COMPLETE_TYPE_P (ctx))
9773               {
9774                 if (complain & tf_error)
9775                   cxx_incomplete_type_error (NULL_TREE, ctx);
9776                 return error_mark_node;
9777               }
9778           }
9779
9780         f = make_typename_type (ctx, f, typename_type,
9781                                 (complain & tf_error) | tf_keep_type_decl);
9782         if (f == error_mark_node)
9783           return f;
9784         if (TREE_CODE (f) == TYPE_DECL)
9785           {
9786             complain |= tf_ignore_bad_quals;
9787             f = TREE_TYPE (f);
9788           }
9789
9790         if (TREE_CODE (f) != TYPENAME_TYPE)
9791           {
9792             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9793               error ("%qT resolves to %qT, which is not an enumeration type",
9794                      t, f);
9795             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9796               error ("%qT resolves to %qT, which is is not a class type",
9797                      t, f);
9798           }
9799
9800         /* cv-quals from the template are discarded when
9801            substituting in a function or reference type.  */
9802         if (TREE_CODE (f) == FUNCTION_TYPE
9803             || TREE_CODE (f) == METHOD_TYPE
9804             || TREE_CODE (f) == REFERENCE_TYPE)
9805           quals = cp_type_quals (f);
9806         else
9807           quals = cp_type_quals (f) | cp_type_quals (t);
9808         return cp_build_qualified_type_real (f, quals, complain);
9809       }
9810
9811     case UNBOUND_CLASS_TEMPLATE:
9812       {
9813         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9814                                      in_decl, /*entering_scope=*/1);
9815         tree name = TYPE_IDENTIFIER (t);
9816         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9817
9818         if (ctx == error_mark_node || name == error_mark_node)
9819           return error_mark_node;
9820
9821         if (parm_list)
9822           parm_list = tsubst_template_parms (parm_list, args, complain);
9823         return make_unbound_class_template (ctx, name, parm_list, complain);
9824       }
9825
9826     case INDIRECT_REF:
9827     case ADDR_EXPR:
9828     case CALL_EXPR:
9829       gcc_unreachable ();
9830
9831     case ARRAY_REF:
9832       {
9833         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9834         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9835                                /*integral_constant_expression_p=*/false);
9836         if (e1 == error_mark_node || e2 == error_mark_node)
9837           return error_mark_node;
9838
9839         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9840       }
9841
9842     case SCOPE_REF:
9843       {
9844         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9845         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9846         if (e1 == error_mark_node || e2 == error_mark_node)
9847           return error_mark_node;
9848
9849         return build_qualified_name (/*type=*/NULL_TREE,
9850                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9851       }
9852
9853     case TYPEOF_TYPE:
9854       {
9855         tree type;
9856
9857         type = finish_typeof (tsubst_expr 
9858                               (TYPEOF_TYPE_EXPR (t), args,
9859                                complain, in_decl,
9860                                /*integral_constant_expression_p=*/false));
9861         return cp_build_qualified_type_real (type,
9862                                              cp_type_quals (t)
9863                                              | cp_type_quals (type),
9864                                              complain);
9865       }
9866
9867     case DECLTYPE_TYPE:
9868       {
9869         tree type;
9870
9871         ++skip_evaluation;
9872
9873         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
9874                             complain, in_decl,
9875                             /*integral_constant_expression_p=*/false);
9876
9877         --skip_evaluation;
9878
9879         type =
9880           finish_decltype_type (type,
9881                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9882         return cp_build_qualified_type_real (type,
9883                                              cp_type_quals (t)
9884                                              | cp_type_quals (type),
9885                                              complain);
9886       }
9887
9888     case TYPE_ARGUMENT_PACK:
9889     case NONTYPE_ARGUMENT_PACK:
9890       {
9891         tree r = make_node (TREE_CODE (t));
9892         tree packed_out = 
9893           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9894                                 args,
9895                                 complain,
9896                                 in_decl);
9897         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9898
9899         /* For template nontype argument packs, also substitute into
9900            the type.  */
9901         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9902           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9903
9904         return r;
9905       }
9906       break;
9907
9908     default:
9909       sorry ("use of %qs in template",
9910              tree_code_name [(int) TREE_CODE (t)]);
9911       return error_mark_node;
9912     }
9913 }
9914
9915 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9916    type of the expression on the left-hand side of the "." or "->"
9917    operator.  */
9918
9919 static tree
9920 tsubst_baselink (tree baselink, tree object_type,
9921                  tree args, tsubst_flags_t complain, tree in_decl)
9922 {
9923     tree name;
9924     tree qualifying_scope;
9925     tree fns;
9926     tree optype;
9927     tree template_args = 0;
9928     bool template_id_p = false;
9929
9930     /* A baselink indicates a function from a base class.  Both the
9931        BASELINK_ACCESS_BINFO and the base class referenced may
9932        indicate bases of the template class, rather than the
9933        instantiated class.  In addition, lookups that were not
9934        ambiguous before may be ambiguous now.  Therefore, we perform
9935        the lookup again.  */
9936     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9937     qualifying_scope = tsubst (qualifying_scope, args,
9938                                complain, in_decl);
9939     fns = BASELINK_FUNCTIONS (baselink);
9940     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
9941     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9942       {
9943         template_id_p = true;
9944         template_args = TREE_OPERAND (fns, 1);
9945         fns = TREE_OPERAND (fns, 0);
9946         if (template_args)
9947           template_args = tsubst_template_args (template_args, args,
9948                                                 complain, in_decl);
9949       }
9950     name = DECL_NAME (get_first_fn (fns));
9951     if (IDENTIFIER_TYPENAME_P (name))
9952       name = mangle_conv_op_name_for_type (optype);
9953     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9954
9955     /* If lookup found a single function, mark it as used at this
9956        point.  (If it lookup found multiple functions the one selected
9957        later by overload resolution will be marked as used at that
9958        point.)  */
9959     if (BASELINK_P (baselink))
9960       fns = BASELINK_FUNCTIONS (baselink);
9961     if (!template_id_p && !really_overloaded_fn (fns))
9962       mark_used (OVL_CURRENT (fns));
9963
9964     /* Add back the template arguments, if present.  */
9965     if (BASELINK_P (baselink) && template_id_p)
9966       BASELINK_FUNCTIONS (baselink)
9967         = build_nt (TEMPLATE_ID_EXPR,
9968                     BASELINK_FUNCTIONS (baselink),
9969                     template_args);
9970     /* Update the conversion operator type.  */
9971     BASELINK_OPTYPE (baselink) = optype;
9972
9973     if (!object_type)
9974       object_type = current_class_type;
9975     return adjust_result_of_qualified_name_lookup (baselink,
9976                                                    qualifying_scope,
9977                                                    object_type);
9978 }
9979
9980 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9981    true if the qualified-id will be a postfix-expression in-and-of
9982    itself; false if more of the postfix-expression follows the
9983    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9984    of "&".  */
9985
9986 static tree
9987 tsubst_qualified_id (tree qualified_id, tree args,
9988                      tsubst_flags_t complain, tree in_decl,
9989                      bool done, bool address_p)
9990 {
9991   tree expr;
9992   tree scope;
9993   tree name;
9994   bool is_template;
9995   tree template_args;
9996
9997   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9998
9999   /* Figure out what name to look up.  */
10000   name = TREE_OPERAND (qualified_id, 1);
10001   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10002     {
10003       is_template = true;
10004       template_args = TREE_OPERAND (name, 1);
10005       if (template_args)
10006         template_args = tsubst_template_args (template_args, args,
10007                                               complain, in_decl);
10008       name = TREE_OPERAND (name, 0);
10009     }
10010   else
10011     {
10012       is_template = false;
10013       template_args = NULL_TREE;
10014     }
10015
10016   /* Substitute into the qualifying scope.  When there are no ARGS, we
10017      are just trying to simplify a non-dependent expression.  In that
10018      case the qualifying scope may be dependent, and, in any case,
10019      substituting will not help.  */
10020   scope = TREE_OPERAND (qualified_id, 0);
10021   if (args)
10022     {
10023       scope = tsubst (scope, args, complain, in_decl);
10024       expr = tsubst_copy (name, args, complain, in_decl);
10025     }
10026   else
10027     expr = name;
10028
10029   if (dependent_type_p (scope))
10030     return build_qualified_name (/*type=*/NULL_TREE,
10031                                  scope, expr,
10032                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10033
10034   if (!BASELINK_P (name) && !DECL_P (expr))
10035     {
10036       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10037         /* If this were actually a destructor call, it would have been
10038            parsed as such by the parser.  */
10039         expr = error_mark_node;
10040       else
10041         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10042       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10043                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10044         {
10045           if (complain & tf_error)
10046             {
10047               error ("dependent-name %qE is parsed as a non-type, but "
10048                      "instantiation yields a type", qualified_id);
10049               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10050             }
10051           return error_mark_node;
10052         }
10053     }
10054
10055   if (DECL_P (expr))
10056     {
10057       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10058                                            scope);
10059       /* Remember that there was a reference to this entity.  */
10060       mark_used (expr);
10061     }
10062
10063   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10064     {
10065       if (complain & tf_error)
10066         qualified_name_lookup_error (scope,
10067                                      TREE_OPERAND (qualified_id, 1),
10068                                      expr, input_location);
10069       return error_mark_node;
10070     }
10071
10072   if (is_template)
10073     expr = lookup_template_function (expr, template_args);
10074
10075   if (expr == error_mark_node && complain & tf_error)
10076     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10077                                  expr, input_location);
10078   else if (TYPE_P (scope))
10079     {
10080       expr = (adjust_result_of_qualified_name_lookup
10081               (expr, scope, current_class_type));
10082       expr = (finish_qualified_id_expr
10083               (scope, expr, done, address_p,
10084                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10085                /*template_arg_p=*/false));
10086     }
10087
10088   /* Expressions do not generally have reference type.  */
10089   if (TREE_CODE (expr) != SCOPE_REF
10090       /* However, if we're about to form a pointer-to-member, we just
10091          want the referenced member referenced.  */
10092       && TREE_CODE (expr) != OFFSET_REF)
10093     expr = convert_from_reference (expr);
10094
10095   return expr;
10096 }
10097
10098 /* Like tsubst, but deals with expressions.  This function just replaces
10099    template parms; to finish processing the resultant expression, use
10100    tsubst_expr.  */
10101
10102 static tree
10103 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10104 {
10105   enum tree_code code;
10106   tree r;
10107
10108   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10109     return t;
10110
10111   code = TREE_CODE (t);
10112
10113   switch (code)
10114     {
10115     case PARM_DECL:
10116       r = retrieve_local_specialization (t);
10117
10118       if (r == NULL)
10119         {
10120           tree c;
10121           /* This can happen for a parameter name used later in a function
10122              declaration (such as in a late-specified return type).  Just
10123              make a dummy decl, since it's only used for its type.  */
10124           gcc_assert (skip_evaluation);   
10125           /* We copy T because want to tsubst the PARM_DECL only,
10126              not the following PARM_DECLs that are chained to T.  */
10127           c = copy_node (t);
10128           r = tsubst_decl (c, args, complain);
10129           /* Give it the template pattern as its context; its true context
10130              hasn't been instantiated yet and this is good enough for
10131              mangling.  */
10132           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10133         }
10134       
10135       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10136         r = ARGUMENT_PACK_SELECT_ARG (r);
10137       mark_used (r);
10138       return r;
10139
10140     case CONST_DECL:
10141       {
10142         tree enum_type;
10143         tree v;
10144
10145         if (DECL_TEMPLATE_PARM_P (t))
10146           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10147         /* There is no need to substitute into namespace-scope
10148            enumerators.  */
10149         if (DECL_NAMESPACE_SCOPE_P (t))
10150           return t;
10151         /* If ARGS is NULL, then T is known to be non-dependent.  */
10152         if (args == NULL_TREE)
10153           return integral_constant_value (t);
10154
10155         /* Unfortunately, we cannot just call lookup_name here.
10156            Consider:
10157
10158              template <int I> int f() {
10159              enum E { a = I };
10160              struct S { void g() { E e = a; } };
10161              };
10162
10163            When we instantiate f<7>::S::g(), say, lookup_name is not
10164            clever enough to find f<7>::a.  */
10165         enum_type
10166           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10167                               /*entering_scope=*/0);
10168
10169         for (v = TYPE_VALUES (enum_type);
10170              v != NULL_TREE;
10171              v = TREE_CHAIN (v))
10172           if (TREE_PURPOSE (v) == DECL_NAME (t))
10173             return TREE_VALUE (v);
10174
10175           /* We didn't find the name.  That should never happen; if
10176              name-lookup found it during preliminary parsing, we
10177              should find it again here during instantiation.  */
10178         gcc_unreachable ();
10179       }
10180       return t;
10181
10182     case FIELD_DECL:
10183       if (DECL_CONTEXT (t))
10184         {
10185           tree ctx;
10186
10187           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10188                                   /*entering_scope=*/1);
10189           if (ctx != DECL_CONTEXT (t))
10190             {
10191               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10192               if (!r)
10193                 {
10194                   if (complain & tf_error)
10195                     error ("using invalid field %qD", t);
10196                   return error_mark_node;
10197                 }
10198               return r;
10199             }
10200         }
10201
10202       return t;
10203
10204     case VAR_DECL:
10205     case FUNCTION_DECL:
10206       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10207           || local_variable_p (t))
10208         t = tsubst (t, args, complain, in_decl);
10209       mark_used (t);
10210       return t;
10211
10212     case BASELINK:
10213       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10214
10215     case TEMPLATE_DECL:
10216       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10217         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10218                        args, complain, in_decl);
10219       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10220         return tsubst (t, args, complain, in_decl);
10221       else if (DECL_CLASS_SCOPE_P (t)
10222                && uses_template_parms (DECL_CONTEXT (t)))
10223         {
10224           /* Template template argument like the following example need
10225              special treatment:
10226
10227                template <template <class> class TT> struct C {};
10228                template <class T> struct D {
10229                  template <class U> struct E {};
10230                  C<E> c;                                // #1
10231                };
10232                D<int> d;                                // #2
10233
10234              We are processing the template argument `E' in #1 for
10235              the template instantiation #2.  Originally, `E' is a
10236              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10237              have to substitute this with one having context `D<int>'.  */
10238
10239           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10240           return lookup_field (context, DECL_NAME(t), 0, false);
10241         }
10242       else
10243         /* Ordinary template template argument.  */
10244         return t;
10245
10246     case CAST_EXPR:
10247     case REINTERPRET_CAST_EXPR:
10248     case CONST_CAST_EXPR:
10249     case STATIC_CAST_EXPR:
10250     case DYNAMIC_CAST_EXPR:
10251     case NOP_EXPR:
10252       return build1
10253         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10254          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10255
10256     case SIZEOF_EXPR:
10257       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10258         {
10259           /* We only want to compute the number of arguments.  */
10260           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10261                                                 complain, in_decl);
10262           int len = 0;
10263
10264           if (TREE_CODE (expanded) == TREE_VEC)
10265             len = TREE_VEC_LENGTH (expanded);
10266
10267           if (expanded == error_mark_node)
10268             return error_mark_node;
10269           else if (PACK_EXPANSION_P (expanded)
10270                    || (TREE_CODE (expanded) == TREE_VEC
10271                        && len > 0
10272                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10273             {
10274               if (TREE_CODE (expanded) == TREE_VEC)
10275                 expanded = TREE_VEC_ELT (expanded, len - 1);
10276
10277               if (TYPE_P (expanded))
10278                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10279                                                    complain & tf_error);
10280               else
10281                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10282                                                    complain & tf_error);
10283             }
10284           else
10285             return build_int_cst (size_type_node, len);
10286         }
10287       /* Fall through */
10288
10289     case INDIRECT_REF:
10290     case NEGATE_EXPR:
10291     case TRUTH_NOT_EXPR:
10292     case BIT_NOT_EXPR:
10293     case ADDR_EXPR:
10294     case UNARY_PLUS_EXPR:      /* Unary + */
10295     case ALIGNOF_EXPR:
10296     case ARROW_EXPR:
10297     case THROW_EXPR:
10298     case TYPEID_EXPR:
10299     case REALPART_EXPR:
10300     case IMAGPART_EXPR:
10301       return build1
10302         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10303          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10304
10305     case COMPONENT_REF:
10306       {
10307         tree object;
10308         tree name;
10309
10310         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10311         name = TREE_OPERAND (t, 1);
10312         if (TREE_CODE (name) == BIT_NOT_EXPR)
10313           {
10314             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10315                                 complain, in_decl);
10316             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10317           }
10318         else if (TREE_CODE (name) == SCOPE_REF
10319                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10320           {
10321             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10322                                      complain, in_decl);
10323             name = TREE_OPERAND (name, 1);
10324             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10325                                 complain, in_decl);
10326             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10327             name = build_qualified_name (/*type=*/NULL_TREE,
10328                                          base, name,
10329                                          /*template_p=*/false);
10330           }
10331         else if (TREE_CODE (name) == BASELINK)
10332           name = tsubst_baselink (name,
10333                                   non_reference (TREE_TYPE (object)),
10334                                   args, complain,
10335                                   in_decl);
10336         else
10337           name = tsubst_copy (name, args, complain, in_decl);
10338         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10339       }
10340
10341     case PLUS_EXPR:
10342     case MINUS_EXPR:
10343     case MULT_EXPR:
10344     case TRUNC_DIV_EXPR:
10345     case CEIL_DIV_EXPR:
10346     case FLOOR_DIV_EXPR:
10347     case ROUND_DIV_EXPR:
10348     case EXACT_DIV_EXPR:
10349     case BIT_AND_EXPR:
10350     case BIT_IOR_EXPR:
10351     case BIT_XOR_EXPR:
10352     case TRUNC_MOD_EXPR:
10353     case FLOOR_MOD_EXPR:
10354     case TRUTH_ANDIF_EXPR:
10355     case TRUTH_ORIF_EXPR:
10356     case TRUTH_AND_EXPR:
10357     case TRUTH_OR_EXPR:
10358     case RSHIFT_EXPR:
10359     case LSHIFT_EXPR:
10360     case RROTATE_EXPR:
10361     case LROTATE_EXPR:
10362     case EQ_EXPR:
10363     case NE_EXPR:
10364     case MAX_EXPR:
10365     case MIN_EXPR:
10366     case LE_EXPR:
10367     case GE_EXPR:
10368     case LT_EXPR:
10369     case GT_EXPR:
10370     case COMPOUND_EXPR:
10371     case DOTSTAR_EXPR:
10372     case MEMBER_REF:
10373     case PREDECREMENT_EXPR:
10374     case PREINCREMENT_EXPR:
10375     case POSTDECREMENT_EXPR:
10376     case POSTINCREMENT_EXPR:
10377       return build_nt
10378         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10379          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10380
10381     case SCOPE_REF:
10382       return build_qualified_name (/*type=*/NULL_TREE,
10383                                    tsubst_copy (TREE_OPERAND (t, 0),
10384                                                 args, complain, in_decl),
10385                                    tsubst_copy (TREE_OPERAND (t, 1),
10386                                                 args, complain, in_decl),
10387                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10388
10389     case ARRAY_REF:
10390       return build_nt
10391         (ARRAY_REF,
10392          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10393          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10394          NULL_TREE, NULL_TREE);
10395
10396     case CALL_EXPR:
10397       {
10398         int n = VL_EXP_OPERAND_LENGTH (t);
10399         tree result = build_vl_exp (CALL_EXPR, n);
10400         int i;
10401         for (i = 0; i < n; i++)
10402           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10403                                              complain, in_decl);
10404         return result;
10405       }
10406
10407     case COND_EXPR:
10408     case MODOP_EXPR:
10409     case PSEUDO_DTOR_EXPR:
10410       {
10411         r = build_nt
10412           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10413            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10414            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10415         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10416         return r;
10417       }
10418
10419     case NEW_EXPR:
10420       {
10421         r = build_nt
10422         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10423          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10424          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10425         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10426         return r;
10427       }
10428
10429     case DELETE_EXPR:
10430       {
10431         r = build_nt
10432         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10433          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10434         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10435         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10436         return r;
10437       }
10438
10439     case TEMPLATE_ID_EXPR:
10440       {
10441         /* Substituted template arguments */
10442         tree fn = TREE_OPERAND (t, 0);
10443         tree targs = TREE_OPERAND (t, 1);
10444
10445         fn = tsubst_copy (fn, args, complain, in_decl);
10446         if (targs)
10447           targs = tsubst_template_args (targs, args, complain, in_decl);
10448
10449         return lookup_template_function (fn, targs);
10450       }
10451
10452     case TREE_LIST:
10453       {
10454         tree purpose, value, chain;
10455
10456         if (t == void_list_node)
10457           return t;
10458
10459         purpose = TREE_PURPOSE (t);
10460         if (purpose)
10461           purpose = tsubst_copy (purpose, args, complain, in_decl);
10462         value = TREE_VALUE (t);
10463         if (value)
10464           value = tsubst_copy (value, args, complain, in_decl);
10465         chain = TREE_CHAIN (t);
10466         if (chain && chain != void_type_node)
10467           chain = tsubst_copy (chain, args, complain, in_decl);
10468         if (purpose == TREE_PURPOSE (t)
10469             && value == TREE_VALUE (t)
10470             && chain == TREE_CHAIN (t))
10471           return t;
10472         return tree_cons (purpose, value, chain);
10473       }
10474
10475     case RECORD_TYPE:
10476     case UNION_TYPE:
10477     case ENUMERAL_TYPE:
10478     case INTEGER_TYPE:
10479     case TEMPLATE_TYPE_PARM:
10480     case TEMPLATE_TEMPLATE_PARM:
10481     case BOUND_TEMPLATE_TEMPLATE_PARM:
10482     case TEMPLATE_PARM_INDEX:
10483     case POINTER_TYPE:
10484     case REFERENCE_TYPE:
10485     case OFFSET_TYPE:
10486     case FUNCTION_TYPE:
10487     case METHOD_TYPE:
10488     case ARRAY_TYPE:
10489     case TYPENAME_TYPE:
10490     case UNBOUND_CLASS_TEMPLATE:
10491     case TYPEOF_TYPE:
10492     case DECLTYPE_TYPE:
10493     case TYPE_DECL:
10494       return tsubst (t, args, complain, in_decl);
10495
10496     case IDENTIFIER_NODE:
10497       if (IDENTIFIER_TYPENAME_P (t))
10498         {
10499           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10500           return mangle_conv_op_name_for_type (new_type);
10501         }
10502       else
10503         return t;
10504
10505     case CONSTRUCTOR:
10506       /* This is handled by tsubst_copy_and_build.  */
10507       gcc_unreachable ();
10508
10509     case VA_ARG_EXPR:
10510       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10511                                           in_decl),
10512                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10513
10514     case CLEANUP_POINT_EXPR:
10515       /* We shouldn't have built any of these during initial template
10516          generation.  Instead, they should be built during instantiation
10517          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10518       gcc_unreachable ();
10519
10520     case OFFSET_REF:
10521       mark_used (TREE_OPERAND (t, 1));
10522       return t;
10523
10524     case EXPR_PACK_EXPANSION:
10525       error ("invalid use of pack expansion expression");
10526       return error_mark_node;
10527
10528     case NONTYPE_ARGUMENT_PACK:
10529       error ("use %<...%> to expand argument pack");
10530       return error_mark_node;
10531
10532     default:
10533       return t;
10534     }
10535 }
10536
10537 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10538
10539 static tree
10540 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10541                     tree in_decl)
10542 {
10543   tree new_clauses = NULL, nc, oc;
10544
10545   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10546     {
10547       nc = copy_node (oc);
10548       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10549       new_clauses = nc;
10550
10551       switch (OMP_CLAUSE_CODE (nc))
10552         {
10553         case OMP_CLAUSE_LASTPRIVATE:
10554           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10555             {
10556               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10557               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10558                            in_decl, /*integral_constant_expression_p=*/false);
10559               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10560                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10561             }
10562           /* FALLTHRU */
10563         case OMP_CLAUSE_PRIVATE:
10564         case OMP_CLAUSE_SHARED:
10565         case OMP_CLAUSE_FIRSTPRIVATE:
10566         case OMP_CLAUSE_REDUCTION:
10567         case OMP_CLAUSE_COPYIN:
10568         case OMP_CLAUSE_COPYPRIVATE:
10569         case OMP_CLAUSE_IF:
10570         case OMP_CLAUSE_NUM_THREADS:
10571         case OMP_CLAUSE_SCHEDULE:
10572         case OMP_CLAUSE_COLLAPSE:
10573           OMP_CLAUSE_OPERAND (nc, 0)
10574             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10575                            in_decl, /*integral_constant_expression_p=*/false);
10576           break;
10577         case OMP_CLAUSE_NOWAIT:
10578         case OMP_CLAUSE_ORDERED:
10579         case OMP_CLAUSE_DEFAULT:
10580         case OMP_CLAUSE_UNTIED:
10581           break;
10582         default:
10583           gcc_unreachable ();
10584         }
10585     }
10586
10587   return finish_omp_clauses (nreverse (new_clauses));
10588 }
10589
10590 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10591
10592 static tree
10593 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10594                           tree in_decl)
10595 {
10596 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10597
10598   tree purpose, value, chain;
10599
10600   if (t == NULL)
10601     return t;
10602
10603   if (TREE_CODE (t) != TREE_LIST)
10604     return tsubst_copy_and_build (t, args, complain, in_decl,
10605                                   /*function_p=*/false,
10606                                   /*integral_constant_expression_p=*/false);
10607
10608   if (t == void_list_node)
10609     return t;
10610
10611   purpose = TREE_PURPOSE (t);
10612   if (purpose)
10613     purpose = RECUR (purpose);
10614   value = TREE_VALUE (t);
10615   if (value)
10616     value = RECUR (value);
10617   chain = TREE_CHAIN (t);
10618   if (chain && chain != void_type_node)
10619     chain = RECUR (chain);
10620   return tree_cons (purpose, value, chain);
10621 #undef RECUR
10622 }
10623
10624 /* Substitute one OMP_FOR iterator.  */
10625
10626 static void
10627 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
10628                          tree condv, tree incrv, tree *clauses,
10629                          tree args, tsubst_flags_t complain, tree in_decl,
10630                          bool integral_constant_expression_p)
10631 {
10632 #define RECUR(NODE)                             \
10633   tsubst_expr ((NODE), args, complain, in_decl, \
10634                integral_constant_expression_p)
10635   tree decl, init, cond, incr, auto_node;
10636
10637   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
10638   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10639   decl = RECUR (TREE_OPERAND (init, 0));
10640   init = TREE_OPERAND (init, 1);
10641   auto_node = type_uses_auto (TREE_TYPE (decl));
10642   if (auto_node && init)
10643     {
10644       tree init_expr = init;
10645       if (TREE_CODE (init_expr) == DECL_EXPR)
10646         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
10647       init_expr = RECUR (init_expr);
10648       TREE_TYPE (decl)
10649         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
10650     }
10651   gcc_assert (!type_dependent_expression_p (decl));
10652
10653   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
10654     {
10655       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
10656       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10657       if (TREE_CODE (incr) == MODIFY_EXPR)
10658         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
10659                                     RECUR (TREE_OPERAND (incr, 1)),
10660                                     complain);
10661       else
10662         incr = RECUR (incr);
10663       TREE_VEC_ELT (declv, i) = decl;
10664       TREE_VEC_ELT (initv, i) = init;
10665       TREE_VEC_ELT (condv, i) = cond;
10666       TREE_VEC_ELT (incrv, i) = incr;
10667       return;
10668     }
10669
10670   if (init && TREE_CODE (init) != DECL_EXPR)
10671     {
10672       tree c;
10673       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
10674         {
10675           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
10676                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
10677               && OMP_CLAUSE_DECL (c) == decl)
10678             break;
10679           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
10680                    && OMP_CLAUSE_DECL (c) == decl)
10681             error ("iteration variable %qD should not be firstprivate", decl);
10682           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
10683                    && OMP_CLAUSE_DECL (c) == decl)
10684             error ("iteration variable %qD should not be reduction", decl);
10685         }
10686       if (c == NULL)
10687         {
10688           c = build_omp_clause (OMP_CLAUSE_PRIVATE);
10689           OMP_CLAUSE_DECL (c) = decl;
10690           c = finish_omp_clauses (c);
10691           if (c)
10692             {
10693               OMP_CLAUSE_CHAIN (c) = *clauses;
10694               *clauses = c;
10695             }
10696         }
10697     }
10698   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
10699   if (COMPARISON_CLASS_P (cond))
10700     cond = build2 (TREE_CODE (cond), boolean_type_node,
10701                    RECUR (TREE_OPERAND (cond, 0)),
10702                    RECUR (TREE_OPERAND (cond, 1)));
10703   else
10704     cond = RECUR (cond);
10705   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10706   switch (TREE_CODE (incr))
10707     {
10708     case PREINCREMENT_EXPR:
10709     case PREDECREMENT_EXPR:
10710     case POSTINCREMENT_EXPR:
10711     case POSTDECREMENT_EXPR:
10712       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
10713                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
10714       break;
10715     case MODIFY_EXPR:
10716       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10717           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10718         {
10719           tree rhs = TREE_OPERAND (incr, 1);
10720           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10721                          RECUR (TREE_OPERAND (incr, 0)),
10722                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10723                                  RECUR (TREE_OPERAND (rhs, 0)),
10724                                  RECUR (TREE_OPERAND (rhs, 1))));
10725         }
10726       else
10727         incr = RECUR (incr);
10728       break;
10729     case MODOP_EXPR:
10730       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10731           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10732         {
10733           tree lhs = RECUR (TREE_OPERAND (incr, 0));
10734           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
10735                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
10736                                  TREE_TYPE (decl), lhs,
10737                                  RECUR (TREE_OPERAND (incr, 2))));
10738         }
10739       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
10740                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
10741                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
10742         {
10743           tree rhs = TREE_OPERAND (incr, 2);
10744           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10745                          RECUR (TREE_OPERAND (incr, 0)),
10746                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10747                                  RECUR (TREE_OPERAND (rhs, 0)),
10748                                  RECUR (TREE_OPERAND (rhs, 1))));
10749         }
10750       else
10751         incr = RECUR (incr);
10752       break;
10753     default:
10754       incr = RECUR (incr);
10755       break;
10756     }
10757
10758   TREE_VEC_ELT (declv, i) = decl;
10759   TREE_VEC_ELT (initv, i) = init;
10760   TREE_VEC_ELT (condv, i) = cond;
10761   TREE_VEC_ELT (incrv, i) = incr;
10762 #undef RECUR
10763 }
10764
10765 /* Like tsubst_copy for expressions, etc. but also does semantic
10766    processing.  */
10767
10768 static tree
10769 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10770              bool integral_constant_expression_p)
10771 {
10772 #define RECUR(NODE)                             \
10773   tsubst_expr ((NODE), args, complain, in_decl, \
10774                integral_constant_expression_p)
10775
10776   tree stmt, tmp;
10777
10778   if (t == NULL_TREE || t == error_mark_node)
10779     return t;
10780
10781   if (EXPR_HAS_LOCATION (t))
10782     input_location = EXPR_LOCATION (t);
10783   if (STATEMENT_CODE_P (TREE_CODE (t)))
10784     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10785
10786   switch (TREE_CODE (t))
10787     {
10788     case STATEMENT_LIST:
10789       {
10790         tree_stmt_iterator i;
10791         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10792           RECUR (tsi_stmt (i));
10793         break;
10794       }
10795
10796     case CTOR_INITIALIZER:
10797       finish_mem_initializers (tsubst_initializer_list
10798                                (TREE_OPERAND (t, 0), args));
10799       break;
10800
10801     case RETURN_EXPR:
10802       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10803       break;
10804
10805     case EXPR_STMT:
10806       tmp = RECUR (EXPR_STMT_EXPR (t));
10807       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10808         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10809       else
10810         finish_expr_stmt (tmp);
10811       break;
10812
10813     case USING_STMT:
10814       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10815       break;
10816
10817     case DECL_EXPR:
10818       {
10819         tree decl;
10820         tree init;
10821
10822         decl = DECL_EXPR_DECL (t);
10823         if (TREE_CODE (decl) == LABEL_DECL)
10824           finish_label_decl (DECL_NAME (decl));
10825         else if (TREE_CODE (decl) == USING_DECL)
10826           {
10827             tree scope = USING_DECL_SCOPE (decl);
10828             tree name = DECL_NAME (decl);
10829             tree decl;
10830
10831             scope = RECUR (scope);
10832             decl = lookup_qualified_name (scope, name,
10833                                           /*is_type_p=*/false,
10834                                           /*complain=*/false);
10835             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10836               qualified_name_lookup_error (scope, name, decl, input_location);
10837             else
10838               do_local_using_decl (decl, scope, name);
10839           }
10840         else
10841           {
10842             init = DECL_INITIAL (decl);
10843             decl = tsubst (decl, args, complain, in_decl);
10844             if (decl != error_mark_node)
10845               {
10846                 /* By marking the declaration as instantiated, we avoid
10847                    trying to instantiate it.  Since instantiate_decl can't
10848                    handle local variables, and since we've already done
10849                    all that needs to be done, that's the right thing to
10850                    do.  */
10851                 if (TREE_CODE (decl) == VAR_DECL)
10852                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10853                 if (TREE_CODE (decl) == VAR_DECL
10854                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10855                   /* Anonymous aggregates are a special case.  */
10856                   finish_anon_union (decl);
10857                 else
10858                   {
10859                     maybe_push_decl (decl);
10860                     if (TREE_CODE (decl) == VAR_DECL
10861                         && DECL_PRETTY_FUNCTION_P (decl))
10862                       {
10863                         /* For __PRETTY_FUNCTION__ we have to adjust the
10864                            initializer.  */
10865                         const char *const name
10866                           = cxx_printable_name (current_function_decl, 2);
10867                         init = cp_fname_init (name, &TREE_TYPE (decl));
10868                       }
10869                     else
10870                       {
10871                         tree t = RECUR (init);
10872
10873                         if (init && !t)
10874                           /* If we had an initializer but it
10875                              instantiated to nothing,
10876                              value-initialize the object.  This will
10877                              only occur when the initializer was a
10878                              pack expansion where the parameter packs
10879                              used in that expansion were of length
10880                              zero.  */
10881                           init = build_value_init (TREE_TYPE (decl));
10882                         else
10883                           init = t;
10884                       }
10885
10886                     finish_decl (decl, init, NULL_TREE);
10887                   }
10888               }
10889           }
10890
10891         /* A DECL_EXPR can also be used as an expression, in the condition
10892            clause of an if/for/while construct.  */
10893         return decl;
10894       }
10895
10896     case FOR_STMT:
10897       stmt = begin_for_stmt ();
10898                           RECUR (FOR_INIT_STMT (t));
10899       finish_for_init_stmt (stmt);
10900       tmp = RECUR (FOR_COND (t));
10901       finish_for_cond (tmp, stmt);
10902       tmp = RECUR (FOR_EXPR (t));
10903       finish_for_expr (tmp, stmt);
10904       RECUR (FOR_BODY (t));
10905       finish_for_stmt (stmt);
10906       break;
10907
10908     case WHILE_STMT:
10909       stmt = begin_while_stmt ();
10910       tmp = RECUR (WHILE_COND (t));
10911       finish_while_stmt_cond (tmp, stmt);
10912       RECUR (WHILE_BODY (t));
10913       finish_while_stmt (stmt);
10914       break;
10915
10916     case DO_STMT:
10917       stmt = begin_do_stmt ();
10918       RECUR (DO_BODY (t));
10919       finish_do_body (stmt);
10920       tmp = RECUR (DO_COND (t));
10921       finish_do_stmt (tmp, stmt);
10922       break;
10923
10924     case IF_STMT:
10925       stmt = begin_if_stmt ();
10926       tmp = RECUR (IF_COND (t));
10927       finish_if_stmt_cond (tmp, stmt);
10928       RECUR (THEN_CLAUSE (t));
10929       finish_then_clause (stmt);
10930
10931       if (ELSE_CLAUSE (t))
10932         {
10933           begin_else_clause (stmt);
10934           RECUR (ELSE_CLAUSE (t));
10935           finish_else_clause (stmt);
10936         }
10937
10938       finish_if_stmt (stmt);
10939       break;
10940
10941     case BIND_EXPR:
10942       if (BIND_EXPR_BODY_BLOCK (t))
10943         stmt = begin_function_body ();
10944       else
10945         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10946                                     ? BCS_TRY_BLOCK : 0);
10947
10948       RECUR (BIND_EXPR_BODY (t));
10949
10950       if (BIND_EXPR_BODY_BLOCK (t))
10951         finish_function_body (stmt);
10952       else
10953         finish_compound_stmt (stmt);
10954       break;
10955
10956     case BREAK_STMT:
10957       finish_break_stmt ();
10958       break;
10959
10960     case CONTINUE_STMT:
10961       finish_continue_stmt ();
10962       break;
10963
10964     case SWITCH_STMT:
10965       stmt = begin_switch_stmt ();
10966       tmp = RECUR (SWITCH_STMT_COND (t));
10967       finish_switch_cond (tmp, stmt);
10968       RECUR (SWITCH_STMT_BODY (t));
10969       finish_switch_stmt (stmt);
10970       break;
10971
10972     case CASE_LABEL_EXPR:
10973       finish_case_label (RECUR (CASE_LOW (t)),
10974                          RECUR (CASE_HIGH (t)));
10975       break;
10976
10977     case LABEL_EXPR:
10978       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10979       break;
10980
10981     case GOTO_EXPR:
10982       tmp = GOTO_DESTINATION (t);
10983       if (TREE_CODE (tmp) != LABEL_DECL)
10984         /* Computed goto's must be tsubst'd into.  On the other hand,
10985            non-computed gotos must not be; the identifier in question
10986            will have no binding.  */
10987         tmp = RECUR (tmp);
10988       else
10989         tmp = DECL_NAME (tmp);
10990       finish_goto_stmt (tmp);
10991       break;
10992
10993     case ASM_EXPR:
10994       tmp = finish_asm_stmt
10995         (ASM_VOLATILE_P (t),
10996          RECUR (ASM_STRING (t)),
10997          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10998          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10999          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
11000       {
11001         tree asm_expr = tmp;
11002         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11003           asm_expr = TREE_OPERAND (asm_expr, 0);
11004         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11005       }
11006       break;
11007
11008     case TRY_BLOCK:
11009       if (CLEANUP_P (t))
11010         {
11011           stmt = begin_try_block ();
11012           RECUR (TRY_STMTS (t));
11013           finish_cleanup_try_block (stmt);
11014           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11015         }
11016       else
11017         {
11018           tree compound_stmt = NULL_TREE;
11019
11020           if (FN_TRY_BLOCK_P (t))
11021             stmt = begin_function_try_block (&compound_stmt);
11022           else
11023             stmt = begin_try_block ();
11024
11025           RECUR (TRY_STMTS (t));
11026
11027           if (FN_TRY_BLOCK_P (t))
11028             finish_function_try_block (stmt);
11029           else
11030             finish_try_block (stmt);
11031
11032           RECUR (TRY_HANDLERS (t));
11033           if (FN_TRY_BLOCK_P (t))
11034             finish_function_handler_sequence (stmt, compound_stmt);
11035           else
11036             finish_handler_sequence (stmt);
11037         }
11038       break;
11039
11040     case HANDLER:
11041       {
11042         tree decl = HANDLER_PARMS (t);
11043
11044         if (decl)
11045           {
11046             decl = tsubst (decl, args, complain, in_decl);
11047             /* Prevent instantiate_decl from trying to instantiate
11048                this variable.  We've already done all that needs to be
11049                done.  */
11050             if (decl != error_mark_node)
11051               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11052           }
11053         stmt = begin_handler ();
11054         finish_handler_parms (decl, stmt);
11055         RECUR (HANDLER_BODY (t));
11056         finish_handler (stmt);
11057       }
11058       break;
11059
11060     case TAG_DEFN:
11061       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11062       break;
11063
11064     case STATIC_ASSERT:
11065       {
11066         tree condition = 
11067           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11068                        args,
11069                        complain, in_decl,
11070                        /*integral_constant_expression_p=*/true);
11071         finish_static_assert (condition,
11072                               STATIC_ASSERT_MESSAGE (t),
11073                               STATIC_ASSERT_SOURCE_LOCATION (t),
11074                               /*member_p=*/false);
11075       }
11076       break;
11077
11078     case OMP_PARALLEL:
11079       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11080                                 args, complain, in_decl);
11081       stmt = begin_omp_parallel ();
11082       RECUR (OMP_PARALLEL_BODY (t));
11083       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11084         = OMP_PARALLEL_COMBINED (t);
11085       break;
11086
11087     case OMP_TASK:
11088       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11089                                 args, complain, in_decl);
11090       stmt = begin_omp_task ();
11091       RECUR (OMP_TASK_BODY (t));
11092       finish_omp_task (tmp, stmt);
11093       break;
11094
11095     case OMP_FOR:
11096       {
11097         tree clauses, body, pre_body;
11098         tree declv, initv, condv, incrv;
11099         int i;
11100
11101         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11102                                       args, complain, in_decl);
11103         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11104         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11105         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11106         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11107
11108         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11109           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11110                                    &clauses, args, complain, in_decl,
11111                                    integral_constant_expression_p);
11112
11113         stmt = begin_omp_structured_block ();
11114
11115         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11116           if (TREE_VEC_ELT (initv, i) == NULL
11117               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11118             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11119           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11120             {
11121               tree init = RECUR (TREE_VEC_ELT (initv, i));
11122               gcc_assert (init == TREE_VEC_ELT (declv, i));
11123               TREE_VEC_ELT (initv, i) = NULL_TREE;
11124             }
11125           else
11126             {
11127               tree decl_expr = TREE_VEC_ELT (initv, i);
11128               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11129               gcc_assert (init != NULL);
11130               TREE_VEC_ELT (initv, i) = RECUR (init);
11131               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11132               RECUR (decl_expr);
11133               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11134             }
11135
11136         pre_body = push_stmt_list ();
11137         RECUR (OMP_FOR_PRE_BODY (t));
11138         pre_body = pop_stmt_list (pre_body);
11139
11140         body = push_stmt_list ();
11141         RECUR (OMP_FOR_BODY (t));
11142         body = pop_stmt_list (body);
11143
11144         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11145                             body, pre_body, clauses);
11146
11147         add_stmt (finish_omp_structured_block (stmt));
11148       }
11149       break;
11150
11151     case OMP_SECTIONS:
11152     case OMP_SINGLE:
11153       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11154       stmt = push_stmt_list ();
11155       RECUR (OMP_BODY (t));
11156       stmt = pop_stmt_list (stmt);
11157
11158       t = copy_node (t);
11159       OMP_BODY (t) = stmt;
11160       OMP_CLAUSES (t) = tmp;
11161       add_stmt (t);
11162       break;
11163
11164     case OMP_SECTION:
11165     case OMP_CRITICAL:
11166     case OMP_MASTER:
11167     case OMP_ORDERED:
11168       stmt = push_stmt_list ();
11169       RECUR (OMP_BODY (t));
11170       stmt = pop_stmt_list (stmt);
11171
11172       t = copy_node (t);
11173       OMP_BODY (t) = stmt;
11174       add_stmt (t);
11175       break;
11176
11177     case OMP_ATOMIC:
11178       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11179       {
11180         tree op1 = TREE_OPERAND (t, 1);
11181         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11182         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11183         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11184       }
11185       break;
11186
11187     case EXPR_PACK_EXPANSION:
11188       error ("invalid use of pack expansion expression");
11189       return error_mark_node;
11190
11191     case NONTYPE_ARGUMENT_PACK:
11192       error ("use %<...%> to expand argument pack");
11193       return error_mark_node;
11194
11195     default:
11196       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11197
11198       return tsubst_copy_and_build (t, args, complain, in_decl,
11199                                     /*function_p=*/false,
11200                                     integral_constant_expression_p);
11201     }
11202
11203   return NULL_TREE;
11204 #undef RECUR
11205 }
11206
11207 /* T is a postfix-expression that is not being used in a function
11208    call.  Return the substituted version of T.  */
11209
11210 static tree
11211 tsubst_non_call_postfix_expression (tree t, tree args,
11212                                     tsubst_flags_t complain,
11213                                     tree in_decl)
11214 {
11215   if (TREE_CODE (t) == SCOPE_REF)
11216     t = tsubst_qualified_id (t, args, complain, in_decl,
11217                              /*done=*/false, /*address_p=*/false);
11218   else
11219     t = tsubst_copy_and_build (t, args, complain, in_decl,
11220                                /*function_p=*/false,
11221                                /*integral_constant_expression_p=*/false);
11222
11223   return t;
11224 }
11225
11226 /* Like tsubst but deals with expressions and performs semantic
11227    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11228
11229 tree
11230 tsubst_copy_and_build (tree t,
11231                        tree args,
11232                        tsubst_flags_t complain,
11233                        tree in_decl,
11234                        bool function_p,
11235                        bool integral_constant_expression_p)
11236 {
11237 #define RECUR(NODE)                                             \
11238   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11239                          /*function_p=*/false,                  \
11240                          integral_constant_expression_p)
11241
11242   tree op1;
11243
11244   if (t == NULL_TREE || t == error_mark_node)
11245     return t;
11246
11247   switch (TREE_CODE (t))
11248     {
11249     case USING_DECL:
11250       t = DECL_NAME (t);
11251       /* Fall through.  */
11252     case IDENTIFIER_NODE:
11253       {
11254         tree decl;
11255         cp_id_kind idk;
11256         bool non_integral_constant_expression_p;
11257         const char *error_msg;
11258
11259         if (IDENTIFIER_TYPENAME_P (t))
11260           {
11261             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11262             t = mangle_conv_op_name_for_type (new_type);
11263           }
11264
11265         /* Look up the name.  */
11266         decl = lookup_name (t);
11267
11268         /* By convention, expressions use ERROR_MARK_NODE to indicate
11269            failure, not NULL_TREE.  */
11270         if (decl == NULL_TREE)
11271           decl = error_mark_node;
11272
11273         decl = finish_id_expression (t, decl, NULL_TREE,
11274                                      &idk,
11275                                      integral_constant_expression_p,
11276                                      /*allow_non_integral_constant_expression_p=*/false,
11277                                      &non_integral_constant_expression_p,
11278                                      /*template_p=*/false,
11279                                      /*done=*/true,
11280                                      /*address_p=*/false,
11281                                      /*template_arg_p=*/false,
11282                                      &error_msg,
11283                                      input_location);
11284         if (error_msg)
11285           error (error_msg);
11286         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11287           decl = unqualified_name_lookup_error (decl);
11288         return decl;
11289       }
11290
11291     case TEMPLATE_ID_EXPR:
11292       {
11293         tree object;
11294         tree templ = RECUR (TREE_OPERAND (t, 0));
11295         tree targs = TREE_OPERAND (t, 1);
11296
11297         if (targs)
11298           targs = tsubst_template_args (targs, args, complain, in_decl);
11299
11300         if (TREE_CODE (templ) == COMPONENT_REF)
11301           {
11302             object = TREE_OPERAND (templ, 0);
11303             templ = TREE_OPERAND (templ, 1);
11304           }
11305         else
11306           object = NULL_TREE;
11307         templ = lookup_template_function (templ, targs);
11308
11309         if (object)
11310           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11311                          object, templ, NULL_TREE);
11312         else
11313           return baselink_for_fns (templ);
11314       }
11315
11316     case INDIRECT_REF:
11317       {
11318         tree r = RECUR (TREE_OPERAND (t, 0));
11319
11320         if (REFERENCE_REF_P (t))
11321           {
11322             /* A type conversion to reference type will be enclosed in
11323                such an indirect ref, but the substitution of the cast
11324                will have also added such an indirect ref.  */
11325             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11326               r = convert_from_reference (r);
11327           }
11328         else
11329           r = build_x_indirect_ref (r, "unary *", complain);
11330         return r;
11331       }
11332
11333     case NOP_EXPR:
11334       return build_nop
11335         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11336          RECUR (TREE_OPERAND (t, 0)));
11337
11338     case CAST_EXPR:
11339     case REINTERPRET_CAST_EXPR:
11340     case CONST_CAST_EXPR:
11341     case DYNAMIC_CAST_EXPR:
11342     case STATIC_CAST_EXPR:
11343       {
11344         tree type;
11345         tree op;
11346
11347         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11348         if (integral_constant_expression_p
11349             && !cast_valid_in_integral_constant_expression_p (type))
11350           {
11351             if (complain & tf_error)
11352               error ("a cast to a type other than an integral or "
11353                      "enumeration type cannot appear in a constant-expression");
11354             return error_mark_node; 
11355           }
11356
11357         op = RECUR (TREE_OPERAND (t, 0));
11358
11359         switch (TREE_CODE (t))
11360           {
11361           case CAST_EXPR:
11362             return build_functional_cast (type, op, complain);
11363           case REINTERPRET_CAST_EXPR:
11364             return build_reinterpret_cast (type, op, complain);
11365           case CONST_CAST_EXPR:
11366             return build_const_cast (type, op, complain);
11367           case DYNAMIC_CAST_EXPR:
11368             return build_dynamic_cast (type, op, complain);
11369           case STATIC_CAST_EXPR:
11370             return build_static_cast (type, op, complain);
11371           default:
11372             gcc_unreachable ();
11373           }
11374       }
11375
11376     case POSTDECREMENT_EXPR:
11377     case POSTINCREMENT_EXPR:
11378       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11379                                                 args, complain, in_decl);
11380       return build_x_unary_op (TREE_CODE (t), op1, complain);
11381
11382     case PREDECREMENT_EXPR:
11383     case PREINCREMENT_EXPR:
11384     case NEGATE_EXPR:
11385     case BIT_NOT_EXPR:
11386     case ABS_EXPR:
11387     case TRUTH_NOT_EXPR:
11388     case UNARY_PLUS_EXPR:  /* Unary + */
11389     case REALPART_EXPR:
11390     case IMAGPART_EXPR:
11391       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11392                                complain);
11393
11394     case ADDR_EXPR:
11395       op1 = TREE_OPERAND (t, 0);
11396       if (TREE_CODE (op1) == SCOPE_REF)
11397         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11398                                    /*done=*/true, /*address_p=*/true);
11399       else
11400         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11401                                                   in_decl);
11402       if (TREE_CODE (op1) == LABEL_DECL)
11403         return finish_label_address_expr (DECL_NAME (op1),
11404                                           EXPR_LOCATION (op1));
11405       return build_x_unary_op (ADDR_EXPR, op1, complain);
11406
11407     case PLUS_EXPR:
11408     case MINUS_EXPR:
11409     case MULT_EXPR:
11410     case TRUNC_DIV_EXPR:
11411     case CEIL_DIV_EXPR:
11412     case FLOOR_DIV_EXPR:
11413     case ROUND_DIV_EXPR:
11414     case EXACT_DIV_EXPR:
11415     case BIT_AND_EXPR:
11416     case BIT_IOR_EXPR:
11417     case BIT_XOR_EXPR:
11418     case TRUNC_MOD_EXPR:
11419     case FLOOR_MOD_EXPR:
11420     case TRUTH_ANDIF_EXPR:
11421     case TRUTH_ORIF_EXPR:
11422     case TRUTH_AND_EXPR:
11423     case TRUTH_OR_EXPR:
11424     case RSHIFT_EXPR:
11425     case LSHIFT_EXPR:
11426     case RROTATE_EXPR:
11427     case LROTATE_EXPR:
11428     case EQ_EXPR:
11429     case NE_EXPR:
11430     case MAX_EXPR:
11431     case MIN_EXPR:
11432     case LE_EXPR:
11433     case GE_EXPR:
11434     case LT_EXPR:
11435     case GT_EXPR:
11436     case MEMBER_REF:
11437     case DOTSTAR_EXPR:
11438       return build_x_binary_op
11439         (TREE_CODE (t),
11440          RECUR (TREE_OPERAND (t, 0)),
11441          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11442           ? ERROR_MARK
11443           : TREE_CODE (TREE_OPERAND (t, 0))),
11444          RECUR (TREE_OPERAND (t, 1)),
11445          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11446           ? ERROR_MARK
11447           : TREE_CODE (TREE_OPERAND (t, 1))),
11448          /*overloaded_p=*/NULL,
11449          complain);
11450
11451     case SCOPE_REF:
11452       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11453                                   /*address_p=*/false);
11454     case ARRAY_REF:
11455       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11456                                                 args, complain, in_decl);
11457       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11458
11459     case SIZEOF_EXPR:
11460       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11461         return tsubst_copy (t, args, complain, in_decl);
11462       /* Fall through */
11463       
11464     case ALIGNOF_EXPR:
11465       op1 = TREE_OPERAND (t, 0);
11466       if (!args)
11467         {
11468           /* When there are no ARGS, we are trying to evaluate a
11469              non-dependent expression from the parser.  Trying to do
11470              the substitutions may not work.  */
11471           if (!TYPE_P (op1))
11472             op1 = TREE_TYPE (op1);
11473         }
11474       else
11475         {
11476           ++skip_evaluation;
11477           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11478                                        /*function_p=*/false,
11479                                        /*integral_constant_expression_p=*/false);
11480           --skip_evaluation;
11481         }
11482       if (TYPE_P (op1))
11483         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11484                                            complain & tf_error);
11485       else
11486         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11487                                            complain & tf_error);
11488
11489     case MODOP_EXPR:
11490       {
11491         tree r = build_x_modify_expr
11492           (RECUR (TREE_OPERAND (t, 0)),
11493            TREE_CODE (TREE_OPERAND (t, 1)),
11494            RECUR (TREE_OPERAND (t, 2)),
11495            complain);
11496         /* TREE_NO_WARNING must be set if either the expression was
11497            parenthesized or it uses an operator such as >>= rather
11498            than plain assignment.  In the former case, it was already
11499            set and must be copied.  In the latter case,
11500            build_x_modify_expr sets it and it must not be reset
11501            here.  */
11502         if (TREE_NO_WARNING (t))
11503           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11504         return r;
11505       }
11506
11507     case ARROW_EXPR:
11508       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11509                                                 args, complain, in_decl);
11510       /* Remember that there was a reference to this entity.  */
11511       if (DECL_P (op1))
11512         mark_used (op1);
11513       return build_x_arrow (op1);
11514
11515     case NEW_EXPR:
11516       {
11517         tree init = RECUR (TREE_OPERAND (t, 3));
11518
11519         if (TREE_OPERAND (t, 3) && !init)
11520           /* If there was an initializer in the original tree, but
11521              it instantiated to an empty list, then we should pass on
11522              VOID_ZERO_NODE to tell build_new that it was an empty
11523              initializer () rather than no initializer.  This can only
11524              happen when the initializer is a pack expansion whose
11525              parameter packs are of length zero.  */
11526           init = void_zero_node;
11527
11528         return build_new
11529           (RECUR (TREE_OPERAND (t, 0)),
11530            RECUR (TREE_OPERAND (t, 1)),
11531            RECUR (TREE_OPERAND (t, 2)),
11532            init,
11533            NEW_EXPR_USE_GLOBAL (t),
11534            complain);
11535       }
11536
11537     case DELETE_EXPR:
11538      return delete_sanity
11539        (RECUR (TREE_OPERAND (t, 0)),
11540         RECUR (TREE_OPERAND (t, 1)),
11541         DELETE_EXPR_USE_VEC (t),
11542         DELETE_EXPR_USE_GLOBAL (t));
11543
11544     case COMPOUND_EXPR:
11545       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11546                                     RECUR (TREE_OPERAND (t, 1)),
11547                                     complain);
11548
11549     case CALL_EXPR:
11550       {
11551         tree function;
11552         tree call_args;
11553         bool qualified_p;
11554         bool koenig_p;
11555
11556         function = CALL_EXPR_FN (t);
11557         /* When we parsed the expression,  we determined whether or
11558            not Koenig lookup should be performed.  */
11559         koenig_p = KOENIG_LOOKUP_P (t);
11560         if (TREE_CODE (function) == SCOPE_REF)
11561           {
11562             qualified_p = true;
11563             function = tsubst_qualified_id (function, args, complain, in_decl,
11564                                             /*done=*/false,
11565                                             /*address_p=*/false);
11566           }
11567         else
11568           {
11569             if (TREE_CODE (function) == COMPONENT_REF)
11570               {
11571                 tree op = TREE_OPERAND (function, 1);
11572
11573                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11574                                || (BASELINK_P (op)
11575                                    && BASELINK_QUALIFIED_P (op)));
11576               }
11577             else
11578               qualified_p = false;
11579
11580             function = tsubst_copy_and_build (function, args, complain,
11581                                               in_decl,
11582                                               !qualified_p,
11583                                               integral_constant_expression_p);
11584
11585             if (BASELINK_P (function))
11586               qualified_p = true;
11587           }
11588
11589         /* FIXME:  Rewrite this so as not to construct an arglist.  */
11590         call_args = RECUR (CALL_EXPR_ARGS (t));
11591
11592         /* We do not perform argument-dependent lookup if normal
11593            lookup finds a non-function, in accordance with the
11594            expected resolution of DR 218.  */
11595         if (koenig_p
11596             && ((is_overloaded_fn (function)
11597                  /* If lookup found a member function, the Koenig lookup is
11598                     not appropriate, even if an unqualified-name was used
11599                     to denote the function.  */
11600                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11601                 || TREE_CODE (function) == IDENTIFIER_NODE)
11602             /* Only do this when substitution turns a dependent call
11603                into a non-dependent call.  */
11604             && type_dependent_expression_p_push (t)
11605             && !any_type_dependent_arguments_p (call_args))
11606           function = perform_koenig_lookup (function, call_args);
11607
11608         if (TREE_CODE (function) == IDENTIFIER_NODE)
11609           {
11610             unqualified_name_lookup_error (function);
11611             return error_mark_node;
11612           }
11613
11614         /* Remember that there was a reference to this entity.  */
11615         if (DECL_P (function))
11616           mark_used (function);
11617
11618         if (TREE_CODE (function) == OFFSET_REF)
11619           return build_offset_ref_call_from_tree (function, call_args);
11620         if (TREE_CODE (function) == COMPONENT_REF)
11621           {
11622             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11623               return finish_call_expr (function, call_args,
11624                                        /*disallow_virtual=*/false,
11625                                        /*koenig_p=*/false,
11626                                        complain);
11627             else
11628               return (build_new_method_call
11629                       (TREE_OPERAND (function, 0),
11630                        TREE_OPERAND (function, 1),
11631                        call_args, NULL_TREE,
11632                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11633                        /*fn_p=*/NULL,
11634                        complain));
11635           }
11636         return finish_call_expr (function, call_args,
11637                                  /*disallow_virtual=*/qualified_p,
11638                                  koenig_p,
11639                                  complain);
11640       }
11641
11642     case COND_EXPR:
11643       return build_x_conditional_expr
11644         (RECUR (TREE_OPERAND (t, 0)),
11645          RECUR (TREE_OPERAND (t, 1)),
11646          RECUR (TREE_OPERAND (t, 2)),
11647          complain);
11648
11649     case PSEUDO_DTOR_EXPR:
11650       return finish_pseudo_destructor_expr
11651         (RECUR (TREE_OPERAND (t, 0)),
11652          RECUR (TREE_OPERAND (t, 1)),
11653          RECUR (TREE_OPERAND (t, 2)));
11654
11655     case TREE_LIST:
11656       {
11657         tree purpose, value, chain;
11658
11659         if (t == void_list_node)
11660           return t;
11661
11662         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11663             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11664           {
11665             /* We have pack expansions, so expand those and
11666                create a new list out of it.  */
11667             tree purposevec = NULL_TREE;
11668             tree valuevec = NULL_TREE;
11669             tree chain;
11670             int i, len = -1;
11671
11672             /* Expand the argument expressions.  */
11673             if (TREE_PURPOSE (t))
11674               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11675                                                  complain, in_decl);
11676             if (TREE_VALUE (t))
11677               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11678                                                complain, in_decl);
11679
11680             /* Build the rest of the list.  */
11681             chain = TREE_CHAIN (t);
11682             if (chain && chain != void_type_node)
11683               chain = RECUR (chain);
11684
11685             /* Determine the number of arguments.  */
11686             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11687               {
11688                 len = TREE_VEC_LENGTH (purposevec);
11689                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11690               }
11691             else if (TREE_CODE (valuevec) == TREE_VEC)
11692               len = TREE_VEC_LENGTH (valuevec);
11693             else
11694               {
11695                 /* Since we only performed a partial substitution into
11696                    the argument pack, we only return a single list
11697                    node.  */
11698                 if (purposevec == TREE_PURPOSE (t)
11699                     && valuevec == TREE_VALUE (t)
11700                     && chain == TREE_CHAIN (t))
11701                   return t;
11702
11703                 return tree_cons (purposevec, valuevec, chain);
11704               }
11705             
11706             /* Convert the argument vectors into a TREE_LIST */
11707             i = len;
11708             while (i > 0)
11709               {
11710                 /* Grab the Ith values.  */
11711                 i--;
11712                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11713                                      : NULL_TREE;
11714                 value 
11715                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11716                              : NULL_TREE;
11717
11718                 /* Build the list (backwards).  */
11719                 chain = tree_cons (purpose, value, chain);
11720               }
11721
11722             return chain;
11723           }
11724
11725         purpose = TREE_PURPOSE (t);
11726         if (purpose)
11727           purpose = RECUR (purpose);
11728         value = TREE_VALUE (t);
11729         if (value)
11730           value = RECUR (value);
11731         chain = TREE_CHAIN (t);
11732         if (chain && chain != void_type_node)
11733           chain = RECUR (chain);
11734         if (purpose == TREE_PURPOSE (t)
11735             && value == TREE_VALUE (t)
11736             && chain == TREE_CHAIN (t))
11737           return t;
11738         return tree_cons (purpose, value, chain);
11739       }
11740
11741     case COMPONENT_REF:
11742       {
11743         tree object;
11744         tree object_type;
11745         tree member;
11746
11747         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11748                                                      args, complain, in_decl);
11749         /* Remember that there was a reference to this entity.  */
11750         if (DECL_P (object))
11751           mark_used (object);
11752         object_type = TREE_TYPE (object);
11753
11754         member = TREE_OPERAND (t, 1);
11755         if (BASELINK_P (member))
11756           member = tsubst_baselink (member,
11757                                     non_reference (TREE_TYPE (object)),
11758                                     args, complain, in_decl);
11759         else
11760           member = tsubst_copy (member, args, complain, in_decl);
11761         if (member == error_mark_node)
11762           return error_mark_node;
11763
11764         if (object_type && !CLASS_TYPE_P (object_type))
11765           {
11766             if (SCALAR_TYPE_P (object_type))
11767               {
11768                 tree s = NULL_TREE;
11769                 tree dtor = member;
11770
11771                 if (TREE_CODE (dtor) == SCOPE_REF)
11772                   {
11773                     s = TREE_OPERAND (dtor, 0);
11774                     dtor = TREE_OPERAND (dtor, 1);
11775                   }
11776                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11777                   {
11778                     dtor = TREE_OPERAND (dtor, 0);
11779                     if (TYPE_P (dtor))
11780                       return finish_pseudo_destructor_expr (object, s, dtor);
11781                   }
11782               }
11783           }
11784         else if (TREE_CODE (member) == SCOPE_REF
11785                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11786           {
11787             tree tmpl;
11788             tree args;
11789
11790             /* Lookup the template functions now that we know what the
11791                scope is.  */
11792             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11793             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11794             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11795                                             /*is_type_p=*/false,
11796                                             /*complain=*/false);
11797             if (BASELINK_P (member))
11798               {
11799                 BASELINK_FUNCTIONS (member)
11800                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11801                               args);
11802                 member = (adjust_result_of_qualified_name_lookup
11803                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11804                            object_type));
11805               }
11806             else
11807               {
11808                 qualified_name_lookup_error (object_type, tmpl, member,
11809                                              input_location);
11810                 return error_mark_node;
11811               }
11812           }
11813         else if (TREE_CODE (member) == SCOPE_REF
11814                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11815                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11816           {
11817             if (complain & tf_error)
11818               {
11819                 if (TYPE_P (TREE_OPERAND (member, 0)))
11820                   error ("%qT is not a class or namespace",
11821                          TREE_OPERAND (member, 0));
11822                 else
11823                   error ("%qD is not a class or namespace",
11824                          TREE_OPERAND (member, 0));
11825               }
11826             return error_mark_node;
11827           }
11828         else if (TREE_CODE (member) == FIELD_DECL)
11829           return finish_non_static_data_member (member, object, NULL_TREE);
11830
11831         return finish_class_member_access_expr (object, member,
11832                                                 /*template_p=*/false,
11833                                                 complain);
11834       }
11835
11836     case THROW_EXPR:
11837       return build_throw
11838         (RECUR (TREE_OPERAND (t, 0)));
11839
11840     case CONSTRUCTOR:
11841       {
11842         VEC(constructor_elt,gc) *n;
11843         constructor_elt *ce;
11844         unsigned HOST_WIDE_INT idx;
11845         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11846         bool process_index_p;
11847         int newlen;
11848         bool need_copy_p = false;
11849         tree r;
11850
11851         if (type == error_mark_node)
11852           return error_mark_node;
11853
11854         /* digest_init will do the wrong thing if we let it.  */
11855         if (type && TYPE_PTRMEMFUNC_P (type))
11856           return t;
11857
11858         /* We do not want to process the index of aggregate
11859            initializers as they are identifier nodes which will be
11860            looked up by digest_init.  */
11861         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
11862
11863         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11864         newlen = VEC_length (constructor_elt, n);
11865         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11866           {
11867             if (ce->index && process_index_p)
11868               ce->index = RECUR (ce->index);
11869
11870             if (PACK_EXPANSION_P (ce->value))
11871               {
11872                 /* Substitute into the pack expansion.  */
11873                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11874                                                   in_decl);
11875
11876                 if (ce->value == error_mark_node)
11877                   ;
11878                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11879                   /* Just move the argument into place.  */
11880                   ce->value = TREE_VEC_ELT (ce->value, 0);
11881                 else
11882                   {
11883                     /* Update the length of the final CONSTRUCTOR
11884                        arguments vector, and note that we will need to
11885                        copy.*/
11886                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11887                     need_copy_p = true;
11888                   }
11889               }
11890             else
11891               ce->value = RECUR (ce->value);
11892           }
11893
11894         if (need_copy_p)
11895           {
11896             VEC(constructor_elt,gc) *old_n = n;
11897
11898             n = VEC_alloc (constructor_elt, gc, newlen);
11899             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11900                  idx++)
11901               {
11902                 if (TREE_CODE (ce->value) == TREE_VEC)
11903                   {
11904                     int i, len = TREE_VEC_LENGTH (ce->value);
11905                     for (i = 0; i < len; ++i)
11906                       CONSTRUCTOR_APPEND_ELT (n, 0,
11907                                               TREE_VEC_ELT (ce->value, i));
11908                   }
11909                 else
11910                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11911               }
11912           }
11913
11914         r = build_constructor (init_list_type_node, n);
11915         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
11916
11917         if (TREE_HAS_CONSTRUCTOR (t))
11918           return finish_compound_literal (type, r);
11919
11920         return r;
11921       }
11922
11923     case TYPEID_EXPR:
11924       {
11925         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11926         if (TYPE_P (operand_0))
11927           return get_typeid (operand_0);
11928         return build_typeid (operand_0);
11929       }
11930
11931     case VAR_DECL:
11932       if (!args)
11933         return t;
11934       /* Fall through */
11935
11936     case PARM_DECL:
11937       {
11938         tree r = tsubst_copy (t, args, complain, in_decl);
11939
11940         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11941           /* If the original type was a reference, we'll be wrapped in
11942              the appropriate INDIRECT_REF.  */
11943           r = convert_from_reference (r);
11944         return r;
11945       }
11946
11947     case VA_ARG_EXPR:
11948       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11949                              tsubst_copy (TREE_TYPE (t), args, complain,
11950                                           in_decl));
11951
11952     case OFFSETOF_EXPR:
11953       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11954
11955     case TRAIT_EXPR:
11956       {
11957         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11958                                   complain, in_decl);
11959
11960         tree type2 = TRAIT_EXPR_TYPE2 (t);
11961         if (type2)
11962           type2 = tsubst_copy (type2, args, complain, in_decl);
11963         
11964         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11965       }
11966
11967     case STMT_EXPR:
11968       {
11969         tree old_stmt_expr = cur_stmt_expr;
11970         tree stmt_expr = begin_stmt_expr ();
11971
11972         cur_stmt_expr = stmt_expr;
11973         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11974                      integral_constant_expression_p);
11975         stmt_expr = finish_stmt_expr (stmt_expr, false);
11976         cur_stmt_expr = old_stmt_expr;
11977
11978         return stmt_expr;
11979       }
11980
11981     case CONST_DECL:
11982       t = tsubst_copy (t, args, complain, in_decl);
11983       /* As in finish_id_expression, we resolve enumeration constants
11984          to their underlying values.  */
11985       if (TREE_CODE (t) == CONST_DECL)
11986         {
11987           used_types_insert (TREE_TYPE (t));
11988           return DECL_INITIAL (t);
11989         }
11990       return t;
11991
11992     default:
11993       /* Handle Objective-C++ constructs, if appropriate.  */
11994       {
11995         tree subst
11996           = objcp_tsubst_copy_and_build (t, args, complain,
11997                                          in_decl, /*function_p=*/false);
11998         if (subst)
11999           return subst;
12000       }
12001       return tsubst_copy (t, args, complain, in_decl);
12002     }
12003
12004 #undef RECUR
12005 }
12006
12007 /* Verify that the instantiated ARGS are valid. For type arguments,
12008    make sure that the type's linkage is ok. For non-type arguments,
12009    make sure they are constants if they are integral or enumerations.
12010    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12011
12012 static bool
12013 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12014 {
12015   if (ARGUMENT_PACK_P (t))
12016     {
12017       tree vec = ARGUMENT_PACK_ARGS (t);
12018       int len = TREE_VEC_LENGTH (vec);
12019       bool result = false;
12020       int i;
12021
12022       for (i = 0; i < len; ++i)
12023         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12024           result = true;
12025       return result;
12026     }
12027   else if (TYPE_P (t))
12028     {
12029       /* [basic.link]: A name with no linkage (notably, the name
12030          of a class or enumeration declared in a local scope)
12031          shall not be used to declare an entity with linkage.
12032          This implies that names with no linkage cannot be used as
12033          template arguments.  */
12034       tree nt = no_linkage_check (t, /*relaxed_p=*/false);
12035
12036       if (nt)
12037         {
12038           /* DR 488 makes use of a type with no linkage cause
12039              type deduction to fail.  */
12040           if (complain & tf_error)
12041             {
12042               if (TYPE_ANONYMOUS_P (nt))
12043                 error ("%qT is/uses anonymous type", t);
12044               else
12045                 error ("template argument for %qD uses local type %qT",
12046                        tmpl, t);
12047             }
12048           return true;
12049         }
12050       /* In order to avoid all sorts of complications, we do not
12051          allow variably-modified types as template arguments.  */
12052       else if (variably_modified_type_p (t, NULL_TREE))
12053         {
12054           if (complain & tf_error)
12055             error ("%qT is a variably modified type", t);
12056           return true;
12057         }
12058     }
12059   /* A non-type argument of integral or enumerated type must be a
12060      constant.  */
12061   else if (TREE_TYPE (t)
12062            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12063            && !TREE_CONSTANT (t))
12064     {
12065       if (complain & tf_error)
12066         error ("integral expression %qE is not constant", t);
12067       return true;
12068     }
12069   return false;
12070 }
12071
12072 static bool
12073 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12074 {
12075   int ix, len = DECL_NTPARMS (tmpl);
12076   bool result = false;
12077
12078   for (ix = 0; ix != len; ix++)
12079     {
12080       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12081         result = true;
12082     }
12083   if (result && (complain & tf_error))
12084     error ("  trying to instantiate %qD", tmpl);
12085   return result;
12086 }
12087
12088 /* Instantiate the indicated variable or function template TMPL with
12089    the template arguments in TARG_PTR.  */
12090
12091 tree
12092 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
12093 {
12094   tree fndecl;
12095   tree gen_tmpl;
12096   tree spec;
12097   HOST_WIDE_INT saved_processing_template_decl;
12098
12099   if (tmpl == error_mark_node)
12100     return error_mark_node;
12101
12102   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12103
12104   /* If this function is a clone, handle it specially.  */
12105   if (DECL_CLONED_FUNCTION_P (tmpl))
12106     {
12107       tree spec;
12108       tree clone;
12109
12110       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
12111                                    complain);
12112       if (spec == error_mark_node)
12113         return error_mark_node;
12114
12115       /* Look for the clone.  */
12116       FOR_EACH_CLONE (clone, spec)
12117         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12118           return clone;
12119       /* We should always have found the clone by now.  */
12120       gcc_unreachable ();
12121       return NULL_TREE;
12122     }
12123
12124   /* Check to see if we already have this specialization.  */
12125   spec = retrieve_specialization (tmpl, targ_ptr,
12126                                   /*class_specializations_p=*/false);
12127   if (spec != NULL_TREE)
12128     return spec;
12129
12130   gen_tmpl = most_general_template (tmpl);
12131   if (tmpl != gen_tmpl)
12132     {
12133       /* The TMPL is a partial instantiation.  To get a full set of
12134          arguments we must add the arguments used to perform the
12135          partial instantiation.  */
12136       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12137                                               targ_ptr);
12138
12139       /* Check to see if we already have this specialization.  */
12140       spec = retrieve_specialization (gen_tmpl, targ_ptr,
12141                                       /*class_specializations_p=*/false);
12142       if (spec != NULL_TREE)
12143         return spec;
12144     }
12145
12146   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12147                                complain))
12148     return error_mark_node;
12149
12150   /* We are building a FUNCTION_DECL, during which the access of its
12151      parameters and return types have to be checked.  However this
12152      FUNCTION_DECL which is the desired context for access checking
12153      is not built yet.  We solve this chicken-and-egg problem by
12154      deferring all checks until we have the FUNCTION_DECL.  */
12155   push_deferring_access_checks (dk_deferred);
12156
12157   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12158      (because, for example, we have encountered a non-dependent
12159      function call in the body of a template function and must now
12160      determine which of several overloaded functions will be called),
12161      within the instantiation itself we are not processing a
12162      template.  */  
12163   saved_processing_template_decl = processing_template_decl;
12164   processing_template_decl = 0;
12165   /* Substitute template parameters to obtain the specialization.  */
12166   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12167                    targ_ptr, complain, gen_tmpl);
12168   processing_template_decl = saved_processing_template_decl;
12169   if (fndecl == error_mark_node)
12170     return error_mark_node;
12171
12172   /* Now we know the specialization, compute access previously
12173      deferred.  */
12174   push_access_scope (fndecl);
12175   perform_deferred_access_checks ();
12176   pop_access_scope (fndecl);
12177   pop_deferring_access_checks ();
12178
12179   /* The DECL_TI_TEMPLATE should always be the immediate parent
12180      template, not the most general template.  */
12181   DECL_TI_TEMPLATE (fndecl) = tmpl;
12182
12183   /* If we've just instantiated the main entry point for a function,
12184      instantiate all the alternate entry points as well.  We do this
12185      by cloning the instantiation of the main entry point, not by
12186      instantiating the template clones.  */
12187   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12188     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12189
12190   return fndecl;
12191 }
12192
12193 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
12194    arguments that are being used when calling it.  TARGS is a vector
12195    into which the deduced template arguments are placed.
12196
12197    Return zero for success, 2 for an incomplete match that doesn't resolve
12198    all the types, and 1 for complete failure.  An error message will be
12199    printed only for an incomplete match.
12200
12201    If FN is a conversion operator, or we are trying to produce a specific
12202    specialization, RETURN_TYPE is the return type desired.
12203
12204    The EXPLICIT_TARGS are explicit template arguments provided via a
12205    template-id.
12206
12207    The parameter STRICT is one of:
12208
12209    DEDUCE_CALL:
12210      We are deducing arguments for a function call, as in
12211      [temp.deduct.call].
12212
12213    DEDUCE_CONV:
12214      We are deducing arguments for a conversion function, as in
12215      [temp.deduct.conv].
12216
12217    DEDUCE_EXACT:
12218      We are deducing arguments when doing an explicit instantiation
12219      as in [temp.explicit], when determining an explicit specialization
12220      as in [temp.expl.spec], or when taking the address of a function
12221      template, as in [temp.deduct.funcaddr].  */
12222
12223 int
12224 fn_type_unification (tree fn,
12225                      tree explicit_targs,
12226                      tree targs,
12227                      tree args,
12228                      tree return_type,
12229                      unification_kind_t strict,
12230                      int flags)
12231 {
12232   tree parms;
12233   tree fntype;
12234   int result;
12235   bool incomplete_argument_packs_p = false;
12236
12237   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12238
12239   fntype = TREE_TYPE (fn);
12240   if (explicit_targs)
12241     {
12242       /* [temp.deduct]
12243
12244          The specified template arguments must match the template
12245          parameters in kind (i.e., type, nontype, template), and there
12246          must not be more arguments than there are parameters;
12247          otherwise type deduction fails.
12248
12249          Nontype arguments must match the types of the corresponding
12250          nontype template parameters, or must be convertible to the
12251          types of the corresponding nontype parameters as specified in
12252          _temp.arg.nontype_, otherwise type deduction fails.
12253
12254          All references in the function type of the function template
12255          to the corresponding template parameters are replaced by the
12256          specified template argument values.  If a substitution in a
12257          template parameter or in the function type of the function
12258          template results in an invalid type, type deduction fails.  */
12259       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12260       int i, len = TREE_VEC_LENGTH (tparms);
12261       tree converted_args;
12262       bool incomplete = false;
12263
12264       if (explicit_targs == error_mark_node)
12265         return 1;
12266
12267       converted_args
12268         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12269                                   /*require_all_args=*/false,
12270                                   /*use_default_args=*/false));
12271       if (converted_args == error_mark_node)
12272         return 1;
12273
12274       /* Substitute the explicit args into the function type.  This is
12275          necessary so that, for instance, explicitly declared function
12276          arguments can match null pointed constants.  If we were given
12277          an incomplete set of explicit args, we must not do semantic
12278          processing during substitution as we could create partial
12279          instantiations.  */
12280       for (i = 0; i < len; i++)
12281         {
12282           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12283           bool parameter_pack = false;
12284
12285           /* Dig out the actual parm.  */
12286           if (TREE_CODE (parm) == TYPE_DECL
12287               || TREE_CODE (parm) == TEMPLATE_DECL)
12288             {
12289               parm = TREE_TYPE (parm);
12290               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12291             }
12292           else if (TREE_CODE (parm) == PARM_DECL)
12293             {
12294               parm = DECL_INITIAL (parm);
12295               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12296             }
12297
12298           if (parameter_pack)
12299             {
12300               int level, idx;
12301               tree targ;
12302               template_parm_level_and_index (parm, &level, &idx);
12303
12304               /* Mark the argument pack as "incomplete". We could
12305                  still deduce more arguments during unification.  */
12306               targ = TMPL_ARG (converted_args, level, idx);
12307               if (targ)
12308                 {
12309                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12310                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12311                     = ARGUMENT_PACK_ARGS (targ);
12312                 }
12313
12314               /* We have some incomplete argument packs.  */
12315               incomplete_argument_packs_p = true;
12316             }
12317         }
12318
12319       if (incomplete_argument_packs_p)
12320         /* Any substitution is guaranteed to be incomplete if there
12321            are incomplete argument packs, because we can still deduce
12322            more arguments.  */
12323         incomplete = 1;
12324       else
12325         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12326
12327       processing_template_decl += incomplete;
12328       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12329       processing_template_decl -= incomplete;
12330
12331       if (fntype == error_mark_node)
12332         return 1;
12333
12334       /* Place the explicitly specified arguments in TARGS.  */
12335       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12336         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12337     }
12338
12339   /* Never do unification on the 'this' parameter.  */
12340   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12341
12342   if (return_type)
12343     {
12344       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12345       args = tree_cons (NULL_TREE, return_type, args);
12346     }
12347
12348   /* We allow incomplete unification without an error message here
12349      because the standard doesn't seem to explicitly prohibit it.  Our
12350      callers must be ready to deal with unification failures in any
12351      event.  */
12352   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12353                                   targs, parms, args, /*subr=*/0,
12354                                   strict, flags);
12355
12356   if (result == 0 && incomplete_argument_packs_p)
12357     {
12358       int i, len = NUM_TMPL_ARGS (targs);
12359
12360       /* Clear the "incomplete" flags on all argument packs.  */
12361       for (i = 0; i < len; i++)
12362         {
12363           tree arg = TREE_VEC_ELT (targs, i);
12364           if (ARGUMENT_PACK_P (arg))
12365             {
12366               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12367               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12368             }
12369         }
12370     }
12371
12372   /* Now that we have bindings for all of the template arguments,
12373      ensure that the arguments deduced for the template template
12374      parameters have compatible template parameter lists.  We cannot
12375      check this property before we have deduced all template
12376      arguments, because the template parameter types of a template
12377      template parameter might depend on prior template parameters
12378      deduced after the template template parameter.  The following
12379      ill-formed example illustrates this issue:
12380
12381        template<typename T, template<T> class C> void f(C<5>, T);
12382
12383        template<int N> struct X {};
12384
12385        void g() {
12386          f(X<5>(), 5l); // error: template argument deduction fails
12387        }
12388
12389      The template parameter list of 'C' depends on the template type
12390      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12391      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12392      time that we deduce 'C'.  */
12393   if (result == 0
12394       && !template_template_parm_bindings_ok_p 
12395            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12396     return 1;
12397
12398   if (result == 0)
12399     /* All is well so far.  Now, check:
12400
12401        [temp.deduct]
12402
12403        When all template arguments have been deduced, all uses of
12404        template parameters in nondeduced contexts are replaced with
12405        the corresponding deduced argument values.  If the
12406        substitution results in an invalid type, as described above,
12407        type deduction fails.  */
12408     {
12409       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
12410       if (substed == error_mark_node)
12411         return 1;
12412
12413       /* If we're looking for an exact match, check that what we got
12414          is indeed an exact match.  It might not be if some template
12415          parameters are used in non-deduced contexts.  */
12416       if (strict == DEDUCE_EXACT)
12417         {
12418           tree sarg
12419             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
12420           tree arg = args;
12421           if (return_type)
12422             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
12423           for (; arg && sarg;
12424                arg = TREE_CHAIN (arg), sarg = TREE_CHAIN (sarg))
12425             if (!same_type_p (TREE_VALUE (arg), TREE_VALUE (sarg)))
12426               return 1;
12427         }
12428     }
12429
12430   return result;
12431 }
12432
12433 /* Adjust types before performing type deduction, as described in
12434    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12435    sections are symmetric.  PARM is the type of a function parameter
12436    or the return type of the conversion function.  ARG is the type of
12437    the argument passed to the call, or the type of the value
12438    initialized with the result of the conversion function.
12439    ARG_EXPR is the original argument expression, which may be null.  */
12440
12441 static int
12442 maybe_adjust_types_for_deduction (unification_kind_t strict,
12443                                   tree* parm,
12444                                   tree* arg,
12445                                   tree arg_expr)
12446 {
12447   int result = 0;
12448
12449   switch (strict)
12450     {
12451     case DEDUCE_CALL:
12452       break;
12453
12454     case DEDUCE_CONV:
12455       {
12456         /* Swap PARM and ARG throughout the remainder of this
12457            function; the handling is precisely symmetric since PARM
12458            will initialize ARG rather than vice versa.  */
12459         tree* temp = parm;
12460         parm = arg;
12461         arg = temp;
12462         break;
12463       }
12464
12465     case DEDUCE_EXACT:
12466       /* There is nothing to do in this case.  */
12467       return 0;
12468
12469     default:
12470       gcc_unreachable ();
12471     }
12472
12473   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12474     {
12475       /* [temp.deduct.call]
12476
12477          If P is not a reference type:
12478
12479          --If A is an array type, the pointer type produced by the
12480          array-to-pointer standard conversion (_conv.array_) is
12481          used in place of A for type deduction; otherwise,
12482
12483          --If A is a function type, the pointer type produced by
12484          the function-to-pointer standard conversion
12485          (_conv.func_) is used in place of A for type deduction;
12486          otherwise,
12487
12488          --If A is a cv-qualified type, the top level
12489          cv-qualifiers of A's type are ignored for type
12490          deduction.  */
12491       if (TREE_CODE (*arg) == ARRAY_TYPE)
12492         *arg = build_pointer_type (TREE_TYPE (*arg));
12493       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12494         *arg = build_pointer_type (*arg);
12495       else
12496         *arg = TYPE_MAIN_VARIANT (*arg);
12497     }
12498
12499   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12500      of the form T&&, where T is a template parameter, and the argument
12501      is an lvalue, T is deduced as A& */
12502   if (TREE_CODE (*parm) == REFERENCE_TYPE
12503       && TYPE_REF_IS_RVALUE (*parm)
12504       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12505       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12506       && arg_expr && real_lvalue_p (arg_expr))
12507     *arg = build_reference_type (*arg);
12508
12509   /* [temp.deduct.call]
12510
12511      If P is a cv-qualified type, the top level cv-qualifiers
12512      of P's type are ignored for type deduction.  If P is a
12513      reference type, the type referred to by P is used for
12514      type deduction.  */
12515   *parm = TYPE_MAIN_VARIANT (*parm);
12516   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12517     {
12518       *parm = TREE_TYPE (*parm);
12519       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12520     }
12521
12522   /* DR 322. For conversion deduction, remove a reference type on parm
12523      too (which has been swapped into ARG).  */
12524   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12525     *arg = TREE_TYPE (*arg);
12526
12527   return result;
12528 }
12529
12530 /* Most parms like fn_type_unification.
12531
12532    If SUBR is 1, we're being called recursively (to unify the
12533    arguments of a function or method parameter of a function
12534    template). */
12535
12536 static int
12537 type_unification_real (tree tparms,
12538                        tree targs,
12539                        tree xparms,
12540                        tree xargs,
12541                        int subr,
12542                        unification_kind_t strict,
12543                        int flags)
12544 {
12545   tree parm, arg, arg_expr;
12546   int i;
12547   int ntparms = TREE_VEC_LENGTH (tparms);
12548   int sub_strict;
12549   int saw_undeduced = 0;
12550   tree parms, args;
12551
12552   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
12553   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
12554   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
12555   gcc_assert (ntparms > 0);
12556
12557   switch (strict)
12558     {
12559     case DEDUCE_CALL:
12560       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12561                     | UNIFY_ALLOW_DERIVED);
12562       break;
12563
12564     case DEDUCE_CONV:
12565       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12566       break;
12567
12568     case DEDUCE_EXACT:
12569       sub_strict = UNIFY_ALLOW_NONE;
12570       break;
12571
12572     default:
12573       gcc_unreachable ();
12574     }
12575
12576  again:
12577   parms = xparms;
12578   args = xargs;
12579
12580   while (parms && parms != void_list_node
12581          && args && args != void_list_node)
12582     {
12583       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12584         break;
12585
12586       parm = TREE_VALUE (parms);
12587       parms = TREE_CHAIN (parms);
12588       arg = TREE_VALUE (args);
12589       args = TREE_CHAIN (args);
12590       arg_expr = NULL;
12591
12592       if (arg == error_mark_node)
12593         return 1;
12594       if (arg == unknown_type_node)
12595         /* We can't deduce anything from this, but we might get all the
12596            template args from other function args.  */
12597         continue;
12598
12599       /* Conversions will be performed on a function argument that
12600          corresponds with a function parameter that contains only
12601          non-deducible template parameters and explicitly specified
12602          template parameters.  */
12603       if (!uses_template_parms (parm))
12604         {
12605           tree type;
12606
12607           if (!TYPE_P (arg))
12608             type = TREE_TYPE (arg);
12609           else
12610             type = arg;
12611
12612           if (same_type_p (parm, type))
12613             continue;
12614           if (strict != DEDUCE_EXACT
12615               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12616                                   flags))
12617             continue;
12618
12619           return 1;
12620         }
12621
12622       if (!TYPE_P (arg))
12623         {
12624           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12625           if (type_unknown_p (arg))
12626             {
12627               /* [temp.deduct.type] 
12628
12629                  A template-argument can be deduced from a pointer to
12630                  function or pointer to member function argument if
12631                  the set of overloaded functions does not contain
12632                  function templates and at most one of a set of
12633                  overloaded functions provides a unique match.  */
12634               if (resolve_overloaded_unification
12635                   (tparms, targs, parm, arg, strict, sub_strict))
12636                 continue;
12637
12638               return 1;
12639             }
12640           arg_expr = arg;
12641           arg = unlowered_expr_type (arg);
12642           if (arg == error_mark_node)
12643             return 1;
12644         }
12645
12646       {
12647         int arg_strict = sub_strict;
12648
12649         if (!subr)
12650           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12651                                                           arg_expr);
12652
12653         if (arg == init_list_type_node && arg_expr)
12654           arg = arg_expr;
12655         if (unify (tparms, targs, parm, arg, arg_strict))
12656           return 1;
12657       }
12658     }
12659
12660
12661   if (parms 
12662       && parms != void_list_node
12663       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12664     {
12665       /* Unify the remaining arguments with the pack expansion type.  */
12666       tree argvec;
12667       tree parmvec = make_tree_vec (1);
12668       int len = 0;
12669       tree t;
12670
12671       /* Count the number of arguments that remain.  */
12672       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
12673         len++;
12674         
12675       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12676       argvec = make_tree_vec (len);
12677       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
12678         {
12679           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
12680           ++i;
12681         }
12682
12683       /* Copy the parameter into parmvec.  */
12684       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12685       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12686                                 /*call_args_p=*/true, /*subr=*/subr))
12687         return 1;
12688
12689       /* Advance to the end of the list of parameters.  */
12690       parms = TREE_CHAIN (parms);
12691     }
12692
12693   /* Fail if we've reached the end of the parm list, and more args
12694      are present, and the parm list isn't variadic.  */
12695   if (args && args != void_list_node && parms == void_list_node)
12696     return 1;
12697   /* Fail if parms are left and they don't have default values.  */
12698   if (parms && parms != void_list_node
12699       && TREE_PURPOSE (parms) == NULL_TREE)
12700     return 1;
12701
12702   if (!subr)
12703     for (i = 0; i < ntparms; i++)
12704       if (!TREE_VEC_ELT (targs, i))
12705         {
12706           tree tparm;
12707
12708           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12709             continue;
12710
12711           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12712
12713           /* If this is an undeduced nontype parameter that depends on
12714              a type parameter, try another pass; its type may have been
12715              deduced from a later argument than the one from which
12716              this parameter can be deduced.  */
12717           if (TREE_CODE (tparm) == PARM_DECL
12718               && uses_template_parms (TREE_TYPE (tparm))
12719               && !saw_undeduced++)
12720             goto again;
12721
12722           /* Core issue #226 (C++0x) [temp.deduct]:
12723
12724                If a template argument has not been deduced, its
12725                default template argument, if any, is used. 
12726
12727              When we are in C++98 mode, TREE_PURPOSE will either
12728              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12729              to explicitly check cxx_dialect here.  */
12730           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12731             {
12732               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12733               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
12734               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
12735               arg = convert_template_argument (parm, arg, targs, tf_none,
12736                                                i, NULL_TREE);
12737               if (arg == error_mark_node)
12738                 return 1;
12739               else
12740                 {
12741                   TREE_VEC_ELT (targs, i) = arg;
12742                   continue;
12743                 }
12744             }
12745
12746           /* If the type parameter is a parameter pack, then it will
12747              be deduced to an empty parameter pack.  */
12748           if (template_parameter_pack_p (tparm))
12749             {
12750               tree arg;
12751
12752               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12753                 {
12754                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12755                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12756                   TREE_CONSTANT (arg) = 1;
12757                 }
12758               else
12759                 arg = make_node (TYPE_ARGUMENT_PACK);
12760
12761               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12762
12763               TREE_VEC_ELT (targs, i) = arg;
12764               continue;
12765             }
12766
12767           return 2;
12768         }
12769
12770   return 0;
12771 }
12772
12773 /* Subroutine of type_unification_real.  Args are like the variables
12774    at the call site.  ARG is an overloaded function (or template-id);
12775    we try deducing template args from each of the overloads, and if
12776    only one succeeds, we go with that.  Modifies TARGS and returns
12777    true on success.  */
12778
12779 static bool
12780 resolve_overloaded_unification (tree tparms,
12781                                 tree targs,
12782                                 tree parm,
12783                                 tree arg,
12784                                 unification_kind_t strict,
12785                                 int sub_strict)
12786 {
12787   tree tempargs = copy_node (targs);
12788   int good = 0;
12789   tree goodfn = NULL_TREE;
12790   bool addr_p;
12791
12792   if (TREE_CODE (arg) == ADDR_EXPR)
12793     {
12794       arg = TREE_OPERAND (arg, 0);
12795       addr_p = true;
12796     }
12797   else
12798     addr_p = false;
12799
12800   if (TREE_CODE (arg) == COMPONENT_REF)
12801     /* Handle `&x' where `x' is some static or non-static member
12802        function name.  */
12803     arg = TREE_OPERAND (arg, 1);
12804
12805   if (TREE_CODE (arg) == OFFSET_REF)
12806     arg = TREE_OPERAND (arg, 1);
12807
12808   /* Strip baselink information.  */
12809   if (BASELINK_P (arg))
12810     arg = BASELINK_FUNCTIONS (arg);
12811
12812   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12813     {
12814       /* If we got some explicit template args, we need to plug them into
12815          the affected templates before we try to unify, in case the
12816          explicit args will completely resolve the templates in question.  */
12817
12818       tree expl_subargs = TREE_OPERAND (arg, 1);
12819       arg = TREE_OPERAND (arg, 0);
12820
12821       for (; arg; arg = OVL_NEXT (arg))
12822         {
12823           tree fn = OVL_CURRENT (arg);
12824           tree subargs, elem;
12825
12826           if (TREE_CODE (fn) != TEMPLATE_DECL)
12827             continue;
12828
12829           ++processing_template_decl;
12830           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12831                                   expl_subargs, /*check_ret=*/false);
12832           if (subargs)
12833             {
12834               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12835               if (try_one_overload (tparms, targs, tempargs, parm,
12836                                     elem, strict, sub_strict, addr_p)
12837                   && (!goodfn || !decls_match (goodfn, elem)))
12838                 {
12839                   goodfn = elem;
12840                   ++good;
12841                 }
12842             }
12843           --processing_template_decl;
12844         }
12845     }
12846   else if (TREE_CODE (arg) != OVERLOAD
12847            && TREE_CODE (arg) != FUNCTION_DECL)
12848     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12849        -- but the deduction does not succeed because the expression is
12850        not just the function on its own.  */
12851     return false;
12852   else
12853     for (; arg; arg = OVL_NEXT (arg))
12854       if (try_one_overload (tparms, targs, tempargs, parm,
12855                             TREE_TYPE (OVL_CURRENT (arg)),
12856                             strict, sub_strict, addr_p)
12857           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
12858         {
12859           goodfn = OVL_CURRENT (arg);
12860           ++good;
12861         }
12862
12863   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12864      to function or pointer to member function argument if the set of
12865      overloaded functions does not contain function templates and at most
12866      one of a set of overloaded functions provides a unique match.
12867
12868      So if we found multiple possibilities, we return success but don't
12869      deduce anything.  */
12870
12871   if (good == 1)
12872     {
12873       int i = TREE_VEC_LENGTH (targs);
12874       for (; i--; )
12875         if (TREE_VEC_ELT (tempargs, i))
12876           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12877     }
12878   if (good)
12879     return true;
12880
12881   return false;
12882 }
12883
12884 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12885    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12886    different overloads deduce different arguments for a given parm.
12887    ADDR_P is true if the expression for which deduction is being
12888    performed was of the form "& fn" rather than simply "fn".
12889
12890    Returns 1 on success.  */
12891
12892 static int
12893 try_one_overload (tree tparms,
12894                   tree orig_targs,
12895                   tree targs,
12896                   tree parm,
12897                   tree arg,
12898                   unification_kind_t strict,
12899                   int sub_strict,
12900                   bool addr_p)
12901 {
12902   int nargs;
12903   tree tempargs;
12904   int i;
12905
12906   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12907      to function or pointer to member function argument if the set of
12908      overloaded functions does not contain function templates and at most
12909      one of a set of overloaded functions provides a unique match.
12910
12911      So if this is a template, just return success.  */
12912
12913   if (uses_template_parms (arg))
12914     return 1;
12915
12916   if (TREE_CODE (arg) == METHOD_TYPE)
12917     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12918   else if (addr_p)
12919     arg = build_pointer_type (arg);
12920
12921   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12922
12923   /* We don't copy orig_targs for this because if we have already deduced
12924      some template args from previous args, unify would complain when we
12925      try to deduce a template parameter for the same argument, even though
12926      there isn't really a conflict.  */
12927   nargs = TREE_VEC_LENGTH (targs);
12928   tempargs = make_tree_vec (nargs);
12929
12930   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12931     return 0;
12932
12933   /* First make sure we didn't deduce anything that conflicts with
12934      explicitly specified args.  */
12935   for (i = nargs; i--; )
12936     {
12937       tree elt = TREE_VEC_ELT (tempargs, i);
12938       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12939
12940       if (!elt)
12941         /*NOP*/;
12942       else if (uses_template_parms (elt))
12943         /* Since we're unifying against ourselves, we will fill in
12944            template args used in the function parm list with our own
12945            template parms.  Discard them.  */
12946         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12947       else if (oldelt && !template_args_equal (oldelt, elt))
12948         return 0;
12949     }
12950
12951   for (i = nargs; i--; )
12952     {
12953       tree elt = TREE_VEC_ELT (tempargs, i);
12954
12955       if (elt)
12956         TREE_VEC_ELT (targs, i) = elt;
12957     }
12958
12959   return 1;
12960 }
12961
12962 /* PARM is a template class (perhaps with unbound template
12963    parameters).  ARG is a fully instantiated type.  If ARG can be
12964    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12965    TARGS are as for unify.  */
12966
12967 static tree
12968 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12969 {
12970   tree copy_of_targs;
12971
12972   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12973       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12974           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12975     return NULL_TREE;
12976
12977   /* We need to make a new template argument vector for the call to
12978      unify.  If we used TARGS, we'd clutter it up with the result of
12979      the attempted unification, even if this class didn't work out.
12980      We also don't want to commit ourselves to all the unifications
12981      we've already done, since unification is supposed to be done on
12982      an argument-by-argument basis.  In other words, consider the
12983      following pathological case:
12984
12985        template <int I, int J, int K>
12986        struct S {};
12987
12988        template <int I, int J>
12989        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12990
12991        template <int I, int J, int K>
12992        void f(S<I, J, K>, S<I, I, I>);
12993
12994        void g() {
12995          S<0, 0, 0> s0;
12996          S<0, 1, 2> s2;
12997
12998          f(s0, s2);
12999        }
13000
13001      Now, by the time we consider the unification involving `s2', we
13002      already know that we must have `f<0, 0, 0>'.  But, even though
13003      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13004      because there are two ways to unify base classes of S<0, 1, 2>
13005      with S<I, I, I>.  If we kept the already deduced knowledge, we
13006      would reject the possibility I=1.  */
13007   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13008
13009   /* If unification failed, we're done.  */
13010   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13011              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13012     return NULL_TREE;
13013
13014   return arg;
13015 }
13016
13017 /* Given a template type PARM and a class type ARG, find the unique
13018    base type in ARG that is an instance of PARM.  We do not examine
13019    ARG itself; only its base-classes.  If there is not exactly one
13020    appropriate base class, return NULL_TREE.  PARM may be the type of
13021    a partial specialization, as well as a plain template type.  Used
13022    by unify.  */
13023
13024 static tree
13025 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13026 {
13027   tree rval = NULL_TREE;
13028   tree binfo;
13029
13030   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13031
13032   binfo = TYPE_BINFO (complete_type (arg));
13033   if (!binfo)
13034     /* The type could not be completed.  */
13035     return NULL_TREE;
13036
13037   /* Walk in inheritance graph order.  The search order is not
13038      important, and this avoids multiple walks of virtual bases.  */
13039   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13040     {
13041       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13042
13043       if (r)
13044         {
13045           /* If there is more than one satisfactory baseclass, then:
13046
13047                [temp.deduct.call]
13048
13049               If they yield more than one possible deduced A, the type
13050               deduction fails.
13051
13052              applies.  */
13053           if (rval && !same_type_p (r, rval))
13054             return NULL_TREE;
13055
13056           rval = r;
13057         }
13058     }
13059
13060   return rval;
13061 }
13062
13063 /* Returns the level of DECL, which declares a template parameter.  */
13064
13065 static int
13066 template_decl_level (tree decl)
13067 {
13068   switch (TREE_CODE (decl))
13069     {
13070     case TYPE_DECL:
13071     case TEMPLATE_DECL:
13072       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13073
13074     case PARM_DECL:
13075       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13076
13077     default:
13078       gcc_unreachable ();
13079     }
13080   return 0;
13081 }
13082
13083 /* Decide whether ARG can be unified with PARM, considering only the
13084    cv-qualifiers of each type, given STRICT as documented for unify.
13085    Returns nonzero iff the unification is OK on that basis.  */
13086
13087 static int
13088 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13089 {
13090   int arg_quals = cp_type_quals (arg);
13091   int parm_quals = cp_type_quals (parm);
13092
13093   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13094       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13095     {
13096       /*  Although a CVR qualifier is ignored when being applied to a
13097           substituted template parameter ([8.3.2]/1 for example), that
13098           does not apply during deduction [14.8.2.4]/1, (even though
13099           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13100           this).  Except when we're allowing additional CV qualifiers
13101           at the outer level [14.8.2.1]/3,1st bullet.  */
13102       if ((TREE_CODE (arg) == REFERENCE_TYPE
13103            || TREE_CODE (arg) == FUNCTION_TYPE
13104            || TREE_CODE (arg) == METHOD_TYPE)
13105           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13106         return 0;
13107
13108       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13109           && (parm_quals & TYPE_QUAL_RESTRICT))
13110         return 0;
13111     }
13112
13113   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13114       && (arg_quals & parm_quals) != parm_quals)
13115     return 0;
13116
13117   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13118       && (parm_quals & arg_quals) != arg_quals)
13119     return 0;
13120
13121   return 1;
13122 }
13123
13124 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13125 void 
13126 template_parm_level_and_index (tree parm, int* level, int* index)
13127 {
13128   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13129       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13130       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13131     {
13132       *index = TEMPLATE_TYPE_IDX (parm);
13133       *level = TEMPLATE_TYPE_LEVEL (parm);
13134     }
13135   else
13136     {
13137       *index = TEMPLATE_PARM_IDX (parm);
13138       *level = TEMPLATE_PARM_LEVEL (parm);
13139     }
13140 }
13141
13142 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13143    expansion at the end of PACKED_PARMS. Returns 0 if the type
13144    deduction succeeds, 1 otherwise. STRICT is the same as in
13145    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13146    call argument list. We'll need to adjust the arguments to make them
13147    types. SUBR tells us if this is from a recursive call to
13148    type_unification_real.  */
13149 int
13150 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13151                       tree packed_args, int strict, bool call_args_p,
13152                       bool subr)
13153 {
13154   tree parm 
13155     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13156   tree pattern = PACK_EXPANSION_PATTERN (parm);
13157   tree pack, packs = NULL_TREE;
13158   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13159   int len = TREE_VEC_LENGTH (packed_args);
13160
13161   /* Determine the parameter packs we will be deducing from the
13162      pattern, and record their current deductions.  */
13163   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13164        pack; pack = TREE_CHAIN (pack))
13165     {
13166       tree parm_pack = TREE_VALUE (pack);
13167       int idx, level;
13168
13169       /* Determine the index and level of this parameter pack.  */
13170       template_parm_level_and_index (parm_pack, &level, &idx);
13171
13172       /* Keep track of the parameter packs and their corresponding
13173          argument packs.  */
13174       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13175       TREE_TYPE (packs) = make_tree_vec (len - start);
13176     }
13177   
13178   /* Loop through all of the arguments that have not yet been
13179      unified and unify each with the pattern.  */
13180   for (i = start; i < len; i++)
13181     {
13182       tree parm = pattern;
13183
13184       /* For each parameter pack, clear out the deduced value so that
13185          we can deduce it again.  */
13186       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13187         {
13188           int idx, level;
13189           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13190
13191           TMPL_ARG (targs, level, idx) = NULL_TREE;
13192         }
13193
13194       /* Unify the pattern with the current argument.  */
13195       {
13196         tree arg = TREE_VEC_ELT (packed_args, i);
13197         tree arg_expr = NULL_TREE;
13198         int arg_strict = strict;
13199         bool skip_arg_p = false;
13200
13201         if (call_args_p)
13202           {
13203             int sub_strict;
13204
13205             /* This mirrors what we do in type_unification_real.  */
13206             switch (strict)
13207               {
13208               case DEDUCE_CALL:
13209                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13210                               | UNIFY_ALLOW_MORE_CV_QUAL
13211                               | UNIFY_ALLOW_DERIVED);
13212                 break;
13213                 
13214               case DEDUCE_CONV:
13215                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13216                 break;
13217                 
13218               case DEDUCE_EXACT:
13219                 sub_strict = UNIFY_ALLOW_NONE;
13220                 break;
13221                 
13222               default:
13223                 gcc_unreachable ();
13224               }
13225
13226             if (!TYPE_P (arg))
13227               {
13228                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13229                 if (type_unknown_p (arg))
13230                   {
13231                     /* [temp.deduct.type] A template-argument can be
13232                        deduced from a pointer to function or pointer
13233                        to member function argument if the set of
13234                        overloaded functions does not contain function
13235                        templates and at most one of a set of
13236                        overloaded functions provides a unique
13237                        match.  */
13238
13239                     if (resolve_overloaded_unification
13240                         (tparms, targs, parm, arg, strict, sub_strict)
13241                         != 0)
13242                       return 1;
13243                     skip_arg_p = true;
13244                   }
13245
13246                 if (!skip_arg_p)
13247                   {
13248                     arg_expr = arg;
13249                     arg = unlowered_expr_type (arg);
13250                     if (arg == error_mark_node)
13251                       return 1;
13252                   }
13253               }
13254       
13255             arg_strict = sub_strict;
13256
13257             if (!subr)
13258               arg_strict |= 
13259                 maybe_adjust_types_for_deduction (strict, &parm, &arg, 
13260                                                   arg_expr);
13261           }
13262
13263         if (!skip_arg_p)
13264           {
13265             if (unify (tparms, targs, parm, arg, arg_strict))
13266               return 1;
13267           }
13268       }
13269
13270       /* For each parameter pack, collect the deduced value.  */
13271       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13272         {
13273           int idx, level;
13274           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13275
13276           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13277             TMPL_ARG (targs, level, idx);
13278         }
13279     }
13280
13281   /* Verify that the results of unification with the parameter packs
13282      produce results consistent with what we've seen before, and make
13283      the deduced argument packs available.  */
13284   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13285     {
13286       tree old_pack = TREE_VALUE (pack);
13287       tree new_args = TREE_TYPE (pack);
13288       int i, len = TREE_VEC_LENGTH (new_args);
13289       bool nondeduced_p = false;
13290
13291       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13292          actually deduce anything.  */
13293       for (i = 0; i < len && !nondeduced_p; ++i)
13294         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13295           nondeduced_p = true;
13296       if (nondeduced_p)
13297         continue;
13298
13299       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13300         {
13301           /* Prepend the explicit arguments onto NEW_ARGS.  */
13302           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13303           tree old_args = new_args;
13304           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13305           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13306
13307           /* Copy the explicit arguments.  */
13308           new_args = make_tree_vec (len);
13309           for (i = 0; i < explicit_len; i++)
13310             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13311
13312           /* Copy the deduced arguments.  */
13313           for (; i < len; i++)
13314             TREE_VEC_ELT (new_args, i) =
13315               TREE_VEC_ELT (old_args, i - explicit_len);
13316         }
13317
13318       if (!old_pack)
13319         {
13320           tree result;
13321           int idx, level;
13322           
13323           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13324
13325           /* Build the deduced *_ARGUMENT_PACK.  */
13326           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13327             {
13328               result = make_node (NONTYPE_ARGUMENT_PACK);
13329               TREE_TYPE (result) = 
13330                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13331               TREE_CONSTANT (result) = 1;
13332             }
13333           else
13334             result = make_node (TYPE_ARGUMENT_PACK);
13335
13336           SET_ARGUMENT_PACK_ARGS (result, new_args);
13337
13338           /* Note the deduced argument packs for this parameter
13339              pack.  */
13340           TMPL_ARG (targs, level, idx) = result;
13341         }
13342       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13343                && (ARGUMENT_PACK_ARGS (old_pack) 
13344                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13345         {
13346           /* We only had the explicitly-provided arguments before, but
13347              now we have a complete set of arguments.  */
13348           int idx, level;
13349           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13350           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13351
13352           /* Keep the original deduced argument pack.  */
13353           TMPL_ARG (targs, level, idx) = old_pack;
13354
13355           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13356           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13357           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13358         }
13359       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13360                                     new_args))
13361         /* Inconsistent unification of this parameter pack.  */
13362         return 1;
13363       else
13364         {
13365           int idx, level;
13366           
13367           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13368
13369           /* Keep the original deduced argument pack.  */
13370           TMPL_ARG (targs, level, idx) = old_pack;
13371         }
13372     }
13373
13374   return 0;
13375 }
13376
13377 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13378    set of template parameters to a template.  TARGS is the bindings
13379    for those template parameters, as determined thus far; TARGS may
13380    include template arguments for outer levels of template parameters
13381    as well.  PARM is a parameter to a template function, or a
13382    subcomponent of that parameter; ARG is the corresponding argument.
13383    This function attempts to match PARM with ARG in a manner
13384    consistent with the existing assignments in TARGS.  If more values
13385    are deduced, then TARGS is updated.
13386
13387    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13388    parameter STRICT is a bitwise or of the following flags:
13389
13390      UNIFY_ALLOW_NONE:
13391        Require an exact match between PARM and ARG.
13392      UNIFY_ALLOW_MORE_CV_QUAL:
13393        Allow the deduced ARG to be more cv-qualified (by qualification
13394        conversion) than ARG.
13395      UNIFY_ALLOW_LESS_CV_QUAL:
13396        Allow the deduced ARG to be less cv-qualified than ARG.
13397      UNIFY_ALLOW_DERIVED:
13398        Allow the deduced ARG to be a template base class of ARG,
13399        or a pointer to a template base class of the type pointed to by
13400        ARG.
13401      UNIFY_ALLOW_INTEGER:
13402        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13403        case for more information.
13404      UNIFY_ALLOW_OUTER_LEVEL:
13405        This is the outermost level of a deduction. Used to determine validity
13406        of qualification conversions. A valid qualification conversion must
13407        have const qualified pointers leading up to the inner type which
13408        requires additional CV quals, except at the outer level, where const
13409        is not required [conv.qual]. It would be normal to set this flag in
13410        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13411      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13412        This is the outermost level of a deduction, and PARM can be more CV
13413        qualified at this point.
13414      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13415        This is the outermost level of a deduction, and PARM can be less CV
13416        qualified at this point.  */
13417
13418 static int
13419 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13420 {
13421   int idx;
13422   tree targ;
13423   tree tparm;
13424   int strict_in = strict;
13425
13426   /* I don't think this will do the right thing with respect to types.
13427      But the only case I've seen it in so far has been array bounds, where
13428      signedness is the only information lost, and I think that will be
13429      okay.  */
13430   while (TREE_CODE (parm) == NOP_EXPR)
13431     parm = TREE_OPERAND (parm, 0);
13432
13433   if (arg == error_mark_node)
13434     return 1;
13435   if (arg == unknown_type_node
13436       || arg == init_list_type_node)
13437     /* We can't deduce anything from this, but we might get all the
13438        template args from other function args.  */
13439     return 0;
13440
13441   /* If PARM uses template parameters, then we can't bail out here,
13442      even if ARG == PARM, since we won't record unifications for the
13443      template parameters.  We might need them if we're trying to
13444      figure out which of two things is more specialized.  */
13445   if (arg == parm && !uses_template_parms (parm))
13446     return 0;
13447
13448   /* Handle init lists early, so the rest of the function can assume
13449      we're dealing with a type. */
13450   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
13451     {
13452       tree elt, elttype;
13453       unsigned i;
13454       tree orig_parm = parm;
13455
13456       /* Replace T with std::initializer_list<T> for deduction.  */
13457       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13458           && flag_deduce_init_list)
13459         parm = listify (parm);
13460
13461       if (!is_std_init_list (parm))
13462         /* We can only deduce from an initializer list argument if the
13463            parameter is std::initializer_list; otherwise this is a
13464            non-deduced context. */
13465         return 0;
13466
13467       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
13468
13469       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
13470         {
13471           int elt_strict = strict;
13472           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
13473             {
13474               tree type = TREE_TYPE (elt);
13475               /* It should only be possible to get here for a call.  */
13476               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
13477               elt_strict |= maybe_adjust_types_for_deduction
13478                 (DEDUCE_CALL, &elttype, &type, elt);
13479               elt = type;
13480             }
13481
13482           if (unify (tparms, targs, elttype, elt, elt_strict))
13483             return 1;
13484         }
13485
13486       /* If the std::initializer_list<T> deduction worked, replace the
13487          deduced A with std::initializer_list<A>.  */
13488       if (orig_parm != parm)
13489         {
13490           idx = TEMPLATE_TYPE_IDX (orig_parm);
13491           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13492           targ = listify (targ);
13493           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
13494         }
13495       return 0;
13496     }
13497
13498   /* Immediately reject some pairs that won't unify because of
13499      cv-qualification mismatches.  */
13500   if (TREE_CODE (arg) == TREE_CODE (parm)
13501       && TYPE_P (arg)
13502       /* It is the elements of the array which hold the cv quals of an array
13503          type, and the elements might be template type parms. We'll check
13504          when we recurse.  */
13505       && TREE_CODE (arg) != ARRAY_TYPE
13506       /* We check the cv-qualifiers when unifying with template type
13507          parameters below.  We want to allow ARG `const T' to unify with
13508          PARM `T' for example, when computing which of two templates
13509          is more specialized, for example.  */
13510       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
13511       && !check_cv_quals_for_unify (strict_in, arg, parm))
13512     return 1;
13513
13514   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
13515       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
13516     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
13517   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
13518   strict &= ~UNIFY_ALLOW_DERIVED;
13519   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13520   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
13521
13522   switch (TREE_CODE (parm))
13523     {
13524     case TYPENAME_TYPE:
13525     case SCOPE_REF:
13526     case UNBOUND_CLASS_TEMPLATE:
13527       /* In a type which contains a nested-name-specifier, template
13528          argument values cannot be deduced for template parameters used
13529          within the nested-name-specifier.  */
13530       return 0;
13531
13532     case TEMPLATE_TYPE_PARM:
13533     case TEMPLATE_TEMPLATE_PARM:
13534     case BOUND_TEMPLATE_TEMPLATE_PARM:
13535       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13536       if (tparm == error_mark_node)
13537         return 1;
13538
13539       if (TEMPLATE_TYPE_LEVEL (parm)
13540           != template_decl_level (tparm))
13541         /* The PARM is not one we're trying to unify.  Just check
13542            to see if it matches ARG.  */
13543         return (TREE_CODE (arg) == TREE_CODE (parm)
13544                 && same_type_p (parm, arg)) ? 0 : 1;
13545       idx = TEMPLATE_TYPE_IDX (parm);
13546       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13547       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
13548
13549       /* Check for mixed types and values.  */
13550       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13551            && TREE_CODE (tparm) != TYPE_DECL)
13552           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13553               && TREE_CODE (tparm) != TEMPLATE_DECL))
13554         return 1;
13555
13556       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13557         {
13558           /* ARG must be constructed from a template class or a template
13559              template parameter.  */
13560           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
13561               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
13562             return 1;
13563
13564           {
13565             tree parmvec = TYPE_TI_ARGS (parm);
13566             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
13567             tree parm_parms 
13568               = DECL_INNERMOST_TEMPLATE_PARMS
13569                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
13570             int i, len;
13571             int parm_variadic_p = 0;
13572
13573             /* The resolution to DR150 makes clear that default
13574                arguments for an N-argument may not be used to bind T
13575                to a template template parameter with fewer than N
13576                parameters.  It is not safe to permit the binding of
13577                default arguments as an extension, as that may change
13578                the meaning of a conforming program.  Consider:
13579
13580                   struct Dense { static const unsigned int dim = 1; };
13581
13582                   template <template <typename> class View,
13583                             typename Block>
13584                   void operator+(float, View<Block> const&);
13585
13586                   template <typename Block,
13587                             unsigned int Dim = Block::dim>
13588                   struct Lvalue_proxy { operator float() const; };
13589
13590                   void
13591                   test_1d (void) {
13592                     Lvalue_proxy<Dense> p;
13593                     float b;
13594                     b + p;
13595                   }
13596
13597               Here, if Lvalue_proxy is permitted to bind to View, then
13598               the global operator+ will be used; if they are not, the
13599               Lvalue_proxy will be converted to float.  */
13600             if (coerce_template_parms (parm_parms,
13601                                        argvec,
13602                                        TYPE_TI_TEMPLATE (parm),
13603                                        tf_none,
13604                                        /*require_all_args=*/true,
13605                                        /*use_default_args=*/false)
13606                 == error_mark_node)
13607               return 1;
13608
13609             /* Deduce arguments T, i from TT<T> or TT<i>.
13610                We check each element of PARMVEC and ARGVEC individually
13611                rather than the whole TREE_VEC since they can have
13612                different number of elements.  */
13613
13614             parmvec = expand_template_argument_pack (parmvec);
13615             argvec = expand_template_argument_pack (argvec);
13616
13617             len = TREE_VEC_LENGTH (parmvec);
13618
13619             /* Check if the parameters end in a pack, making them
13620                variadic.  */
13621             if (len > 0
13622                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
13623               parm_variadic_p = 1;
13624             
13625             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
13626               return 1;
13627
13628              for (i = 0; i < len - parm_variadic_p; ++i)
13629               {
13630                 if (unify (tparms, targs,
13631                            TREE_VEC_ELT (parmvec, i),
13632                            TREE_VEC_ELT (argvec, i),
13633                            UNIFY_ALLOW_NONE))
13634                   return 1;
13635               }
13636
13637             if (parm_variadic_p
13638                 && unify_pack_expansion (tparms, targs,
13639                                          parmvec, argvec,
13640                                          UNIFY_ALLOW_NONE,
13641                                          /*call_args_p=*/false,
13642                                          /*subr=*/false))
13643               return 1;
13644           }
13645           arg = TYPE_TI_TEMPLATE (arg);
13646
13647           /* Fall through to deduce template name.  */
13648         }
13649
13650       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13651           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13652         {
13653           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13654
13655           /* Simple cases: Value already set, does match or doesn't.  */
13656           if (targ != NULL_TREE && template_args_equal (targ, arg))
13657             return 0;
13658           else if (targ)
13659             return 1;
13660         }
13661       else
13662         {
13663           /* If PARM is `const T' and ARG is only `int', we don't have
13664              a match unless we are allowing additional qualification.
13665              If ARG is `const int' and PARM is just `T' that's OK;
13666              that binds `const int' to `T'.  */
13667           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13668                                          arg, parm))
13669             return 1;
13670
13671           /* Consider the case where ARG is `const volatile int' and
13672              PARM is `const T'.  Then, T should be `volatile int'.  */
13673           arg = cp_build_qualified_type_real
13674             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13675           if (arg == error_mark_node)
13676             return 1;
13677
13678           /* Simple cases: Value already set, does match or doesn't.  */
13679           if (targ != NULL_TREE && same_type_p (targ, arg))
13680             return 0;
13681           else if (targ)
13682             return 1;
13683
13684           /* Make sure that ARG is not a variable-sized array.  (Note
13685              that were talking about variable-sized arrays (like
13686              `int[n]'), rather than arrays of unknown size (like
13687              `int[]').)  We'll get very confused by such a type since
13688              the bound of the array will not be computable in an
13689              instantiation.  Besides, such types are not allowed in
13690              ISO C++, so we can do as we please here.  */
13691           if (variably_modified_type_p (arg, NULL_TREE))
13692             return 1;
13693         }
13694
13695       /* If ARG is a parameter pack or an expansion, we cannot unify
13696          against it unless PARM is also a parameter pack.  */
13697       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13698           && !template_parameter_pack_p (parm))
13699         return 1;
13700
13701       /* If the argument deduction results is a METHOD_TYPE,
13702          then there is a problem.
13703          METHOD_TYPE doesn't map to any real C++ type the result of
13704          the deduction can not be of that type.  */
13705       if (TREE_CODE (arg) == METHOD_TYPE)
13706         return 1;
13707
13708       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13709       return 0;
13710
13711     case TEMPLATE_PARM_INDEX:
13712       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13713       if (tparm == error_mark_node)
13714         return 1;
13715
13716       if (TEMPLATE_PARM_LEVEL (parm)
13717           != template_decl_level (tparm))
13718         /* The PARM is not one we're trying to unify.  Just check
13719            to see if it matches ARG.  */
13720         return !(TREE_CODE (arg) == TREE_CODE (parm)
13721                  && cp_tree_equal (parm, arg));
13722
13723       idx = TEMPLATE_PARM_IDX (parm);
13724       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13725
13726       if (targ)
13727         return !cp_tree_equal (targ, arg);
13728
13729       /* [temp.deduct.type] If, in the declaration of a function template
13730          with a non-type template-parameter, the non-type
13731          template-parameter is used in an expression in the function
13732          parameter-list and, if the corresponding template-argument is
13733          deduced, the template-argument type shall match the type of the
13734          template-parameter exactly, except that a template-argument
13735          deduced from an array bound may be of any integral type.
13736          The non-type parameter might use already deduced type parameters.  */
13737       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13738       if (!TREE_TYPE (arg))
13739         /* Template-parameter dependent expression.  Just accept it for now.
13740            It will later be processed in convert_template_argument.  */
13741         ;
13742       else if (same_type_p (TREE_TYPE (arg), tparm))
13743         /* OK */;
13744       else if ((strict & UNIFY_ALLOW_INTEGER)
13745                && (TREE_CODE (tparm) == INTEGER_TYPE
13746                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13747         /* Convert the ARG to the type of PARM; the deduced non-type
13748            template argument must exactly match the types of the
13749            corresponding parameter.  */
13750         arg = fold (build_nop (tparm, arg));
13751       else if (uses_template_parms (tparm))
13752         /* We haven't deduced the type of this parameter yet.  Try again
13753            later.  */
13754         return 0;
13755       else
13756         return 1;
13757
13758       /* If ARG is a parameter pack or an expansion, we cannot unify
13759          against it unless PARM is also a parameter pack.  */
13760       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13761           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13762         return 1;
13763
13764       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13765       return 0;
13766
13767     case PTRMEM_CST:
13768      {
13769         /* A pointer-to-member constant can be unified only with
13770          another constant.  */
13771       if (TREE_CODE (arg) != PTRMEM_CST)
13772         return 1;
13773
13774       /* Just unify the class member. It would be useless (and possibly
13775          wrong, depending on the strict flags) to unify also
13776          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13777          arg refer to the same variable, even if through different
13778          classes. For instance:
13779
13780          struct A { int x; };
13781          struct B : A { };
13782
13783          Unification of &A::x and &B::x must succeed.  */
13784       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13785                     PTRMEM_CST_MEMBER (arg), strict);
13786      }
13787
13788     case POINTER_TYPE:
13789       {
13790         if (TREE_CODE (arg) != POINTER_TYPE)
13791           return 1;
13792
13793         /* [temp.deduct.call]
13794
13795            A can be another pointer or pointer to member type that can
13796            be converted to the deduced A via a qualification
13797            conversion (_conv.qual_).
13798
13799            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13800            This will allow for additional cv-qualification of the
13801            pointed-to types if appropriate.  */
13802
13803         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13804           /* The derived-to-base conversion only persists through one
13805              level of pointers.  */
13806           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13807
13808         return unify (tparms, targs, TREE_TYPE (parm),
13809                       TREE_TYPE (arg), strict);
13810       }
13811
13812     case REFERENCE_TYPE:
13813       if (TREE_CODE (arg) != REFERENCE_TYPE)
13814         return 1;
13815       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13816                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13817
13818     case ARRAY_TYPE:
13819       if (TREE_CODE (arg) != ARRAY_TYPE)
13820         return 1;
13821       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13822           != (TYPE_DOMAIN (arg) == NULL_TREE))
13823         return 1;
13824       if (TYPE_DOMAIN (parm) != NULL_TREE)
13825         {
13826           tree parm_max;
13827           tree arg_max;
13828           bool parm_cst;
13829           bool arg_cst;
13830
13831           /* Our representation of array types uses "N - 1" as the
13832              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13833              not an integer constant.  We cannot unify arbitrarily
13834              complex expressions, so we eliminate the MINUS_EXPRs
13835              here.  */
13836           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13837           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13838           if (!parm_cst)
13839             {
13840               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13841               parm_max = TREE_OPERAND (parm_max, 0);
13842             }
13843           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13844           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13845           if (!arg_cst)
13846             {
13847               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13848                  trying to unify the type of a variable with the type
13849                  of a template parameter.  For example:
13850
13851                    template <unsigned int N>
13852                    void f (char (&) [N]);
13853                    int g(); 
13854                    void h(int i) {
13855                      char a[g(i)];
13856                      f(a); 
13857                    }
13858
13859                 Here, the type of the ARG will be "int [g(i)]", and
13860                 may be a SAVE_EXPR, etc.  */
13861               if (TREE_CODE (arg_max) != MINUS_EXPR)
13862                 return 1;
13863               arg_max = TREE_OPERAND (arg_max, 0);
13864             }
13865
13866           /* If only one of the bounds used a MINUS_EXPR, compensate
13867              by adding one to the other bound.  */
13868           if (parm_cst && !arg_cst)
13869             parm_max = fold_build2 (PLUS_EXPR,
13870                                     integer_type_node,
13871                                     parm_max,
13872                                     integer_one_node);
13873           else if (arg_cst && !parm_cst)
13874             arg_max = fold_build2 (PLUS_EXPR,
13875                                    integer_type_node,
13876                                    arg_max,
13877                                    integer_one_node);
13878
13879           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13880             return 1;
13881         }
13882       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13883                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13884
13885     case REAL_TYPE:
13886     case COMPLEX_TYPE:
13887     case VECTOR_TYPE:
13888     case INTEGER_TYPE:
13889     case BOOLEAN_TYPE:
13890     case ENUMERAL_TYPE:
13891     case VOID_TYPE:
13892       if (TREE_CODE (arg) != TREE_CODE (parm))
13893         return 1;
13894
13895       /* We have already checked cv-qualification at the top of the
13896          function.  */
13897       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13898         return 1;
13899
13900       /* As far as unification is concerned, this wins.  Later checks
13901          will invalidate it if necessary.  */
13902       return 0;
13903
13904       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13905       /* Type INTEGER_CST can come from ordinary constant template args.  */
13906     case INTEGER_CST:
13907       while (TREE_CODE (arg) == NOP_EXPR)
13908         arg = TREE_OPERAND (arg, 0);
13909
13910       if (TREE_CODE (arg) != INTEGER_CST)
13911         return 1;
13912       return !tree_int_cst_equal (parm, arg);
13913
13914     case TREE_VEC:
13915       {
13916         int i;
13917         if (TREE_CODE (arg) != TREE_VEC)
13918           return 1;
13919         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13920           return 1;
13921         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13922           if (unify (tparms, targs,
13923                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13924                      UNIFY_ALLOW_NONE))
13925             return 1;
13926         return 0;
13927       }
13928
13929     case RECORD_TYPE:
13930     case UNION_TYPE:
13931       if (TREE_CODE (arg) != TREE_CODE (parm))
13932         return 1;
13933
13934       if (TYPE_PTRMEMFUNC_P (parm))
13935         {
13936           if (!TYPE_PTRMEMFUNC_P (arg))
13937             return 1;
13938
13939           return unify (tparms, targs,
13940                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13941                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13942                         strict);
13943         }
13944
13945       if (CLASSTYPE_TEMPLATE_INFO (parm))
13946         {
13947           tree t = NULL_TREE;
13948
13949           if (strict_in & UNIFY_ALLOW_DERIVED)
13950             {
13951               /* First, we try to unify the PARM and ARG directly.  */
13952               t = try_class_unification (tparms, targs,
13953                                          parm, arg);
13954
13955               if (!t)
13956                 {
13957                   /* Fallback to the special case allowed in
13958                      [temp.deduct.call]:
13959
13960                        If P is a class, and P has the form
13961                        template-id, then A can be a derived class of
13962                        the deduced A.  Likewise, if P is a pointer to
13963                        a class of the form template-id, A can be a
13964                        pointer to a derived class pointed to by the
13965                        deduced A.  */
13966                   t = get_template_base (tparms, targs, parm, arg);
13967
13968                   if (!t)
13969                     return 1;
13970                 }
13971             }
13972           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13973                    && (CLASSTYPE_TI_TEMPLATE (parm)
13974                        == CLASSTYPE_TI_TEMPLATE (arg)))
13975             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13976                Then, we should unify `int' and `U'.  */
13977             t = arg;
13978           else
13979             /* There's no chance of unification succeeding.  */
13980             return 1;
13981
13982           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13983                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13984         }
13985       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13986         return 1;
13987       return 0;
13988
13989     case METHOD_TYPE:
13990     case FUNCTION_TYPE:
13991       if (TREE_CODE (arg) != TREE_CODE (parm))
13992         return 1;
13993
13994       /* CV qualifications for methods can never be deduced, they must
13995          match exactly.  We need to check them explicitly here,
13996          because type_unification_real treats them as any other
13997          cv-qualified parameter.  */
13998       if (TREE_CODE (parm) == METHOD_TYPE
13999           && (!check_cv_quals_for_unify
14000               (UNIFY_ALLOW_NONE,
14001                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14002                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14003         return 1;
14004
14005       if (unify (tparms, targs, TREE_TYPE (parm),
14006                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14007         return 1;
14008       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14009                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
14010                                     LOOKUP_NORMAL);
14011
14012     case OFFSET_TYPE:
14013       /* Unify a pointer to member with a pointer to member function, which
14014          deduces the type of the member as a function type. */
14015       if (TYPE_PTRMEMFUNC_P (arg))
14016         {
14017           tree method_type;
14018           tree fntype;
14019           cp_cv_quals cv_quals;
14020
14021           /* Check top-level cv qualifiers */
14022           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14023             return 1;
14024
14025           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14026                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14027             return 1;
14028
14029           /* Determine the type of the function we are unifying against. */
14030           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14031           fntype =
14032             build_function_type (TREE_TYPE (method_type),
14033                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14034
14035           /* Extract the cv-qualifiers of the member function from the
14036              implicit object parameter and place them on the function
14037              type to be restored later. */
14038           cv_quals =
14039             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14040           fntype = build_qualified_type (fntype, cv_quals);
14041           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14042         }
14043
14044       if (TREE_CODE (arg) != OFFSET_TYPE)
14045         return 1;
14046       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14047                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14048         return 1;
14049       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14050                     strict);
14051
14052     case CONST_DECL:
14053       if (DECL_TEMPLATE_PARM_P (parm))
14054         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14055       if (arg != integral_constant_value (parm))
14056         return 1;
14057       return 0;
14058
14059     case FIELD_DECL:
14060     case TEMPLATE_DECL:
14061       /* Matched cases are handled by the ARG == PARM test above.  */
14062       return 1;
14063
14064     case TYPE_ARGUMENT_PACK:
14065     case NONTYPE_ARGUMENT_PACK:
14066       {
14067         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14068         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14069         int i, len = TREE_VEC_LENGTH (packed_parms);
14070         int argslen = TREE_VEC_LENGTH (packed_args);
14071         int parm_variadic_p = 0;
14072
14073         for (i = 0; i < len; ++i)
14074           {
14075             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14076               {
14077                 if (i == len - 1)
14078                   /* We can unify against something with a trailing
14079                      parameter pack.  */
14080                   parm_variadic_p = 1;
14081                 else
14082                   /* Since there is something following the pack
14083                      expansion, we cannot unify this template argument
14084                      list.  */
14085                   return 0;
14086               }
14087           }
14088           
14089
14090         /* If we don't have enough arguments to satisfy the parameters
14091            (not counting the pack expression at the end), or we have
14092            too many arguments for a parameter list that doesn't end in
14093            a pack expression, we can't unify.  */
14094         if (argslen < (len - parm_variadic_p)
14095             || (argslen > len && !parm_variadic_p))
14096           return 1;
14097
14098         /* Unify all of the parameters that precede the (optional)
14099            pack expression.  */
14100         for (i = 0; i < len - parm_variadic_p; ++i)
14101           {
14102             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14103                        TREE_VEC_ELT (packed_args, i), strict))
14104               return 1;
14105           }
14106
14107         if (parm_variadic_p)
14108           return unify_pack_expansion (tparms, targs, 
14109                                        packed_parms, packed_args,
14110                                        strict, /*call_args_p=*/false,
14111                                        /*subr=*/false);
14112         return 0;
14113       }
14114
14115       break;
14116
14117     case TYPEOF_TYPE:
14118     case DECLTYPE_TYPE:
14119       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14120          nodes.  */
14121       return 0;
14122
14123     case ERROR_MARK:
14124       /* Unification fails if we hit an error node.  */
14125       return 1;
14126
14127     default:
14128       gcc_assert (EXPR_P (parm));
14129
14130       /* We must be looking at an expression.  This can happen with
14131          something like:
14132
14133            template <int I>
14134            void foo(S<I>, S<I + 2>);
14135
14136          This is a "nondeduced context":
14137
14138            [deduct.type]
14139
14140            The nondeduced contexts are:
14141
14142            --A type that is a template-id in which one or more of
14143              the template-arguments is an expression that references
14144              a template-parameter.
14145
14146          In these cases, we assume deduction succeeded, but don't
14147          actually infer any unifications.  */
14148
14149       if (!uses_template_parms (parm)
14150           && !template_args_equal (parm, arg))
14151         return 1;
14152       else
14153         return 0;
14154     }
14155 }
14156 \f
14157 /* Note that DECL can be defined in this translation unit, if
14158    required.  */
14159
14160 static void
14161 mark_definable (tree decl)
14162 {
14163   tree clone;
14164   DECL_NOT_REALLY_EXTERN (decl) = 1;
14165   FOR_EACH_CLONE (clone, decl)
14166     DECL_NOT_REALLY_EXTERN (clone) = 1;
14167 }
14168
14169 /* Called if RESULT is explicitly instantiated, or is a member of an
14170    explicitly instantiated class.  */
14171
14172 void
14173 mark_decl_instantiated (tree result, int extern_p)
14174 {
14175   SET_DECL_EXPLICIT_INSTANTIATION (result);
14176
14177   /* If this entity has already been written out, it's too late to
14178      make any modifications.  */
14179   if (TREE_ASM_WRITTEN (result))
14180     return;
14181
14182   if (TREE_CODE (result) != FUNCTION_DECL)
14183     /* The TREE_PUBLIC flag for function declarations will have been
14184        set correctly by tsubst.  */
14185     TREE_PUBLIC (result) = 1;
14186
14187   /* This might have been set by an earlier implicit instantiation.  */
14188   DECL_COMDAT (result) = 0;
14189
14190   if (extern_p)
14191     DECL_NOT_REALLY_EXTERN (result) = 0;
14192   else
14193     {
14194       mark_definable (result);
14195       /* Always make artificials weak.  */
14196       if (DECL_ARTIFICIAL (result) && flag_weak)
14197         comdat_linkage (result);
14198       /* For WIN32 we also want to put explicit instantiations in
14199          linkonce sections.  */
14200       else if (TREE_PUBLIC (result))
14201         maybe_make_one_only (result);
14202     }
14203
14204   /* If EXTERN_P, then this function will not be emitted -- unless
14205      followed by an explicit instantiation, at which point its linkage
14206      will be adjusted.  If !EXTERN_P, then this function will be
14207      emitted here.  In neither circumstance do we want
14208      import_export_decl to adjust the linkage.  */
14209   DECL_INTERFACE_KNOWN (result) = 1;
14210 }
14211
14212 /* Given two function templates PAT1 and PAT2, return:
14213
14214    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14215    -1 if PAT2 is more specialized than PAT1.
14216    0 if neither is more specialized.
14217
14218    LEN indicates the number of parameters we should consider
14219    (defaulted parameters should not be considered).
14220
14221    The 1998 std underspecified function template partial ordering, and
14222    DR214 addresses the issue.  We take pairs of arguments, one from
14223    each of the templates, and deduce them against each other.  One of
14224    the templates will be more specialized if all the *other*
14225    template's arguments deduce against its arguments and at least one
14226    of its arguments *does* *not* deduce against the other template's
14227    corresponding argument.  Deduction is done as for class templates.
14228    The arguments used in deduction have reference and top level cv
14229    qualifiers removed.  Iff both arguments were originally reference
14230    types *and* deduction succeeds in both directions, the template
14231    with the more cv-qualified argument wins for that pairing (if
14232    neither is more cv-qualified, they both are equal).  Unlike regular
14233    deduction, after all the arguments have been deduced in this way,
14234    we do *not* verify the deduced template argument values can be
14235    substituted into non-deduced contexts, nor do we have to verify
14236    that all template arguments have been deduced.  */
14237
14238 int
14239 more_specialized_fn (tree pat1, tree pat2, int len)
14240 {
14241   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
14242   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
14243   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
14244   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
14245   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
14246   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
14247   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
14248   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
14249   int better1 = 0;
14250   int better2 = 0;
14251
14252   /* Remove the this parameter from non-static member functions.  If
14253      one is a non-static member function and the other is not a static
14254      member function, remove the first parameter from that function
14255      also.  This situation occurs for operator functions where we
14256      locate both a member function (with this pointer) and non-member
14257      operator (with explicit first operand).  */
14258   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
14259     {
14260       len--; /* LEN is the number of significant arguments for DECL1 */
14261       args1 = TREE_CHAIN (args1);
14262       if (!DECL_STATIC_FUNCTION_P (decl2))
14263         args2 = TREE_CHAIN (args2);
14264     }
14265   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
14266     {
14267       args2 = TREE_CHAIN (args2);
14268       if (!DECL_STATIC_FUNCTION_P (decl1))
14269         {
14270           len--;
14271           args1 = TREE_CHAIN (args1);
14272         }
14273     }
14274
14275   /* If only one is a conversion operator, they are unordered.  */
14276   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
14277     return 0;
14278
14279   /* Consider the return type for a conversion function */
14280   if (DECL_CONV_FN_P (decl1))
14281     {
14282       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
14283       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
14284       len++;
14285     }
14286
14287   processing_template_decl++;
14288
14289   while (len--
14290          /* Stop when an ellipsis is seen.  */
14291          && args1 != NULL_TREE && args2 != NULL_TREE)
14292     {
14293       tree arg1 = TREE_VALUE (args1);
14294       tree arg2 = TREE_VALUE (args2);
14295       int deduce1, deduce2;
14296       int quals1 = -1;
14297       int quals2 = -1;
14298
14299       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14300           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14301         {
14302           /* When both arguments are pack expansions, we need only
14303              unify the patterns themselves.  */
14304           arg1 = PACK_EXPANSION_PATTERN (arg1);
14305           arg2 = PACK_EXPANSION_PATTERN (arg2);
14306
14307           /* This is the last comparison we need to do.  */
14308           len = 0;
14309         }
14310
14311       if (TREE_CODE (arg1) == REFERENCE_TYPE)
14312         {
14313           arg1 = TREE_TYPE (arg1);
14314           quals1 = cp_type_quals (arg1);
14315         }
14316
14317       if (TREE_CODE (arg2) == REFERENCE_TYPE)
14318         {
14319           arg2 = TREE_TYPE (arg2);
14320           quals2 = cp_type_quals (arg2);
14321         }
14322
14323       if ((quals1 < 0) != (quals2 < 0))
14324         {
14325           /* Only of the args is a reference, see if we should apply
14326              array/function pointer decay to it.  This is not part of
14327              DR214, but is, IMHO, consistent with the deduction rules
14328              for the function call itself, and with our earlier
14329              implementation of the underspecified partial ordering
14330              rules.  (nathan).  */
14331           if (quals1 >= 0)
14332             {
14333               switch (TREE_CODE (arg1))
14334                 {
14335                 case ARRAY_TYPE:
14336                   arg1 = TREE_TYPE (arg1);
14337                   /* FALLTHROUGH. */
14338                 case FUNCTION_TYPE:
14339                   arg1 = build_pointer_type (arg1);
14340                   break;
14341
14342                 default:
14343                   break;
14344                 }
14345             }
14346           else
14347             {
14348               switch (TREE_CODE (arg2))
14349                 {
14350                 case ARRAY_TYPE:
14351                   arg2 = TREE_TYPE (arg2);
14352                   /* FALLTHROUGH. */
14353                 case FUNCTION_TYPE:
14354                   arg2 = build_pointer_type (arg2);
14355                   break;
14356
14357                 default:
14358                   break;
14359                 }
14360             }
14361         }
14362
14363       arg1 = TYPE_MAIN_VARIANT (arg1);
14364       arg2 = TYPE_MAIN_VARIANT (arg2);
14365
14366       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
14367         {
14368           int i, len2 = list_length (args2);
14369           tree parmvec = make_tree_vec (1);
14370           tree argvec = make_tree_vec (len2);
14371           tree ta = args2;
14372
14373           /* Setup the parameter vector, which contains only ARG1.  */
14374           TREE_VEC_ELT (parmvec, 0) = arg1;
14375
14376           /* Setup the argument vector, which contains the remaining
14377              arguments.  */
14378           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
14379             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14380
14381           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
14382                                            argvec, UNIFY_ALLOW_NONE, 
14383                                            /*call_args_p=*/false, 
14384                                            /*subr=*/0);
14385
14386           /* We cannot deduce in the other direction, because ARG1 is
14387              a pack expansion but ARG2 is not.  */
14388           deduce2 = 0;
14389         }
14390       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14391         {
14392           int i, len1 = list_length (args1);
14393           tree parmvec = make_tree_vec (1);
14394           tree argvec = make_tree_vec (len1);
14395           tree ta = args1;
14396
14397           /* Setup the parameter vector, which contains only ARG1.  */
14398           TREE_VEC_ELT (parmvec, 0) = arg2;
14399
14400           /* Setup the argument vector, which contains the remaining
14401              arguments.  */
14402           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14403             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14404
14405           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14406                                            argvec, UNIFY_ALLOW_NONE, 
14407                                            /*call_args_p=*/false, 
14408                                            /*subr=*/0);
14409
14410           /* We cannot deduce in the other direction, because ARG2 is
14411              a pack expansion but ARG1 is not.*/
14412           deduce1 = 0;
14413         }
14414
14415       else
14416         {
14417           /* The normal case, where neither argument is a pack
14418              expansion.  */
14419           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
14420           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
14421         }
14422
14423       if (!deduce1)
14424         better2 = -1;
14425       if (!deduce2)
14426         better1 = -1;
14427       if (better1 < 0 && better2 < 0)
14428         /* We've failed to deduce something in either direction.
14429            These must be unordered.  */
14430         break;
14431
14432       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
14433         {
14434           /* Deduces in both directions, see if quals can
14435              disambiguate.  Pretend the worse one failed to deduce. */
14436           if ((quals1 & quals2) == quals2)
14437             deduce1 = 0;
14438           if ((quals1 & quals2) == quals1)
14439             deduce2 = 0;
14440         }
14441       if (deduce1 && !deduce2 && !better2)
14442         better2 = 1;
14443       if (deduce2 && !deduce1 && !better1)
14444         better1 = 1;
14445
14446       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14447           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14448         /* We have already processed all of the arguments in our
14449            handing of the pack expansion type.  */
14450         len = 0;
14451
14452       args1 = TREE_CHAIN (args1);
14453       args2 = TREE_CHAIN (args2);
14454     }
14455
14456   processing_template_decl--;
14457
14458   /* All things being equal, if the next argument is a pack expansion
14459      for one function but not for the other, prefer the
14460      non-variadic function.  */
14461   if ((better1 > 0) - (better2 > 0) == 0
14462       && args1 && TREE_VALUE (args1)
14463       && args2 && TREE_VALUE (args2))
14464     {
14465       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
14466         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
14467       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
14468         return 1;
14469     }
14470
14471   return (better1 > 0) - (better2 > 0);
14472 }
14473
14474 /* Determine which of two partial specializations is more specialized.
14475
14476    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
14477    to the first partial specialization.  The TREE_VALUE is the
14478    innermost set of template parameters for the partial
14479    specialization.  PAT2 is similar, but for the second template.
14480
14481    Return 1 if the first partial specialization is more specialized;
14482    -1 if the second is more specialized; 0 if neither is more
14483    specialized.
14484
14485    See [temp.class.order] for information about determining which of
14486    two templates is more specialized.  */
14487
14488 static int
14489 more_specialized_class (tree pat1, tree pat2)
14490 {
14491   tree targs;
14492   tree tmpl1, tmpl2;
14493   int winner = 0;
14494   bool any_deductions = false;
14495
14496   tmpl1 = TREE_TYPE (pat1);
14497   tmpl2 = TREE_TYPE (pat2);
14498
14499   /* Just like what happens for functions, if we are ordering between
14500      different class template specializations, we may encounter dependent
14501      types in the arguments, and we need our dependency check functions
14502      to behave correctly.  */
14503   ++processing_template_decl;
14504   targs = get_class_bindings (TREE_VALUE (pat1),
14505                               CLASSTYPE_TI_ARGS (tmpl1),
14506                               CLASSTYPE_TI_ARGS (tmpl2));
14507   if (targs)
14508     {
14509       --winner;
14510       any_deductions = true;
14511     }
14512
14513   targs = get_class_bindings (TREE_VALUE (pat2),
14514                               CLASSTYPE_TI_ARGS (tmpl2),
14515                               CLASSTYPE_TI_ARGS (tmpl1));
14516   if (targs)
14517     {
14518       ++winner;
14519       any_deductions = true;
14520     }
14521   --processing_template_decl;
14522
14523   /* In the case of a tie where at least one of the class templates
14524      has a parameter pack at the end, the template with the most
14525      non-packed parameters wins.  */
14526   if (winner == 0
14527       && any_deductions
14528       && (template_args_variadic_p (TREE_PURPOSE (pat1))
14529           || template_args_variadic_p (TREE_PURPOSE (pat2))))
14530     {
14531       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
14532       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
14533       int len1 = TREE_VEC_LENGTH (args1);
14534       int len2 = TREE_VEC_LENGTH (args2);
14535
14536       /* We don't count the pack expansion at the end.  */
14537       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
14538         --len1;
14539       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
14540         --len2;
14541
14542       if (len1 > len2)
14543         return 1;
14544       else if (len1 < len2)
14545         return -1;
14546     }
14547
14548   return winner;
14549 }
14550
14551 /* Return the template arguments that will produce the function signature
14552    DECL from the function template FN, with the explicit template
14553    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
14554    also match.  Return NULL_TREE if no satisfactory arguments could be
14555    found.  */
14556
14557 static tree
14558 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
14559 {
14560   int ntparms = DECL_NTPARMS (fn);
14561   tree targs = make_tree_vec (ntparms);
14562   tree decl_type;
14563   tree decl_arg_types;
14564
14565   /* Substitute the explicit template arguments into the type of DECL.
14566      The call to fn_type_unification will handle substitution into the
14567      FN.  */
14568   decl_type = TREE_TYPE (decl);
14569   if (explicit_args && uses_template_parms (decl_type))
14570     {
14571       tree tmpl;
14572       tree converted_args;
14573
14574       if (DECL_TEMPLATE_INFO (decl))
14575         tmpl = DECL_TI_TEMPLATE (decl);
14576       else
14577         /* We can get here for some invalid specializations.  */
14578         return NULL_TREE;
14579
14580       converted_args
14581         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
14582                                  explicit_args, NULL_TREE,
14583                                  tf_none,
14584                                  /*require_all_args=*/false,
14585                                  /*use_default_args=*/false);
14586       if (converted_args == error_mark_node)
14587         return NULL_TREE;
14588
14589       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
14590       if (decl_type == error_mark_node)
14591         return NULL_TREE;
14592     }
14593
14594   /* Never do unification on the 'this' parameter.  */
14595   decl_arg_types = skip_artificial_parms_for (decl, 
14596                                               TYPE_ARG_TYPES (decl_type));
14597
14598   if (fn_type_unification (fn, explicit_args, targs,
14599                            decl_arg_types,
14600                            (check_rettype || DECL_CONV_FN_P (fn)
14601                             ? TREE_TYPE (decl_type) : NULL_TREE),
14602                            DEDUCE_EXACT, LOOKUP_NORMAL))
14603     return NULL_TREE;
14604
14605   return targs;
14606 }
14607
14608 /* Return the innermost template arguments that, when applied to a
14609    template specialization whose innermost template parameters are
14610    TPARMS, and whose specialization arguments are PARMS, yield the
14611    ARGS.
14612
14613    For example, suppose we have:
14614
14615      template <class T, class U> struct S {};
14616      template <class T> struct S<T*, int> {};
14617
14618    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
14619    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
14620    int}.  The resulting vector will be {double}, indicating that `T'
14621    is bound to `double'.  */
14622
14623 static tree
14624 get_class_bindings (tree tparms, tree spec_args, tree args)
14625 {
14626   int i, ntparms = TREE_VEC_LENGTH (tparms);
14627   tree deduced_args;
14628   tree innermost_deduced_args;
14629
14630   innermost_deduced_args = make_tree_vec (ntparms);
14631   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14632     {
14633       deduced_args = copy_node (args);
14634       SET_TMPL_ARGS_LEVEL (deduced_args,
14635                            TMPL_ARGS_DEPTH (deduced_args),
14636                            innermost_deduced_args);
14637     }
14638   else
14639     deduced_args = innermost_deduced_args;
14640
14641   if (unify (tparms, deduced_args,
14642              INNERMOST_TEMPLATE_ARGS (spec_args),
14643              INNERMOST_TEMPLATE_ARGS (args),
14644              UNIFY_ALLOW_NONE))
14645     return NULL_TREE;
14646
14647   for (i =  0; i < ntparms; ++i)
14648     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14649       return NULL_TREE;
14650
14651   /* Verify that nondeduced template arguments agree with the type
14652      obtained from argument deduction.
14653
14654      For example:
14655
14656        struct A { typedef int X; };
14657        template <class T, class U> struct C {};
14658        template <class T> struct C<T, typename T::X> {};
14659
14660      Then with the instantiation `C<A, int>', we can deduce that
14661      `T' is `A' but unify () does not check whether `typename T::X'
14662      is `int'.  */
14663   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14664   if (spec_args == error_mark_node
14665       /* We only need to check the innermost arguments; the other
14666          arguments will always agree.  */
14667       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14668                               INNERMOST_TEMPLATE_ARGS (args)))
14669     return NULL_TREE;
14670
14671   /* Now that we have bindings for all of the template arguments,
14672      ensure that the arguments deduced for the template template
14673      parameters have compatible template parameter lists.  See the use
14674      of template_template_parm_bindings_ok_p in fn_type_unification
14675      for more information.  */
14676   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14677     return NULL_TREE;
14678
14679   return deduced_args;
14680 }
14681
14682 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14683    Return the TREE_LIST node with the most specialized template, if
14684    any.  If there is no most specialized template, the error_mark_node
14685    is returned.
14686
14687    Note that this function does not look at, or modify, the
14688    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14689    returned is one of the elements of INSTANTIATIONS, callers may
14690    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14691    and retrieve it from the value returned.  */
14692
14693 tree
14694 most_specialized_instantiation (tree templates)
14695 {
14696   tree fn, champ;
14697
14698   ++processing_template_decl;
14699
14700   champ = templates;
14701   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14702     {
14703       int fate = 0;
14704
14705       if (get_bindings (TREE_VALUE (champ),
14706                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14707                         NULL_TREE, /*check_ret=*/false))
14708         fate--;
14709
14710       if (get_bindings (TREE_VALUE (fn),
14711                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14712                         NULL_TREE, /*check_ret=*/false))
14713         fate++;
14714
14715       if (fate == -1)
14716         champ = fn;
14717       else if (!fate)
14718         {
14719           /* Equally specialized, move to next function.  If there
14720              is no next function, nothing's most specialized.  */
14721           fn = TREE_CHAIN (fn);
14722           champ = fn;
14723           if (!fn)
14724             break;
14725         }
14726     }
14727
14728   if (champ)
14729     /* Now verify that champ is better than everything earlier in the
14730        instantiation list.  */
14731     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14732       if (get_bindings (TREE_VALUE (champ),
14733                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14734                         NULL_TREE, /*check_ret=*/false)
14735           || !get_bindings (TREE_VALUE (fn),
14736                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14737                             NULL_TREE, /*check_ret=*/false))
14738         {
14739           champ = NULL_TREE;
14740           break;
14741         }
14742
14743   processing_template_decl--;
14744
14745   if (!champ)
14746     return error_mark_node;
14747
14748   return champ;
14749 }
14750
14751 /* If DECL is a specialization of some template, return the most
14752    general such template.  Otherwise, returns NULL_TREE.
14753
14754    For example, given:
14755
14756      template <class T> struct S { template <class U> void f(U); };
14757
14758    if TMPL is `template <class U> void S<int>::f(U)' this will return
14759    the full template.  This function will not trace past partial
14760    specializations, however.  For example, given in addition:
14761
14762      template <class T> struct S<T*> { template <class U> void f(U); };
14763
14764    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14765    `template <class T> template <class U> S<T*>::f(U)'.  */
14766
14767 tree
14768 most_general_template (tree decl)
14769 {
14770   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14771      an immediate specialization.  */
14772   if (TREE_CODE (decl) == FUNCTION_DECL)
14773     {
14774       if (DECL_TEMPLATE_INFO (decl)) {
14775         decl = DECL_TI_TEMPLATE (decl);
14776
14777         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14778            template friend.  */
14779         if (TREE_CODE (decl) != TEMPLATE_DECL)
14780           return NULL_TREE;
14781       } else
14782         return NULL_TREE;
14783     }
14784
14785   /* Look for more and more general templates.  */
14786   while (DECL_TEMPLATE_INFO (decl))
14787     {
14788       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14789          (See cp-tree.h for details.)  */
14790       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14791         break;
14792
14793       if (CLASS_TYPE_P (TREE_TYPE (decl))
14794           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14795         break;
14796
14797       /* Stop if we run into an explicitly specialized class template.  */
14798       if (!DECL_NAMESPACE_SCOPE_P (decl)
14799           && DECL_CONTEXT (decl)
14800           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14801         break;
14802
14803       decl = DECL_TI_TEMPLATE (decl);
14804     }
14805
14806   return decl;
14807 }
14808
14809 /* Return the most specialized of the class template partial
14810    specializations of TMPL which can produce TYPE, a specialization of
14811    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14812    a _TYPE node corresponding to the partial specialization, while the
14813    TREE_PURPOSE is the set of template arguments that must be
14814    substituted into the TREE_TYPE in order to generate TYPE.
14815
14816    If the choice of partial specialization is ambiguous, a diagnostic
14817    is issued, and the error_mark_node is returned.  If there are no
14818    partial specializations of TMPL matching TYPE, then NULL_TREE is
14819    returned.  */
14820
14821 static tree
14822 most_specialized_class (tree type, tree tmpl)
14823 {
14824   tree list = NULL_TREE;
14825   tree t;
14826   tree champ;
14827   int fate;
14828   bool ambiguous_p;
14829   tree args;
14830   tree outer_args = NULL_TREE;
14831
14832   tmpl = most_general_template (tmpl);
14833   args = CLASSTYPE_TI_ARGS (type);
14834
14835   /* For determining which partial specialization to use, only the
14836      innermost args are interesting.  */
14837   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14838     {
14839       outer_args = strip_innermost_template_args (args, 1);
14840       args = INNERMOST_TEMPLATE_ARGS (args);
14841     }
14842
14843   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14844     {
14845       tree partial_spec_args;
14846       tree spec_args;
14847       tree parms = TREE_VALUE (t);
14848
14849       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14850       if (outer_args)
14851         {
14852           int i;
14853
14854           ++processing_template_decl;
14855
14856           /* Discard the outer levels of args, and then substitute in the
14857              template args from the enclosing class.  */
14858           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14859           partial_spec_args = tsubst_template_args
14860             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14861
14862           /* PARMS already refers to just the innermost parms, but the
14863              template parms in partial_spec_args had their levels lowered
14864              by tsubst, so we need to do the same for the parm list.  We
14865              can't just tsubst the TREE_VEC itself, as tsubst wants to
14866              treat a TREE_VEC as an argument vector.  */
14867           parms = copy_node (parms);
14868           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14869             TREE_VEC_ELT (parms, i) =
14870               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14871
14872           --processing_template_decl;
14873         }
14874       spec_args = get_class_bindings (parms,
14875                                       partial_spec_args,
14876                                       args);
14877       if (spec_args)
14878         {
14879           if (outer_args)
14880             spec_args = add_to_template_args (outer_args, spec_args);
14881           list = tree_cons (spec_args, TREE_VALUE (t), list);
14882           TREE_TYPE (list) = TREE_TYPE (t);
14883         }
14884     }
14885
14886   if (! list)
14887     return NULL_TREE;
14888
14889   ambiguous_p = false;
14890   t = list;
14891   champ = t;
14892   t = TREE_CHAIN (t);
14893   for (; t; t = TREE_CHAIN (t))
14894     {
14895       fate = more_specialized_class (champ, t);
14896       if (fate == 1)
14897         ;
14898       else
14899         {
14900           if (fate == 0)
14901             {
14902               t = TREE_CHAIN (t);
14903               if (! t)
14904                 {
14905                   ambiguous_p = true;
14906                   break;
14907                 }
14908             }
14909           champ = t;
14910         }
14911     }
14912
14913   if (!ambiguous_p)
14914     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14915       {
14916         fate = more_specialized_class (champ, t);
14917         if (fate != 1)
14918           {
14919             ambiguous_p = true;
14920             break;
14921           }
14922       }
14923
14924   if (ambiguous_p)
14925     {
14926       const char *str = "candidates are:";
14927       error ("ambiguous class template instantiation for %q#T", type);
14928       for (t = list; t; t = TREE_CHAIN (t))
14929         {
14930           error ("%s %+#T", str, TREE_TYPE (t));
14931           str = "               ";
14932         }
14933       return error_mark_node;
14934     }
14935
14936   return champ;
14937 }
14938
14939 /* Explicitly instantiate DECL.  */
14940
14941 void
14942 do_decl_instantiation (tree decl, tree storage)
14943 {
14944   tree result = NULL_TREE;
14945   int extern_p = 0;
14946
14947   if (!decl || decl == error_mark_node)
14948     /* An error occurred, for which grokdeclarator has already issued
14949        an appropriate message.  */
14950     return;
14951   else if (! DECL_LANG_SPECIFIC (decl))
14952     {
14953       error ("explicit instantiation of non-template %q#D", decl);
14954       return;
14955     }
14956   else if (TREE_CODE (decl) == VAR_DECL)
14957     {
14958       /* There is an asymmetry here in the way VAR_DECLs and
14959          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14960          the latter, the DECL we get back will be marked as a
14961          template instantiation, and the appropriate
14962          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14963          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14964          should handle VAR_DECLs as it currently handles
14965          FUNCTION_DECLs.  */
14966       if (!DECL_CLASS_SCOPE_P (decl))
14967         {
14968           error ("%qD is not a static data member of a class template", decl);
14969           return;
14970         }
14971       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14972       if (!result || TREE_CODE (result) != VAR_DECL)
14973         {
14974           error ("no matching template for %qD found", decl);
14975           return;
14976         }
14977       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14978         {
14979           error ("type %qT for explicit instantiation %qD does not match "
14980                  "declared type %qT", TREE_TYPE (result), decl,
14981                  TREE_TYPE (decl));
14982           return;
14983         }
14984     }
14985   else if (TREE_CODE (decl) != FUNCTION_DECL)
14986     {
14987       error ("explicit instantiation of %q#D", decl);
14988       return;
14989     }
14990   else
14991     result = decl;
14992
14993   /* Check for various error cases.  Note that if the explicit
14994      instantiation is valid the RESULT will currently be marked as an
14995      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
14996      until we get here.  */
14997
14998   if (DECL_TEMPLATE_SPECIALIZATION (result))
14999     {
15000       /* DR 259 [temp.spec].
15001
15002          Both an explicit instantiation and a declaration of an explicit
15003          specialization shall not appear in a program unless the explicit
15004          instantiation follows a declaration of the explicit specialization.
15005
15006          For a given set of template parameters, if an explicit
15007          instantiation of a template appears after a declaration of an
15008          explicit specialization for that template, the explicit
15009          instantiation has no effect.  */
15010       return;
15011     }
15012   else if (DECL_EXPLICIT_INSTANTIATION (result))
15013     {
15014       /* [temp.spec]
15015
15016          No program shall explicitly instantiate any template more
15017          than once.
15018
15019          We check DECL_NOT_REALLY_EXTERN so as not to complain when
15020          the first instantiation was `extern' and the second is not,
15021          and EXTERN_P for the opposite case.  */
15022       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
15023         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
15024       /* If an "extern" explicit instantiation follows an ordinary
15025          explicit instantiation, the template is instantiated.  */
15026       if (extern_p)
15027         return;
15028     }
15029   else if (!DECL_IMPLICIT_INSTANTIATION (result))
15030     {
15031       error ("no matching template for %qD found", result);
15032       return;
15033     }
15034   else if (!DECL_TEMPLATE_INFO (result))
15035     {
15036       permerror (input_location, "explicit instantiation of non-template %q#D", result);
15037       return;
15038     }
15039
15040   if (storage == NULL_TREE)
15041     ;
15042   else if (storage == ridpointers[(int) RID_EXTERN])
15043     {
15044       if (!in_system_header && (cxx_dialect == cxx98))
15045         pedwarn (input_location, OPT_pedantic, 
15046                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
15047                  "instantiations");
15048       extern_p = 1;
15049     }
15050   else
15051     error ("storage class %qD applied to template instantiation", storage);
15052
15053   check_explicit_instantiation_namespace (result);
15054   mark_decl_instantiated (result, extern_p);
15055   if (! extern_p)
15056     instantiate_decl (result, /*defer_ok=*/1,
15057                       /*expl_inst_class_mem_p=*/false);
15058 }
15059
15060 static void
15061 mark_class_instantiated (tree t, int extern_p)
15062 {
15063   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
15064   SET_CLASSTYPE_INTERFACE_KNOWN (t);
15065   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
15066   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
15067   if (! extern_p)
15068     {
15069       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
15070       rest_of_type_compilation (t, 1);
15071     }
15072 }
15073
15074 /* Called from do_type_instantiation through binding_table_foreach to
15075    do recursive instantiation for the type bound in ENTRY.  */
15076 static void
15077 bt_instantiate_type_proc (binding_entry entry, void *data)
15078 {
15079   tree storage = *(tree *) data;
15080
15081   if (MAYBE_CLASS_TYPE_P (entry->type)
15082       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15083     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15084 }
15085
15086 /* Called from do_type_instantiation to instantiate a member
15087    (a member function or a static member variable) of an
15088    explicitly instantiated class template.  */
15089 static void
15090 instantiate_class_member (tree decl, int extern_p)
15091 {
15092   mark_decl_instantiated (decl, extern_p);
15093   if (! extern_p)
15094     instantiate_decl (decl, /*defer_ok=*/1,
15095                       /*expl_inst_class_mem_p=*/true);
15096 }
15097
15098 /* Perform an explicit instantiation of template class T.  STORAGE, if
15099    non-null, is the RID for extern, inline or static.  COMPLAIN is
15100    nonzero if this is called from the parser, zero if called recursively,
15101    since the standard is unclear (as detailed below).  */
15102
15103 void
15104 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15105 {
15106   int extern_p = 0;
15107   int nomem_p = 0;
15108   int static_p = 0;
15109   int previous_instantiation_extern_p = 0;
15110
15111   if (TREE_CODE (t) == TYPE_DECL)
15112     t = TREE_TYPE (t);
15113
15114   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15115     {
15116       error ("explicit instantiation of non-template type %qT", t);
15117       return;
15118     }
15119
15120   complete_type (t);
15121
15122   if (!COMPLETE_TYPE_P (t))
15123     {
15124       if (complain & tf_error)
15125         error ("explicit instantiation of %q#T before definition of template",
15126                t);
15127       return;
15128     }
15129
15130   if (storage != NULL_TREE)
15131     {
15132       if (!in_system_header)
15133         {
15134           if (storage == ridpointers[(int) RID_EXTERN])
15135             {
15136               if (cxx_dialect == cxx98)
15137                 pedwarn (input_location, OPT_pedantic, 
15138                          "ISO C++ 1998 forbids the use of %<extern%> on "
15139                          "explicit instantiations");
15140             }
15141           else
15142             pedwarn (input_location, OPT_pedantic, 
15143                      "ISO C++ forbids the use of %qE"
15144                      " on explicit instantiations", storage);
15145         }
15146
15147       if (storage == ridpointers[(int) RID_INLINE])
15148         nomem_p = 1;
15149       else if (storage == ridpointers[(int) RID_EXTERN])
15150         extern_p = 1;
15151       else if (storage == ridpointers[(int) RID_STATIC])
15152         static_p = 1;
15153       else
15154         {
15155           error ("storage class %qD applied to template instantiation",
15156                  storage);
15157           extern_p = 0;
15158         }
15159     }
15160
15161   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15162     {
15163       /* DR 259 [temp.spec].
15164
15165          Both an explicit instantiation and a declaration of an explicit
15166          specialization shall not appear in a program unless the explicit
15167          instantiation follows a declaration of the explicit specialization.
15168
15169          For a given set of template parameters, if an explicit
15170          instantiation of a template appears after a declaration of an
15171          explicit specialization for that template, the explicit
15172          instantiation has no effect.  */
15173       return;
15174     }
15175   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15176     {
15177       /* [temp.spec]
15178
15179          No program shall explicitly instantiate any template more
15180          than once.
15181
15182          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15183          instantiation was `extern'.  If EXTERN_P then the second is.
15184          These cases are OK.  */
15185       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15186
15187       if (!previous_instantiation_extern_p && !extern_p
15188           && (complain & tf_error))
15189         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15190
15191       /* If we've already instantiated the template, just return now.  */
15192       if (!CLASSTYPE_INTERFACE_ONLY (t))
15193         return;
15194     }
15195
15196   check_explicit_instantiation_namespace (TYPE_NAME (t));
15197   mark_class_instantiated (t, extern_p);
15198
15199   if (nomem_p)
15200     return;
15201
15202   {
15203     tree tmp;
15204
15205     /* In contrast to implicit instantiation, where only the
15206        declarations, and not the definitions, of members are
15207        instantiated, we have here:
15208
15209          [temp.explicit]
15210
15211          The explicit instantiation of a class template specialization
15212          implies the instantiation of all of its members not
15213          previously explicitly specialized in the translation unit
15214          containing the explicit instantiation.
15215
15216        Of course, we can't instantiate member template classes, since
15217        we don't have any arguments for them.  Note that the standard
15218        is unclear on whether the instantiation of the members are
15219        *explicit* instantiations or not.  However, the most natural
15220        interpretation is that it should be an explicit instantiation.  */
15221
15222     if (! static_p)
15223       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
15224         if (TREE_CODE (tmp) == FUNCTION_DECL
15225             && DECL_TEMPLATE_INSTANTIATION (tmp))
15226           instantiate_class_member (tmp, extern_p);
15227
15228     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
15229       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
15230         instantiate_class_member (tmp, extern_p);
15231
15232     if (CLASSTYPE_NESTED_UTDS (t))
15233       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
15234                              bt_instantiate_type_proc, &storage);
15235   }
15236 }
15237
15238 /* Given a function DECL, which is a specialization of TMPL, modify
15239    DECL to be a re-instantiation of TMPL with the same template
15240    arguments.  TMPL should be the template into which tsubst'ing
15241    should occur for DECL, not the most general template.
15242
15243    One reason for doing this is a scenario like this:
15244
15245      template <class T>
15246      void f(const T&, int i);
15247
15248      void g() { f(3, 7); }
15249
15250      template <class T>
15251      void f(const T& t, const int i) { }
15252
15253    Note that when the template is first instantiated, with
15254    instantiate_template, the resulting DECL will have no name for the
15255    first parameter, and the wrong type for the second.  So, when we go
15256    to instantiate the DECL, we regenerate it.  */
15257
15258 static void
15259 regenerate_decl_from_template (tree decl, tree tmpl)
15260 {
15261   /* The arguments used to instantiate DECL, from the most general
15262      template.  */
15263   tree args;
15264   tree code_pattern;
15265
15266   args = DECL_TI_ARGS (decl);
15267   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
15268
15269   /* Make sure that we can see identifiers, and compute access
15270      correctly.  */
15271   push_access_scope (decl);
15272
15273   if (TREE_CODE (decl) == FUNCTION_DECL)
15274     {
15275       tree decl_parm;
15276       tree pattern_parm;
15277       tree specs;
15278       int args_depth;
15279       int parms_depth;
15280
15281       args_depth = TMPL_ARGS_DEPTH (args);
15282       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
15283       if (args_depth > parms_depth)
15284         args = get_innermost_template_args (args, parms_depth);
15285
15286       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
15287                                               args, tf_error, NULL_TREE);
15288       if (specs)
15289         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
15290                                                     specs);
15291
15292       /* Merge parameter declarations.  */
15293       decl_parm = skip_artificial_parms_for (decl,
15294                                              DECL_ARGUMENTS (decl));
15295       pattern_parm
15296         = skip_artificial_parms_for (code_pattern,
15297                                      DECL_ARGUMENTS (code_pattern));
15298       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
15299         {
15300           tree parm_type;
15301           tree attributes;
15302           
15303           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15304             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
15305           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
15306                               NULL_TREE);
15307           parm_type = type_decays_to (parm_type);
15308           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15309             TREE_TYPE (decl_parm) = parm_type;
15310           attributes = DECL_ATTRIBUTES (pattern_parm);
15311           if (DECL_ATTRIBUTES (decl_parm) != attributes)
15312             {
15313               DECL_ATTRIBUTES (decl_parm) = attributes;
15314               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15315             }
15316           decl_parm = TREE_CHAIN (decl_parm);
15317           pattern_parm = TREE_CHAIN (pattern_parm);
15318         }
15319       /* Merge any parameters that match with the function parameter
15320          pack.  */
15321       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
15322         {
15323           int i, len;
15324           tree expanded_types;
15325           /* Expand the TYPE_PACK_EXPANSION that provides the types for
15326              the parameters in this function parameter pack.  */
15327           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
15328                                                  args, tf_error, NULL_TREE);
15329           len = TREE_VEC_LENGTH (expanded_types);
15330           for (i = 0; i < len; i++)
15331             {
15332               tree parm_type;
15333               tree attributes;
15334           
15335               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15336                 /* Rename the parameter to include the index.  */
15337                 DECL_NAME (decl_parm) = 
15338                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
15339               parm_type = TREE_VEC_ELT (expanded_types, i);
15340               parm_type = type_decays_to (parm_type);
15341               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15342                 TREE_TYPE (decl_parm) = parm_type;
15343               attributes = DECL_ATTRIBUTES (pattern_parm);
15344               if (DECL_ATTRIBUTES (decl_parm) != attributes)
15345                 {
15346                   DECL_ATTRIBUTES (decl_parm) = attributes;
15347                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15348                 }
15349               decl_parm = TREE_CHAIN (decl_parm);
15350             }
15351         }
15352       /* Merge additional specifiers from the CODE_PATTERN.  */
15353       if (DECL_DECLARED_INLINE_P (code_pattern)
15354           && !DECL_DECLARED_INLINE_P (decl))
15355         DECL_DECLARED_INLINE_P (decl) = 1;
15356     }
15357   else if (TREE_CODE (decl) == VAR_DECL)
15358     DECL_INITIAL (decl) =
15359       tsubst_expr (DECL_INITIAL (code_pattern), args,
15360                    tf_error, DECL_TI_TEMPLATE (decl),
15361                    /*integral_constant_expression_p=*/false);
15362   else
15363     gcc_unreachable ();
15364
15365   pop_access_scope (decl);
15366 }
15367
15368 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
15369    substituted to get DECL.  */
15370
15371 tree
15372 template_for_substitution (tree decl)
15373 {
15374   tree tmpl = DECL_TI_TEMPLATE (decl);
15375
15376   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
15377      for the instantiation.  This is not always the most general
15378      template.  Consider, for example:
15379
15380         template <class T>
15381         struct S { template <class U> void f();
15382                    template <> void f<int>(); };
15383
15384      and an instantiation of S<double>::f<int>.  We want TD to be the
15385      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
15386   while (/* An instantiation cannot have a definition, so we need a
15387             more general template.  */
15388          DECL_TEMPLATE_INSTANTIATION (tmpl)
15389            /* We must also deal with friend templates.  Given:
15390
15391                 template <class T> struct S {
15392                   template <class U> friend void f() {};
15393                 };
15394
15395               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15396               so far as the language is concerned, but that's still
15397               where we get the pattern for the instantiation from.  On
15398               other hand, if the definition comes outside the class, say:
15399
15400                 template <class T> struct S {
15401                   template <class U> friend void f();
15402                 };
15403                 template <class U> friend void f() {}
15404
15405               we don't need to look any further.  That's what the check for
15406               DECL_INITIAL is for.  */
15407           || (TREE_CODE (decl) == FUNCTION_DECL
15408               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
15409               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
15410     {
15411       /* The present template, TD, should not be a definition.  If it
15412          were a definition, we should be using it!  Note that we
15413          cannot restructure the loop to just keep going until we find
15414          a template with a definition, since that might go too far if
15415          a specialization was declared, but not defined.  */
15416       gcc_assert (TREE_CODE (decl) != VAR_DECL
15417                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
15418
15419       /* Fetch the more general template.  */
15420       tmpl = DECL_TI_TEMPLATE (tmpl);
15421     }
15422
15423   return tmpl;
15424 }
15425
15426 /* Produce the definition of D, a _DECL generated from a template.  If
15427    DEFER_OK is nonzero, then we don't have to actually do the
15428    instantiation now; we just have to do it sometime.  Normally it is
15429    an error if this is an explicit instantiation but D is undefined.
15430    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
15431    explicitly instantiated class template.  */
15432
15433 tree
15434 instantiate_decl (tree d, int defer_ok,
15435                   bool expl_inst_class_mem_p)
15436 {
15437   tree tmpl = DECL_TI_TEMPLATE (d);
15438   tree gen_args;
15439   tree args;
15440   tree td;
15441   tree code_pattern;
15442   tree spec;
15443   tree gen_tmpl;
15444   bool pattern_defined;
15445   int need_push;
15446   location_t saved_loc = input_location;
15447   bool external_p;
15448
15449   /* This function should only be used to instantiate templates for
15450      functions and static member variables.  */
15451   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
15452               || TREE_CODE (d) == VAR_DECL);
15453
15454   /* Variables are never deferred; if instantiation is required, they
15455      are instantiated right away.  That allows for better code in the
15456      case that an expression refers to the value of the variable --
15457      if the variable has a constant value the referring expression can
15458      take advantage of that fact.  */
15459   if (TREE_CODE (d) == VAR_DECL)
15460     defer_ok = 0;
15461
15462   /* Don't instantiate cloned functions.  Instead, instantiate the
15463      functions they cloned.  */
15464   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
15465     d = DECL_CLONED_FUNCTION (d);
15466
15467   if (DECL_TEMPLATE_INSTANTIATED (d))
15468     /* D has already been instantiated.  It might seem reasonable to
15469        check whether or not D is an explicit instantiation, and, if so,
15470        stop here.  But when an explicit instantiation is deferred
15471        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
15472        is set, even though we still need to do the instantiation.  */
15473     return d;
15474
15475   /* If we already have a specialization of this declaration, then
15476      there's no reason to instantiate it.  Note that
15477      retrieve_specialization gives us both instantiations and
15478      specializations, so we must explicitly check
15479      DECL_TEMPLATE_SPECIALIZATION.  */
15480   gen_tmpl = most_general_template (tmpl);
15481   gen_args = DECL_TI_ARGS (d);
15482   spec = retrieve_specialization (gen_tmpl, gen_args,
15483                                   /*class_specializations_p=*/false);
15484   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
15485     return spec;
15486
15487   /* This needs to happen before any tsubsting.  */
15488   if (! push_tinst_level (d))
15489     return d;
15490
15491   timevar_push (TV_PARSE);
15492
15493   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
15494      for the instantiation.  */
15495   td = template_for_substitution (d);
15496   code_pattern = DECL_TEMPLATE_RESULT (td);
15497
15498   /* We should never be trying to instantiate a member of a class
15499      template or partial specialization.  */
15500   gcc_assert (d != code_pattern);
15501
15502   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
15503       || DECL_TEMPLATE_SPECIALIZATION (td))
15504     /* In the case of a friend template whose definition is provided
15505        outside the class, we may have too many arguments.  Drop the
15506        ones we don't need.  The same is true for specializations.  */
15507     args = get_innermost_template_args
15508       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
15509   else
15510     args = gen_args;
15511
15512   if (TREE_CODE (d) == FUNCTION_DECL)
15513     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
15514   else
15515     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
15516
15517   /* We may be in the middle of deferred access check.  Disable it now.  */
15518   push_deferring_access_checks (dk_no_deferred);
15519
15520   /* Unless an explicit instantiation directive has already determined
15521      the linkage of D, remember that a definition is available for
15522      this entity.  */
15523   if (pattern_defined
15524       && !DECL_INTERFACE_KNOWN (d)
15525       && !DECL_NOT_REALLY_EXTERN (d))
15526     mark_definable (d);
15527
15528   input_location = DECL_SOURCE_LOCATION (d);
15529
15530   /* If D is a member of an explicitly instantiated class template,
15531      and no definition is available, treat it like an implicit
15532      instantiation.  */
15533   if (!pattern_defined && expl_inst_class_mem_p
15534       && DECL_EXPLICIT_INSTANTIATION (d))
15535     {
15536       DECL_NOT_REALLY_EXTERN (d) = 0;
15537       DECL_INTERFACE_KNOWN (d) = 0;
15538       SET_DECL_IMPLICIT_INSTANTIATION (d);
15539     }
15540
15541   if (!defer_ok)
15542     {
15543       /* Recheck the substitutions to obtain any warning messages
15544          about ignoring cv qualifiers.  */
15545       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
15546       tree type = TREE_TYPE (gen);
15547
15548       /* Make sure that we can see identifiers, and compute access
15549          correctly.  D is already the target FUNCTION_DECL with the
15550          right context.  */
15551       push_access_scope (d);
15552
15553       if (TREE_CODE (gen) == FUNCTION_DECL)
15554         {
15555           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
15556           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
15557                                           d);
15558           /* Don't simply tsubst the function type, as that will give
15559              duplicate warnings about poor parameter qualifications.
15560              The function arguments are the same as the decl_arguments
15561              without the top level cv qualifiers.  */
15562           type = TREE_TYPE (type);
15563         }
15564       tsubst (type, gen_args, tf_warning_or_error, d);
15565
15566       pop_access_scope (d);
15567     }
15568
15569   /* Check to see whether we know that this template will be
15570      instantiated in some other file, as with "extern template"
15571      extension.  */
15572   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
15573   /* In general, we do not instantiate such templates...  */
15574   if (external_p
15575       /* ... but we instantiate inline functions so that we can inline
15576          them.  An explicit instantiation declaration prohibits implicit
15577          instantiation of non-inline functions.  With high levels of
15578          optimization, we would normally inline non-inline functions
15579          -- but we're not allowed to do that for "extern template" functions.
15580          Therefore, we check DECL_DECLARED_INLINE_P, rather than
15581          possibly_inlined_p.  And ...  */
15582       && ! (TREE_CODE (d) == FUNCTION_DECL
15583             && DECL_DECLARED_INLINE_P (d))
15584       /* ... we instantiate static data members whose values are
15585          needed in integral constant expressions.  */
15586       && ! (TREE_CODE (d) == VAR_DECL
15587             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
15588     goto out;
15589   /* Defer all other templates, unless we have been explicitly
15590      forbidden from doing so.  */
15591   if (/* If there is no definition, we cannot instantiate the
15592          template.  */
15593       ! pattern_defined
15594       /* If it's OK to postpone instantiation, do so.  */
15595       || defer_ok
15596       /* If this is a static data member that will be defined
15597          elsewhere, we don't want to instantiate the entire data
15598          member, but we do want to instantiate the initializer so that
15599          we can substitute that elsewhere.  */
15600       || (external_p && TREE_CODE (d) == VAR_DECL))
15601     {
15602       /* The definition of the static data member is now required so
15603          we must substitute the initializer.  */
15604       if (TREE_CODE (d) == VAR_DECL
15605           && !DECL_INITIAL (d)
15606           && DECL_INITIAL (code_pattern))
15607         {
15608           tree ns;
15609           tree init;
15610
15611           ns = decl_namespace_context (d);
15612           push_nested_namespace (ns);
15613           push_nested_class (DECL_CONTEXT (d));
15614           init = tsubst_expr (DECL_INITIAL (code_pattern),
15615                               args,
15616                               tf_warning_or_error, NULL_TREE,
15617                               /*integral_constant_expression_p=*/false);
15618           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
15619                           /*asmspec_tree=*/NULL_TREE,
15620                           LOOKUP_ONLYCONVERTING);
15621           pop_nested_class ();
15622           pop_nested_namespace (ns);
15623         }
15624
15625       /* We restore the source position here because it's used by
15626          add_pending_template.  */
15627       input_location = saved_loc;
15628
15629       if (at_eof && !pattern_defined
15630           && DECL_EXPLICIT_INSTANTIATION (d)
15631           && DECL_NOT_REALLY_EXTERN (d))
15632         /* [temp.explicit]
15633
15634            The definition of a non-exported function template, a
15635            non-exported member function template, or a non-exported
15636            member function or static data member of a class template
15637            shall be present in every translation unit in which it is
15638            explicitly instantiated.  */
15639         permerror (input_location,  "explicit instantiation of %qD "
15640                    "but no definition available", d);
15641
15642       /* ??? Historically, we have instantiated inline functions, even
15643          when marked as "extern template".  */
15644       if (!(external_p && TREE_CODE (d) == VAR_DECL))
15645         add_pending_template (d);
15646       goto out;
15647     }
15648   /* Tell the repository that D is available in this translation unit
15649      -- and see if it is supposed to be instantiated here.  */
15650   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15651     {
15652       /* In a PCH file, despite the fact that the repository hasn't
15653          requested instantiation in the PCH it is still possible that
15654          an instantiation will be required in a file that includes the
15655          PCH.  */
15656       if (pch_file)
15657         add_pending_template (d);
15658       /* Instantiate inline functions so that the inliner can do its
15659          job, even though we'll not be emitting a copy of this
15660          function.  */
15661       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
15662         goto out;
15663     }
15664
15665   need_push = !cfun || !global_bindings_p ();
15666   if (need_push)
15667     push_to_top_level ();
15668
15669   /* Mark D as instantiated so that recursive calls to
15670      instantiate_decl do not try to instantiate it again.  */
15671   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15672
15673   /* Regenerate the declaration in case the template has been modified
15674      by a subsequent redeclaration.  */
15675   regenerate_decl_from_template (d, td);
15676
15677   /* We already set the file and line above.  Reset them now in case
15678      they changed as a result of calling regenerate_decl_from_template.  */
15679   input_location = DECL_SOURCE_LOCATION (d);
15680
15681   if (TREE_CODE (d) == VAR_DECL)
15682     {
15683       tree init;
15684
15685       /* Clear out DECL_RTL; whatever was there before may not be right
15686          since we've reset the type of the declaration.  */
15687       SET_DECL_RTL (d, NULL_RTX);
15688       DECL_IN_AGGR_P (d) = 0;
15689
15690       /* The initializer is placed in DECL_INITIAL by
15691          regenerate_decl_from_template.  Pull it out so that
15692          finish_decl can process it.  */
15693       init = DECL_INITIAL (d);
15694       DECL_INITIAL (d) = NULL_TREE;
15695       DECL_INITIALIZED_P (d) = 0;
15696
15697       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15698          initializer.  That function will defer actual emission until
15699          we have a chance to determine linkage.  */
15700       DECL_EXTERNAL (d) = 0;
15701
15702       /* Enter the scope of D so that access-checking works correctly.  */
15703       push_nested_class (DECL_CONTEXT (d));
15704       finish_decl (d, init, NULL_TREE);
15705       pop_nested_class ();
15706     }
15707   else if (TREE_CODE (d) == FUNCTION_DECL)
15708     {
15709       htab_t saved_local_specializations;
15710       tree subst_decl;
15711       tree tmpl_parm;
15712       tree spec_parm;
15713
15714       /* Save away the current list, in case we are instantiating one
15715          template from within the body of another.  */
15716       saved_local_specializations = local_specializations;
15717
15718       /* Set up the list of local specializations.  */
15719       local_specializations = htab_create (37,
15720                                            hash_local_specialization,
15721                                            eq_local_specializations,
15722                                            NULL);
15723
15724       /* Set up context.  */
15725       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15726
15727       /* Create substitution entries for the parameters.  */
15728       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15729       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15730       spec_parm = DECL_ARGUMENTS (d);
15731       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15732         {
15733           register_local_specialization (spec_parm, tmpl_parm);
15734           spec_parm = skip_artificial_parms_for (d, spec_parm);
15735           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15736         }
15737       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15738         {
15739           register_local_specialization (spec_parm, tmpl_parm);
15740           tmpl_parm = TREE_CHAIN (tmpl_parm);
15741           spec_parm = TREE_CHAIN (spec_parm);
15742         }
15743       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15744         {
15745           /* Register the (value) argument pack as a specialization of
15746              TMPL_PARM, then move on.  */
15747           tree argpack = make_fnparm_pack (spec_parm);
15748           register_local_specialization (argpack, tmpl_parm);
15749           tmpl_parm = TREE_CHAIN (tmpl_parm);
15750           spec_parm = NULL_TREE;
15751         }
15752       gcc_assert (!spec_parm);
15753
15754       /* Substitute into the body of the function.  */
15755       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15756                    tf_warning_or_error, tmpl,
15757                    /*integral_constant_expression_p=*/false);
15758
15759       /* Set the current input_location to the end of the function
15760          so that finish_function knows where we are.  */
15761       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15762
15763       /* We don't need the local specializations any more.  */
15764       htab_delete (local_specializations);
15765       local_specializations = saved_local_specializations;
15766
15767       /* Finish the function.  */
15768       d = finish_function (0);
15769       expand_or_defer_fn (d);
15770     }
15771
15772   /* We're not deferring instantiation any more.  */
15773   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15774
15775   if (need_push)
15776     pop_from_top_level ();
15777
15778 out:
15779   input_location = saved_loc;
15780   pop_deferring_access_checks ();
15781   pop_tinst_level ();
15782
15783   timevar_pop (TV_PARSE);
15784
15785   return d;
15786 }
15787
15788 /* Run through the list of templates that we wish we could
15789    instantiate, and instantiate any we can.  RETRIES is the
15790    number of times we retry pending template instantiation.  */
15791
15792 void
15793 instantiate_pending_templates (int retries)
15794 {
15795   int reconsider;
15796   location_t saved_loc = input_location;
15797
15798   /* Instantiating templates may trigger vtable generation.  This in turn
15799      may require further template instantiations.  We place a limit here
15800      to avoid infinite loop.  */
15801   if (pending_templates && retries >= max_tinst_depth)
15802     {
15803       tree decl = pending_templates->tinst->decl;
15804
15805       error ("template instantiation depth exceeds maximum of %d"
15806              " instantiating %q+D, possibly from virtual table generation"
15807              " (use -ftemplate-depth-NN to increase the maximum)",
15808              max_tinst_depth, decl);
15809       if (TREE_CODE (decl) == FUNCTION_DECL)
15810         /* Pretend that we defined it.  */
15811         DECL_INITIAL (decl) = error_mark_node;
15812       return;
15813     }
15814
15815   do
15816     {
15817       struct pending_template **t = &pending_templates;
15818       struct pending_template *last = NULL;
15819       reconsider = 0;
15820       while (*t)
15821         {
15822           tree instantiation = reopen_tinst_level ((*t)->tinst);
15823           bool complete = false;
15824
15825           if (TYPE_P (instantiation))
15826             {
15827               tree fn;
15828
15829               if (!COMPLETE_TYPE_P (instantiation))
15830                 {
15831                   instantiate_class_template (instantiation);
15832                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15833                     for (fn = TYPE_METHODS (instantiation);
15834                          fn;
15835                          fn = TREE_CHAIN (fn))
15836                       if (! DECL_ARTIFICIAL (fn))
15837                         instantiate_decl (fn,
15838                                           /*defer_ok=*/0,
15839                                           /*expl_inst_class_mem_p=*/false);
15840                   if (COMPLETE_TYPE_P (instantiation))
15841                     reconsider = 1;
15842                 }
15843
15844               complete = COMPLETE_TYPE_P (instantiation);
15845             }
15846           else
15847             {
15848               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15849                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15850                 {
15851                   instantiation
15852                     = instantiate_decl (instantiation,
15853                                         /*defer_ok=*/0,
15854                                         /*expl_inst_class_mem_p=*/false);
15855                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15856                     reconsider = 1;
15857                 }
15858
15859               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15860                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15861             }
15862
15863           if (complete)
15864             /* If INSTANTIATION has been instantiated, then we don't
15865                need to consider it again in the future.  */
15866             *t = (*t)->next;
15867           else
15868             {
15869               last = *t;
15870               t = &(*t)->next;
15871             }
15872           tinst_depth = 0;
15873           current_tinst_level = NULL;
15874         }
15875       last_pending_template = last;
15876     }
15877   while (reconsider);
15878
15879   input_location = saved_loc;
15880 }
15881
15882 /* Substitute ARGVEC into T, which is a list of initializers for
15883    either base class or a non-static data member.  The TREE_PURPOSEs
15884    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15885    instantiate_decl.  */
15886
15887 static tree
15888 tsubst_initializer_list (tree t, tree argvec)
15889 {
15890   tree inits = NULL_TREE;
15891
15892   for (; t; t = TREE_CHAIN (t))
15893     {
15894       tree decl;
15895       tree init;
15896       tree expanded_bases = NULL_TREE;
15897       tree expanded_arguments = NULL_TREE;
15898       int i, len = 1;
15899
15900       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15901         {
15902           tree expr;
15903           tree arg;
15904
15905           /* Expand the base class expansion type into separate base
15906              classes.  */
15907           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15908                                                  tf_warning_or_error,
15909                                                  NULL_TREE);
15910           if (expanded_bases == error_mark_node)
15911             continue;
15912           
15913           /* We'll be building separate TREE_LISTs of arguments for
15914              each base.  */
15915           len = TREE_VEC_LENGTH (expanded_bases);
15916           expanded_arguments = make_tree_vec (len);
15917           for (i = 0; i < len; i++)
15918             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15919
15920           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15921              expand each argument in the TREE_VALUE of t.  */
15922           expr = make_node (EXPR_PACK_EXPANSION);
15923           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15924             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15925
15926           if (TREE_VALUE (t) == void_type_node)
15927             /* VOID_TYPE_NODE is used to indicate
15928                value-initialization.  */
15929             {
15930               for (i = 0; i < len; i++)
15931                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
15932             }
15933           else
15934             {
15935               /* Substitute parameter packs into each argument in the
15936                  TREE_LIST.  */
15937               in_base_initializer = 1;
15938               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15939                 {
15940                   tree expanded_exprs;
15941
15942                   /* Expand the argument.  */
15943                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15944                   expanded_exprs 
15945                     = tsubst_pack_expansion (expr, argvec,
15946                                              tf_warning_or_error,
15947                                              NULL_TREE);
15948                   if (expanded_exprs == error_mark_node)
15949                     continue;
15950
15951                   /* Prepend each of the expanded expressions to the
15952                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15953                   for (i = 0; i < len; i++)
15954                     {
15955                       TREE_VEC_ELT (expanded_arguments, i) = 
15956                         tree_cons (NULL_TREE, 
15957                                    TREE_VEC_ELT (expanded_exprs, i),
15958                                    TREE_VEC_ELT (expanded_arguments, i));
15959                     }
15960                 }
15961               in_base_initializer = 0;
15962
15963               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15964                  since we built them backwards.  */
15965               for (i = 0; i < len; i++)
15966                 {
15967                   TREE_VEC_ELT (expanded_arguments, i) = 
15968                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
15969                 }
15970             }
15971         }
15972
15973       for (i = 0; i < len; ++i)
15974         {
15975           if (expanded_bases)
15976             {
15977               decl = TREE_VEC_ELT (expanded_bases, i);
15978               decl = expand_member_init (decl);
15979               init = TREE_VEC_ELT (expanded_arguments, i);
15980             }
15981           else
15982             {
15983               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15984                                   tf_warning_or_error, NULL_TREE);
15985
15986               decl = expand_member_init (decl);
15987               if (decl && !DECL_P (decl))
15988                 in_base_initializer = 1;
15989
15990               init = tsubst_expr (TREE_VALUE (t), argvec, 
15991                                   tf_warning_or_error, NULL_TREE,
15992                                   /*integral_constant_expression_p=*/false);
15993               in_base_initializer = 0;
15994             }
15995
15996           if (decl)
15997             {
15998               init = build_tree_list (decl, init);
15999               TREE_CHAIN (init) = inits;
16000               inits = init;
16001             }
16002         }
16003     }
16004   return inits;
16005 }
16006
16007 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
16008
16009 static void
16010 set_current_access_from_decl (tree decl)
16011 {
16012   if (TREE_PRIVATE (decl))
16013     current_access_specifier = access_private_node;
16014   else if (TREE_PROTECTED (decl))
16015     current_access_specifier = access_protected_node;
16016   else
16017     current_access_specifier = access_public_node;
16018 }
16019
16020 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
16021    is the instantiation (which should have been created with
16022    start_enum) and ARGS are the template arguments to use.  */
16023
16024 static void
16025 tsubst_enum (tree tag, tree newtag, tree args)
16026 {
16027   tree e;
16028
16029   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
16030     {
16031       tree value;
16032       tree decl;
16033
16034       decl = TREE_VALUE (e);
16035       /* Note that in a template enum, the TREE_VALUE is the
16036          CONST_DECL, not the corresponding INTEGER_CST.  */
16037       value = tsubst_expr (DECL_INITIAL (decl),
16038                            args, tf_warning_or_error, NULL_TREE,
16039                            /*integral_constant_expression_p=*/true);
16040
16041       /* Give this enumeration constant the correct access.  */
16042       set_current_access_from_decl (decl);
16043
16044       /* Actually build the enumerator itself.  */
16045       build_enumerator (DECL_NAME (decl), value, newtag);
16046     }
16047
16048   finish_enum (newtag);
16049   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
16050     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
16051 }
16052
16053 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
16054    its type -- but without substituting the innermost set of template
16055    arguments.  So, innermost set of template parameters will appear in
16056    the type.  */
16057
16058 tree
16059 get_mostly_instantiated_function_type (tree decl)
16060 {
16061   tree fn_type;
16062   tree tmpl;
16063   tree targs;
16064   tree tparms;
16065   int parm_depth;
16066
16067   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16068   targs = DECL_TI_ARGS (decl);
16069   tparms = DECL_TEMPLATE_PARMS (tmpl);
16070   parm_depth = TMPL_PARMS_DEPTH (tparms);
16071
16072   /* There should be as many levels of arguments as there are levels
16073      of parameters.  */
16074   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16075
16076   fn_type = TREE_TYPE (tmpl);
16077
16078   if (parm_depth == 1)
16079     /* No substitution is necessary.  */
16080     ;
16081   else
16082     {
16083       int i, save_access_control;
16084       tree partial_args;
16085
16086       /* Replace the innermost level of the TARGS with NULL_TREEs to
16087          let tsubst know not to substitute for those parameters.  */
16088       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16089       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16090         SET_TMPL_ARGS_LEVEL (partial_args, i,
16091                              TMPL_ARGS_LEVEL (targs, i));
16092       SET_TMPL_ARGS_LEVEL (partial_args,
16093                            TMPL_ARGS_DEPTH (targs),
16094                            make_tree_vec (DECL_NTPARMS (tmpl)));
16095
16096       /* Disable access control as this function is used only during
16097          name-mangling.  */
16098       save_access_control = flag_access_control;
16099       flag_access_control = 0;
16100
16101       ++processing_template_decl;
16102       /* Now, do the (partial) substitution to figure out the
16103          appropriate function type.  */
16104       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16105       --processing_template_decl;
16106
16107       /* Substitute into the template parameters to obtain the real
16108          innermost set of parameters.  This step is important if the
16109          innermost set of template parameters contains value
16110          parameters whose types depend on outer template parameters.  */
16111       TREE_VEC_LENGTH (partial_args)--;
16112       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16113
16114       flag_access_control = save_access_control;
16115     }
16116
16117   return fn_type;
16118 }
16119
16120 /* Return truthvalue if we're processing a template different from
16121    the last one involved in diagnostics.  */
16122 int
16123 problematic_instantiation_changed (void)
16124 {
16125   return last_template_error_tick != tinst_level_tick;
16126 }
16127
16128 /* Remember current template involved in diagnostics.  */
16129 void
16130 record_last_problematic_instantiation (void)
16131 {
16132   last_template_error_tick = tinst_level_tick;
16133 }
16134
16135 struct tinst_level *
16136 current_instantiation (void)
16137 {
16138   return current_tinst_level;
16139 }
16140
16141 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16142    type. Return zero for ok, nonzero for disallowed. Issue error and
16143    warning messages under control of COMPLAIN.  */
16144
16145 static int
16146 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16147 {
16148   if (INTEGRAL_TYPE_P (type))
16149     return 0;
16150   else if (POINTER_TYPE_P (type))
16151     return 0;
16152   else if (TYPE_PTR_TO_MEMBER_P (type))
16153     return 0;
16154   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16155     return 0;
16156   else if (TREE_CODE (type) == TYPENAME_TYPE)
16157     return 0;
16158
16159   if (complain & tf_error)
16160     error ("%q#T is not a valid type for a template constant parameter", type);
16161   return 1;
16162 }
16163
16164 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16165    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16166
16167 static bool
16168 dependent_type_p_r (tree type)
16169 {
16170   tree scope;
16171
16172   /* [temp.dep.type]
16173
16174      A type is dependent if it is:
16175
16176      -- a template parameter. Template template parameters are types
16177         for us (since TYPE_P holds true for them) so we handle
16178         them here.  */
16179   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16180       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
16181     return true;
16182   /* -- a qualified-id with a nested-name-specifier which contains a
16183         class-name that names a dependent type or whose unqualified-id
16184         names a dependent type.  */
16185   if (TREE_CODE (type) == TYPENAME_TYPE)
16186     return true;
16187   /* -- a cv-qualified type where the cv-unqualified type is
16188         dependent.  */
16189   type = TYPE_MAIN_VARIANT (type);
16190   /* -- a compound type constructed from any dependent type.  */
16191   if (TYPE_PTR_TO_MEMBER_P (type))
16192     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
16193             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
16194                                            (type)));
16195   else if (TREE_CODE (type) == POINTER_TYPE
16196            || TREE_CODE (type) == REFERENCE_TYPE)
16197     return dependent_type_p (TREE_TYPE (type));
16198   else if (TREE_CODE (type) == FUNCTION_TYPE
16199            || TREE_CODE (type) == METHOD_TYPE)
16200     {
16201       tree arg_type;
16202
16203       if (dependent_type_p (TREE_TYPE (type)))
16204         return true;
16205       for (arg_type = TYPE_ARG_TYPES (type);
16206            arg_type;
16207            arg_type = TREE_CHAIN (arg_type))
16208         if (dependent_type_p (TREE_VALUE (arg_type)))
16209           return true;
16210       return false;
16211     }
16212   /* -- an array type constructed from any dependent type or whose
16213         size is specified by a constant expression that is
16214         value-dependent.  */
16215   if (TREE_CODE (type) == ARRAY_TYPE)
16216     {
16217       if (TYPE_DOMAIN (type)
16218           && dependent_type_p (TYPE_DOMAIN (type)))
16219         return true;
16220       return dependent_type_p (TREE_TYPE (type));
16221     }
16222   else if (TREE_CODE (type) == INTEGER_TYPE
16223            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
16224     {
16225       /* If this is the TYPE_DOMAIN of an array type, consider it
16226          dependent.  We already checked for value-dependence in
16227          compute_array_index_type.  */
16228       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
16229     }
16230
16231   /* -- a template-id in which either the template name is a template
16232      parameter ...  */
16233   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16234     return true;
16235   /* ... or any of the template arguments is a dependent type or
16236         an expression that is type-dependent or value-dependent.  */
16237   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
16238            && (any_dependent_template_arguments_p
16239                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
16240     return true;
16241
16242   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
16243      argument of the `typeof' expression is not type-dependent, then
16244      it should already been have resolved.  */
16245   if (TREE_CODE (type) == TYPEOF_TYPE
16246       || TREE_CODE (type) == DECLTYPE_TYPE)
16247     return true;
16248
16249   /* A template argument pack is dependent if any of its packed
16250      arguments are.  */
16251   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
16252     {
16253       tree args = ARGUMENT_PACK_ARGS (type);
16254       int i, len = TREE_VEC_LENGTH (args);
16255       for (i = 0; i < len; ++i)
16256         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16257           return true;
16258     }
16259
16260   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
16261      be template parameters.  */
16262   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
16263     return true;
16264
16265   /* The standard does not specifically mention types that are local
16266      to template functions or local classes, but they should be
16267      considered dependent too.  For example:
16268
16269        template <int I> void f() {
16270          enum E { a = I };
16271          S<sizeof (E)> s;
16272        }
16273
16274      The size of `E' cannot be known until the value of `I' has been
16275      determined.  Therefore, `E' must be considered dependent.  */
16276   scope = TYPE_CONTEXT (type);
16277   if (scope && TYPE_P (scope))
16278     return dependent_type_p (scope);
16279   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
16280     return type_dependent_expression_p (scope);
16281
16282   /* Other types are non-dependent.  */
16283   return false;
16284 }
16285
16286 /* Returns TRUE if TYPE is dependent, in the sense of
16287    [temp.dep.type].  */
16288
16289 bool
16290 dependent_type_p (tree type)
16291 {
16292   /* If there are no template parameters in scope, then there can't be
16293      any dependent types.  */
16294   if (!processing_template_decl)
16295     {
16296       /* If we are not processing a template, then nobody should be
16297          providing us with a dependent type.  */
16298       gcc_assert (type);
16299       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
16300       return false;
16301     }
16302
16303   /* If the type is NULL, we have not computed a type for the entity
16304      in question; in that case, the type is dependent.  */
16305   if (!type)
16306     return true;
16307
16308   /* Erroneous types can be considered non-dependent.  */
16309   if (type == error_mark_node)
16310     return false;
16311
16312   /* If we have not already computed the appropriate value for TYPE,
16313      do so now.  */
16314   if (!TYPE_DEPENDENT_P_VALID (type))
16315     {
16316       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
16317       TYPE_DEPENDENT_P_VALID (type) = 1;
16318     }
16319
16320   return TYPE_DEPENDENT_P (type);
16321 }
16322
16323 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
16324    lookup.  In other words, a dependent type that is not the current
16325    instantiation.  */
16326
16327 bool
16328 dependent_scope_p (tree scope)
16329 {
16330   return (scope && TYPE_P (scope) && dependent_type_p (scope)
16331           && !currently_open_class (scope));
16332 }
16333
16334 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
16335
16336 static bool
16337 dependent_scope_ref_p (tree expression, bool criterion (tree))
16338 {
16339   tree scope;
16340   tree name;
16341
16342   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
16343
16344   if (!TYPE_P (TREE_OPERAND (expression, 0)))
16345     return true;
16346
16347   scope = TREE_OPERAND (expression, 0);
16348   name = TREE_OPERAND (expression, 1);
16349
16350   /* [temp.dep.expr]
16351
16352      An id-expression is type-dependent if it contains a
16353      nested-name-specifier that contains a class-name that names a
16354      dependent type.  */
16355   /* The suggested resolution to Core Issue 224 implies that if the
16356      qualifying type is the current class, then we must peek
16357      inside it.  */
16358   if (DECL_P (name)
16359       && currently_open_class (scope)
16360       && !criterion (name))
16361     return false;
16362   if (dependent_type_p (scope))
16363     return true;
16364
16365   return false;
16366 }
16367
16368 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
16369    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
16370    expression.  */
16371
16372 bool
16373 value_dependent_expression_p (tree expression)
16374 {
16375   if (!processing_template_decl)
16376     return false;
16377
16378   /* A name declared with a dependent type.  */
16379   if (DECL_P (expression) && type_dependent_expression_p (expression))
16380     return true;
16381
16382   switch (TREE_CODE (expression))
16383     {
16384     case IDENTIFIER_NODE:
16385       /* A name that has not been looked up -- must be dependent.  */
16386       return true;
16387
16388     case TEMPLATE_PARM_INDEX:
16389       /* A non-type template parm.  */
16390       return true;
16391
16392     case CONST_DECL:
16393       /* A non-type template parm.  */
16394       if (DECL_TEMPLATE_PARM_P (expression))
16395         return true;
16396       return value_dependent_expression_p (DECL_INITIAL (expression));
16397
16398     case VAR_DECL:
16399        /* A constant with integral or enumeration type and is initialized
16400           with an expression that is value-dependent.  */
16401       if (DECL_INITIAL (expression)
16402           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
16403           && value_dependent_expression_p (DECL_INITIAL (expression)))
16404         return true;
16405       return false;
16406
16407     case DYNAMIC_CAST_EXPR:
16408     case STATIC_CAST_EXPR:
16409     case CONST_CAST_EXPR:
16410     case REINTERPRET_CAST_EXPR:
16411     case CAST_EXPR:
16412       /* These expressions are value-dependent if the type to which
16413          the cast occurs is dependent or the expression being casted
16414          is value-dependent.  */
16415       {
16416         tree type = TREE_TYPE (expression);
16417
16418         if (dependent_type_p (type))
16419           return true;
16420
16421         /* A functional cast has a list of operands.  */
16422         expression = TREE_OPERAND (expression, 0);
16423         if (!expression)
16424           {
16425             /* If there are no operands, it must be an expression such
16426                as "int()". This should not happen for aggregate types
16427                because it would form non-constant expressions.  */
16428             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
16429
16430             return false;
16431           }
16432
16433         if (TREE_CODE (expression) == TREE_LIST)
16434           return any_value_dependent_elements_p (expression);
16435
16436         return value_dependent_expression_p (expression);
16437       }
16438
16439     case SIZEOF_EXPR:
16440     case ALIGNOF_EXPR:
16441       /* A `sizeof' expression is value-dependent if the operand is
16442          type-dependent or is a pack expansion.  */
16443       expression = TREE_OPERAND (expression, 0);
16444       if (PACK_EXPANSION_P (expression))
16445         return true;
16446       else if (TYPE_P (expression))
16447         return dependent_type_p (expression);
16448       return type_dependent_expression_p (expression);
16449
16450     case SCOPE_REF:
16451       return dependent_scope_ref_p (expression, value_dependent_expression_p);
16452
16453     case COMPONENT_REF:
16454       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
16455               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
16456
16457     case CALL_EXPR:
16458       /* A CALL_EXPR may appear in a constant expression if it is a
16459          call to a builtin function, e.g., __builtin_constant_p.  All
16460          such calls are value-dependent.  */
16461       return true;
16462
16463     case NONTYPE_ARGUMENT_PACK:
16464       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
16465          is value-dependent.  */
16466       {
16467         tree values = ARGUMENT_PACK_ARGS (expression);
16468         int i, len = TREE_VEC_LENGTH (values);
16469         
16470         for (i = 0; i < len; ++i)
16471           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
16472             return true;
16473         
16474         return false;
16475       }
16476
16477     case TRAIT_EXPR:
16478       {
16479         tree type2 = TRAIT_EXPR_TYPE2 (expression);
16480         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
16481                 || (type2 ? dependent_type_p (type2) : false));
16482       }
16483
16484     case MODOP_EXPR:
16485       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
16486               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
16487
16488     case ADDR_EXPR:
16489       {
16490         tree op = TREE_OPERAND (expression, 0);
16491         return (value_dependent_expression_p (op)
16492                 || has_value_dependent_address (op));
16493       }
16494
16495     default:
16496       /* A constant expression is value-dependent if any subexpression is
16497          value-dependent.  */
16498       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
16499         {
16500         case tcc_reference:
16501         case tcc_unary:
16502           return (value_dependent_expression_p
16503                   (TREE_OPERAND (expression, 0)));
16504
16505         case tcc_comparison:
16506         case tcc_binary:
16507           return ((value_dependent_expression_p
16508                    (TREE_OPERAND (expression, 0)))
16509                   || (value_dependent_expression_p
16510                       (TREE_OPERAND (expression, 1))));
16511
16512         case tcc_expression:
16513         case tcc_vl_exp:
16514           {
16515             int i;
16516             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
16517               /* In some cases, some of the operands may be missing.
16518                  (For example, in the case of PREDECREMENT_EXPR, the
16519                  amount to increment by may be missing.)  That doesn't
16520                  make the expression dependent.  */
16521               if (TREE_OPERAND (expression, i)
16522                   && (value_dependent_expression_p
16523                       (TREE_OPERAND (expression, i))))
16524                 return true;
16525             return false;
16526           }
16527
16528         default:
16529           break;
16530         }
16531     }
16532
16533   /* The expression is not value-dependent.  */
16534   return false;
16535 }
16536
16537 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
16538    [temp.dep.expr].  */
16539
16540 bool
16541 type_dependent_expression_p (tree expression)
16542 {
16543   if (!processing_template_decl)
16544     return false;
16545
16546   if (expression == error_mark_node)
16547     return false;
16548
16549   /* An unresolved name is always dependent.  */
16550   if (TREE_CODE (expression) == IDENTIFIER_NODE
16551       || TREE_CODE (expression) == USING_DECL)
16552     return true;
16553
16554   /* Some expression forms are never type-dependent.  */
16555   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
16556       || TREE_CODE (expression) == SIZEOF_EXPR
16557       || TREE_CODE (expression) == ALIGNOF_EXPR
16558       || TREE_CODE (expression) == TRAIT_EXPR
16559       || TREE_CODE (expression) == TYPEID_EXPR
16560       || TREE_CODE (expression) == DELETE_EXPR
16561       || TREE_CODE (expression) == VEC_DELETE_EXPR
16562       || TREE_CODE (expression) == THROW_EXPR)
16563     return false;
16564
16565   /* The types of these expressions depends only on the type to which
16566      the cast occurs.  */
16567   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
16568       || TREE_CODE (expression) == STATIC_CAST_EXPR
16569       || TREE_CODE (expression) == CONST_CAST_EXPR
16570       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
16571       || TREE_CODE (expression) == CAST_EXPR)
16572     return dependent_type_p (TREE_TYPE (expression));
16573
16574   /* The types of these expressions depends only on the type created
16575      by the expression.  */
16576   if (TREE_CODE (expression) == NEW_EXPR
16577       || TREE_CODE (expression) == VEC_NEW_EXPR)
16578     {
16579       /* For NEW_EXPR tree nodes created inside a template, either
16580          the object type itself or a TREE_LIST may appear as the
16581          operand 1.  */
16582       tree type = TREE_OPERAND (expression, 1);
16583       if (TREE_CODE (type) == TREE_LIST)
16584         /* This is an array type.  We need to check array dimensions
16585            as well.  */
16586         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
16587                || value_dependent_expression_p
16588                     (TREE_OPERAND (TREE_VALUE (type), 1));
16589       else
16590         return dependent_type_p (type);
16591     }
16592
16593   if (TREE_CODE (expression) == SCOPE_REF
16594       && dependent_scope_ref_p (expression,
16595                                 type_dependent_expression_p))
16596     return true;
16597
16598   if (TREE_CODE (expression) == FUNCTION_DECL
16599       && DECL_LANG_SPECIFIC (expression)
16600       && DECL_TEMPLATE_INFO (expression)
16601       && (any_dependent_template_arguments_p
16602           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
16603     return true;
16604
16605   if (TREE_CODE (expression) == TEMPLATE_DECL
16606       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
16607     return false;
16608
16609   if (TREE_CODE (expression) == STMT_EXPR)
16610     expression = stmt_expr_value_expr (expression);
16611
16612   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
16613     {
16614       tree elt;
16615       unsigned i;
16616
16617       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
16618         {
16619           if (type_dependent_expression_p (elt))
16620             return true;
16621         }
16622       return false;
16623     }
16624
16625   if (TREE_TYPE (expression) == unknown_type_node)
16626     {
16627       if (TREE_CODE (expression) == ADDR_EXPR)
16628         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
16629       if (TREE_CODE (expression) == COMPONENT_REF
16630           || TREE_CODE (expression) == OFFSET_REF)
16631         {
16632           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
16633             return true;
16634           expression = TREE_OPERAND (expression, 1);
16635           if (TREE_CODE (expression) == IDENTIFIER_NODE)
16636             return false;
16637         }
16638       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
16639       if (TREE_CODE (expression) == SCOPE_REF)
16640         return false;
16641
16642       if (TREE_CODE (expression) == BASELINK)
16643         expression = BASELINK_FUNCTIONS (expression);
16644
16645       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
16646         {
16647           if (any_dependent_template_arguments_p
16648               (TREE_OPERAND (expression, 1)))
16649             return true;
16650           expression = TREE_OPERAND (expression, 0);
16651         }
16652       gcc_assert (TREE_CODE (expression) == OVERLOAD
16653                   || TREE_CODE (expression) == FUNCTION_DECL);
16654
16655       while (expression)
16656         {
16657           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16658             return true;
16659           expression = OVL_NEXT (expression);
16660         }
16661       return false;
16662     }
16663
16664   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16665
16666   return (dependent_type_p (TREE_TYPE (expression)));
16667 }
16668
16669 /* Like type_dependent_expression_p, but it also works while not processing
16670    a template definition, i.e. during substitution or mangling.  */
16671
16672 bool
16673 type_dependent_expression_p_push (tree expr)
16674 {
16675   bool b;
16676   ++processing_template_decl;
16677   b = type_dependent_expression_p (expr);
16678   --processing_template_decl;
16679   return b;
16680 }
16681
16682 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
16683    contains a type-dependent expression.  */
16684
16685 bool
16686 any_type_dependent_arguments_p (const_tree args)
16687 {
16688   while (args)
16689     {
16690       tree arg = TREE_VALUE (args);
16691
16692       if (type_dependent_expression_p (arg))
16693         return true;
16694       args = TREE_CHAIN (args);
16695     }
16696   return false;
16697 }
16698
16699 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16700    expressions) contains any value-dependent expressions.  */
16701
16702 bool
16703 any_value_dependent_elements_p (const_tree list)
16704 {
16705   for (; list; list = TREE_CHAIN (list))
16706     if (value_dependent_expression_p (TREE_VALUE (list)))
16707       return true;
16708
16709   return false;
16710 }
16711
16712 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16713
16714 bool
16715 dependent_template_arg_p (tree arg)
16716 {
16717   if (!processing_template_decl)
16718     return false;
16719
16720   if (TREE_CODE (arg) == TEMPLATE_DECL
16721       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16722     return dependent_template_p (arg);
16723   else if (ARGUMENT_PACK_P (arg))
16724     {
16725       tree args = ARGUMENT_PACK_ARGS (arg);
16726       int i, len = TREE_VEC_LENGTH (args);
16727       for (i = 0; i < len; ++i)
16728         {
16729           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16730             return true;
16731         }
16732
16733       return false;
16734     }
16735   else if (TYPE_P (arg))
16736     return dependent_type_p (arg);
16737   else
16738     return (type_dependent_expression_p (arg)
16739             || value_dependent_expression_p (arg));
16740 }
16741
16742 /* Returns true if ARGS (a collection of template arguments) contains
16743    any types that require structural equality testing.  */
16744
16745 bool
16746 any_template_arguments_need_structural_equality_p (tree args)
16747 {
16748   int i;
16749   int j;
16750
16751   if (!args)
16752     return false;
16753   if (args == error_mark_node)
16754     return true;
16755
16756   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16757     {
16758       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16759       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16760         {
16761           tree arg = TREE_VEC_ELT (level, j);
16762           tree packed_args = NULL_TREE;
16763           int k, len = 1;
16764
16765           if (ARGUMENT_PACK_P (arg))
16766             {
16767               /* Look inside the argument pack.  */
16768               packed_args = ARGUMENT_PACK_ARGS (arg);
16769               len = TREE_VEC_LENGTH (packed_args);
16770             }
16771
16772           for (k = 0; k < len; ++k)
16773             {
16774               if (packed_args)
16775                 arg = TREE_VEC_ELT (packed_args, k);
16776
16777               if (error_operand_p (arg))
16778                 return true;
16779               else if (TREE_CODE (arg) == TEMPLATE_DECL
16780                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16781                 continue;
16782               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
16783                 return true;
16784               else if (!TYPE_P (arg) && TREE_TYPE (arg)
16785                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
16786                 return true;
16787             }
16788         }
16789     }
16790
16791   return false;
16792 }
16793
16794 /* Returns true if ARGS (a collection of template arguments) contains
16795    any dependent arguments.  */
16796
16797 bool
16798 any_dependent_template_arguments_p (const_tree args)
16799 {
16800   int i;
16801   int j;
16802
16803   if (!args)
16804     return false;
16805   if (args == error_mark_node)
16806     return true;
16807
16808   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16809     {
16810       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16811       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16812         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16813           return true;
16814     }
16815
16816   return false;
16817 }
16818
16819 /* Returns TRUE if the template TMPL is dependent.  */
16820
16821 bool
16822 dependent_template_p (tree tmpl)
16823 {
16824   if (TREE_CODE (tmpl) == OVERLOAD)
16825     {
16826       while (tmpl)
16827         {
16828           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16829             return true;
16830           tmpl = OVL_CHAIN (tmpl);
16831         }
16832       return false;
16833     }
16834
16835   /* Template template parameters are dependent.  */
16836   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16837       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16838     return true;
16839   /* So are names that have not been looked up.  */
16840   if (TREE_CODE (tmpl) == SCOPE_REF
16841       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16842     return true;
16843   /* So are member templates of dependent classes.  */
16844   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16845     return dependent_type_p (DECL_CONTEXT (tmpl));
16846   return false;
16847 }
16848
16849 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16850
16851 bool
16852 dependent_template_id_p (tree tmpl, tree args)
16853 {
16854   return (dependent_template_p (tmpl)
16855           || any_dependent_template_arguments_p (args));
16856 }
16857
16858 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
16859    is dependent.  */
16860
16861 bool
16862 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
16863 {
16864   int i;
16865
16866   if (!processing_template_decl)
16867     return false;
16868
16869   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
16870     {
16871       tree decl = TREE_VEC_ELT (declv, i);
16872       tree init = TREE_VEC_ELT (initv, i);
16873       tree cond = TREE_VEC_ELT (condv, i);
16874       tree incr = TREE_VEC_ELT (incrv, i);
16875
16876       if (type_dependent_expression_p (decl))
16877         return true;
16878
16879       if (init && type_dependent_expression_p (init))
16880         return true;
16881
16882       if (type_dependent_expression_p (cond))
16883         return true;
16884
16885       if (COMPARISON_CLASS_P (cond)
16886           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
16887               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
16888         return true;
16889
16890       if (TREE_CODE (incr) == MODOP_EXPR)
16891         {
16892           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
16893               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
16894             return true;
16895         }
16896       else if (type_dependent_expression_p (incr))
16897         return true;
16898       else if (TREE_CODE (incr) == MODIFY_EXPR)
16899         {
16900           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
16901             return true;
16902           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
16903             {
16904               tree t = TREE_OPERAND (incr, 1);
16905               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
16906                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
16907                 return true;
16908             }
16909         }
16910     }
16911
16912   return false;
16913 }
16914
16915 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16916    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16917    no such TYPE can be found.  Note that this function peers inside
16918    uninstantiated templates and therefore should be used only in
16919    extremely limited situations.  ONLY_CURRENT_P restricts this
16920    peering to the currently open classes hierarchy (which is required
16921    when comparing types).  */
16922
16923 tree
16924 resolve_typename_type (tree type, bool only_current_p)
16925 {
16926   tree scope;
16927   tree name;
16928   tree decl;
16929   int quals;
16930   tree pushed_scope;
16931   tree result;
16932
16933   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16934
16935   scope = TYPE_CONTEXT (type);
16936   name = TYPE_IDENTIFIER (type);
16937
16938   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16939      it first before we can figure out what NAME refers to.  */
16940   if (TREE_CODE (scope) == TYPENAME_TYPE)
16941     scope = resolve_typename_type (scope, only_current_p);
16942   /* If we don't know what SCOPE refers to, then we cannot resolve the
16943      TYPENAME_TYPE.  */
16944   if (TREE_CODE (scope) == TYPENAME_TYPE)
16945     return type;
16946   /* If the SCOPE is a template type parameter, we have no way of
16947      resolving the name.  */
16948   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16949     return type;
16950   /* If the SCOPE is not the current instantiation, there's no reason
16951      to look inside it.  */
16952   if (only_current_p && !currently_open_class (scope))
16953     return type;
16954   /* If SCOPE isn't the template itself, it will not have a valid
16955      TYPE_FIELDS list.  */
16956   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16957     /* scope is either the template itself or a compatible instantiation
16958        like X<T>, so look up the name in the original template.  */
16959     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16960   else
16961     /* scope is a partial instantiation, so we can't do the lookup or we
16962        will lose the template arguments.  */
16963     return type;
16964   /* Enter the SCOPE so that name lookup will be resolved as if we
16965      were in the class definition.  In particular, SCOPE will no
16966      longer be considered a dependent type.  */
16967   pushed_scope = push_scope (scope);
16968   /* Look up the declaration.  */
16969   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16970
16971   result = NULL_TREE;
16972   
16973   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
16974      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
16975   if (!decl)
16976     /*nop*/;
16977   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
16978            && TREE_CODE (decl) == TYPE_DECL)
16979     {
16980       result = TREE_TYPE (decl);
16981       if (result == error_mark_node)
16982         result = NULL_TREE;
16983     }
16984   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
16985            && DECL_CLASS_TEMPLATE_P (decl))
16986     {
16987       tree tmpl;
16988       tree args;
16989       /* Obtain the template and the arguments.  */
16990       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
16991       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
16992       /* Instantiate the template.  */
16993       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
16994                                       /*entering_scope=*/0,
16995                                       tf_error | tf_user);
16996       if (result == error_mark_node)
16997         result = NULL_TREE;
16998     }
16999   
17000   /* Leave the SCOPE.  */
17001   if (pushed_scope)
17002     pop_scope (pushed_scope);
17003
17004   /* If we failed to resolve it, return the original typename.  */
17005   if (!result)
17006     return type;
17007   
17008   /* If lookup found a typename type, resolve that too.  */
17009   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
17010     {
17011       /* Ill-formed programs can cause infinite recursion here, so we
17012          must catch that.  */
17013       TYPENAME_IS_RESOLVING_P (type) = 1;
17014       result = resolve_typename_type (result, only_current_p);
17015       TYPENAME_IS_RESOLVING_P (type) = 0;
17016     }
17017   
17018   /* Qualify the resulting type.  */
17019   quals = cp_type_quals (type);
17020   if (quals)
17021     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
17022
17023   return result;
17024 }
17025
17026 /* EXPR is an expression which is not type-dependent.  Return a proxy
17027    for EXPR that can be used to compute the types of larger
17028    expressions containing EXPR.  */
17029
17030 tree
17031 build_non_dependent_expr (tree expr)
17032 {
17033   tree inner_expr;
17034
17035   /* Preserve null pointer constants so that the type of things like
17036      "p == 0" where "p" is a pointer can be determined.  */
17037   if (null_ptr_cst_p (expr))
17038     return expr;
17039   /* Preserve OVERLOADs; the functions must be available to resolve
17040      types.  */
17041   inner_expr = expr;
17042   if (TREE_CODE (inner_expr) == STMT_EXPR)
17043     inner_expr = stmt_expr_value_expr (inner_expr);
17044   if (TREE_CODE (inner_expr) == ADDR_EXPR)
17045     inner_expr = TREE_OPERAND (inner_expr, 0);
17046   if (TREE_CODE (inner_expr) == COMPONENT_REF)
17047     inner_expr = TREE_OPERAND (inner_expr, 1);
17048   if (is_overloaded_fn (inner_expr)
17049       || TREE_CODE (inner_expr) == OFFSET_REF)
17050     return expr;
17051   /* There is no need to return a proxy for a variable.  */
17052   if (TREE_CODE (expr) == VAR_DECL)
17053     return expr;
17054   /* Preserve string constants; conversions from string constants to
17055      "char *" are allowed, even though normally a "const char *"
17056      cannot be used to initialize a "char *".  */
17057   if (TREE_CODE (expr) == STRING_CST)
17058     return expr;
17059   /* Preserve arithmetic constants, as an optimization -- there is no
17060      reason to create a new node.  */
17061   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
17062     return expr;
17063   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
17064      There is at least one place where we want to know that a
17065      particular expression is a throw-expression: when checking a ?:
17066      expression, there are special rules if the second or third
17067      argument is a throw-expression.  */
17068   if (TREE_CODE (expr) == THROW_EXPR)
17069     return expr;
17070
17071   if (TREE_CODE (expr) == COND_EXPR)
17072     return build3 (COND_EXPR,
17073                    TREE_TYPE (expr),
17074                    TREE_OPERAND (expr, 0),
17075                    (TREE_OPERAND (expr, 1)
17076                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
17077                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
17078                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
17079   if (TREE_CODE (expr) == COMPOUND_EXPR
17080       && !COMPOUND_EXPR_OVERLOADED (expr))
17081     return build2 (COMPOUND_EXPR,
17082                    TREE_TYPE (expr),
17083                    TREE_OPERAND (expr, 0),
17084                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17085
17086   /* If the type is unknown, it can't really be non-dependent */
17087   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17088
17089   /* Otherwise, build a NON_DEPENDENT_EXPR.
17090
17091      REFERENCE_TYPEs are not stripped for expressions in templates
17092      because doing so would play havoc with mangling.  Consider, for
17093      example:
17094
17095        template <typename T> void f<T& g>() { g(); }
17096
17097      In the body of "f", the expression for "g" will have
17098      REFERENCE_TYPE, even though the standard says that it should
17099      not.  The reason is that we must preserve the syntactic form of
17100      the expression so that mangling (say) "f<g>" inside the body of
17101      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17102      stripped here.  */
17103   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17104 }
17105
17106 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
17107    Return a new TREE_LIST with the various arguments replaced with
17108    equivalent non-dependent expressions.  */
17109
17110 tree
17111 build_non_dependent_args (tree args)
17112 {
17113   tree a;
17114   tree new_args;
17115
17116   new_args = NULL_TREE;
17117   for (a = args; a; a = TREE_CHAIN (a))
17118     new_args = tree_cons (NULL_TREE,
17119                           build_non_dependent_expr (TREE_VALUE (a)),
17120                           new_args);
17121   return nreverse (new_args);
17122 }
17123
17124 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17125    with a level one deeper than the actual template parms.  */
17126
17127 tree
17128 make_auto (void)
17129 {
17130   tree au;
17131
17132   /* ??? Is it worth caching this for multiple autos at the same level?  */
17133   au = cxx_make_type (TEMPLATE_TYPE_PARM);
17134   TYPE_NAME (au) = build_decl (TYPE_DECL, get_identifier ("auto"), au);
17135   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17136   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17137     (0, processing_template_decl + 1, processing_template_decl + 1,
17138      TYPE_NAME (au), NULL_TREE);
17139   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17140   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17141   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17142
17143   return au;
17144 }
17145
17146 /* Given type ARG, return std::initializer_list<ARG>.  */
17147
17148 static tree
17149 listify (tree arg)
17150 {
17151   tree std_init_list = namespace_binding
17152     (get_identifier ("initializer_list"), std_node);
17153   tree argvec;
17154   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17155     {    
17156       error ("deducing from brace-enclosed initializer list requires "
17157              "#include <initializer_list>");
17158       return error_mark_node;
17159     }
17160   argvec = make_tree_vec (1);
17161   TREE_VEC_ELT (argvec, 0) = arg;
17162   return lookup_template_class (std_init_list, argvec, NULL_TREE,
17163                                 NULL_TREE, 0, tf_warning_or_error);
17164 }
17165
17166 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17167
17168 static tree
17169 listify_autos (tree type, tree auto_node)
17170 {
17171   tree init_auto = listify (auto_node);
17172   tree argvec = make_tree_vec (1);
17173   TREE_VEC_ELT (argvec, 0) = init_auto;
17174   if (processing_template_decl)
17175     argvec = add_to_template_args (current_template_args (), argvec);
17176   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17177 }
17178
17179 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
17180    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
17181
17182 tree
17183 do_auto_deduction (tree type, tree init, tree auto_node)
17184 {
17185   tree parms, args, tparms, targs;
17186   int val;
17187
17188   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
17189      with either a new invented type template parameter U or, if the
17190      initializer is a braced-init-list (8.5.4), with
17191      std::initializer_list<U>.  */
17192   if (BRACE_ENCLOSED_INITIALIZER_P (init))
17193     type = listify_autos (type, auto_node);
17194
17195   parms = build_tree_list (NULL_TREE, type);
17196   args = build_tree_list (NULL_TREE, init);
17197   tparms = make_tree_vec (1);
17198   targs = make_tree_vec (1);
17199   TREE_VEC_ELT (tparms, 0)
17200     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
17201   val = type_unification_real (tparms, targs, parms, args, 0,
17202                                DEDUCE_CALL, LOOKUP_NORMAL);
17203   if (val > 0)
17204     {
17205       error ("unable to deduce %qT from %qE", type, init);
17206       return error_mark_node;
17207     }
17208
17209   if (processing_template_decl)
17210     targs = add_to_template_args (current_template_args (), targs);
17211   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
17212 }
17213
17214 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
17215    result.  */
17216
17217 tree
17218 splice_late_return_type (tree type, tree late_return_type)
17219 {
17220   tree argvec;
17221
17222   if (late_return_type == NULL_TREE)
17223     return type;
17224   argvec = make_tree_vec (1);
17225   TREE_VEC_ELT (argvec, 0) = late_return_type;
17226   if (processing_template_decl)
17227     argvec = add_to_template_args (current_template_args (), argvec);
17228   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17229 }
17230
17231 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
17232
17233 bool
17234 is_auto (const_tree type)
17235 {
17236   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17237       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
17238     return true;
17239   else
17240     return false;
17241 }
17242
17243 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
17244    appear as a type-specifier for the declaration in question, we don't
17245    have to look through the whole type.  */
17246
17247 tree
17248 type_uses_auto (tree type)
17249 {
17250   enum tree_code code;
17251   if (is_auto (type))
17252     return type;
17253
17254   code = TREE_CODE (type);
17255
17256   if (code == POINTER_TYPE || code == REFERENCE_TYPE
17257       || code == OFFSET_TYPE || code == FUNCTION_TYPE
17258       || code == METHOD_TYPE || code == ARRAY_TYPE)
17259     return type_uses_auto (TREE_TYPE (type));
17260
17261   if (TYPE_PTRMEMFUNC_P (type))
17262     return type_uses_auto (TREE_TYPE (TREE_TYPE
17263                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
17264
17265   return NULL_TREE;
17266 }
17267
17268 #include "gt-cp-pt.h"