OSDN Git Service

PR c++/35986
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007, 2008  Free Software Foundation, Inc.
4    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
5    Rewritten by Jason Merrill (jason@cygnus.com).
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 /* Known bugs or deficiencies include:
24
25      all methods must be provided in header files; can't use a source
26      file that contains only the method templates and "just win".  */
27
28 #include "config.h"
29 #include "system.h"
30 #include "coretypes.h"
31 #include "tm.h"
32 #include "obstack.h"
33 #include "tree.h"
34 #include "pointer-set.h"
35 #include "flags.h"
36 #include "c-common.h"
37 #include "cp-tree.h"
38 #include "cp-objcp-common.h"
39 #include "tree-inline.h"
40 #include "decl.h"
41 #include "output.h"
42 #include "except.h"
43 #include "toplev.h"
44 #include "rtl.h"
45 #include "timevar.h"
46 #include "tree-iterator.h"
47 #include "vecprim.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
54    instantiations have been deferred, either because their definitions
55    were not yet available, or because we were putting off doing the work.  */
56 struct pending_template GTY (()) {
57   struct pending_template *next;
58   struct tinst_level *tinst;
59 };
60
61 static GTY(()) struct pending_template *pending_templates;
62 static GTY(()) struct pending_template *last_pending_template;
63
64 int processing_template_parmlist;
65 static int template_header_count;
66
67 static GTY(()) tree saved_trees;
68 static VEC(int,heap) *inline_parm_levels;
69
70 static GTY(()) struct tinst_level *current_tinst_level;
71
72 static GTY(()) tree saved_access_scope;
73
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78
79 /* A map from local variable declarations in the body of the template
80    presently being instantiated to the corresponding instantiated
81    local variables.  */
82 static htab_t local_specializations;
83
84 /* Contains canonical template parameter types. The vector is indexed by
85    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
86    TREE_LIST, whose TREE_VALUEs contain the canonical template
87    parameters of various types and levels.  */
88 static GTY(()) VEC(tree,gc) *canonical_template_parms;
89
90 #define UNIFY_ALLOW_NONE 0
91 #define UNIFY_ALLOW_MORE_CV_QUAL 1
92 #define UNIFY_ALLOW_LESS_CV_QUAL 2
93 #define UNIFY_ALLOW_DERIVED 4
94 #define UNIFY_ALLOW_INTEGER 8
95 #define UNIFY_ALLOW_OUTER_LEVEL 16
96 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
97 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
98
99 static void push_access_scope (tree);
100 static void pop_access_scope (tree);
101 static bool resolve_overloaded_unification (tree, tree, tree, tree,
102                                             unification_kind_t, int);
103 static int try_one_overload (tree, tree, tree, tree, tree,
104                              unification_kind_t, int, bool);
105 static int unify (tree, tree, tree, tree, int);
106 static void add_pending_template (tree);
107 static int push_tinst_level (tree);
108 static void pop_tinst_level (void);
109 static tree reopen_tinst_level (struct tinst_level *);
110 static tree tsubst_initializer_list (tree, tree);
111 static tree get_class_bindings (tree, tree, tree);
112 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
113                                    bool, bool);
114 static void tsubst_enum (tree, tree, tree);
115 static tree add_to_template_args (tree, tree);
116 static tree add_outermost_template_args (tree, tree);
117 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
118 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
119                                              tree);
120 static int  type_unification_real (tree, tree, tree, tree,
121                                    int, unification_kind_t, int);
122 static void note_template_header (int);
123 static tree convert_nontype_argument_function (tree, tree);
124 static tree convert_nontype_argument (tree, tree);
125 static tree convert_template_argument (tree, tree, tree,
126                                        tsubst_flags_t, int, tree);
127 static int for_each_template_parm (tree, tree_fn_t, void*,
128                                    struct pointer_set_t*, bool);
129 static tree expand_template_argument_pack (tree);
130 static tree build_template_parm_index (int, int, int, tree, tree);
131 static bool inline_needs_template_parms (tree);
132 static void push_inline_template_parms_recursive (tree, int);
133 static tree retrieve_local_specialization (tree);
134 static void register_local_specialization (tree, tree);
135 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
136 static int mark_template_parm (tree, void *);
137 static int template_parm_this_level_p (tree, void *);
138 static tree tsubst_friend_function (tree, tree);
139 static tree tsubst_friend_class (tree, tree);
140 static int can_complete_type_without_circularity (tree);
141 static tree get_bindings (tree, tree, tree, bool);
142 static int template_decl_level (tree);
143 static int check_cv_quals_for_unify (int, tree, tree);
144 static void template_parm_level_and_index (tree, int*, int*);
145 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
146 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
147 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
148 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
149 static void regenerate_decl_from_template (tree, tree);
150 static tree most_specialized_class (tree, tree);
151 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
152 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
153 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
154 static bool check_specialization_scope (void);
155 static tree process_partial_specialization (tree);
156 static void set_current_access_from_decl (tree);
157 static tree get_template_base (tree, tree, tree, tree);
158 static tree try_class_unification (tree, tree, tree, tree);
159 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
160                                            tree, tree);
161 static bool template_template_parm_bindings_ok_p (tree, tree);
162 static int template_args_equal (tree, tree);
163 static void tsubst_default_arguments (tree);
164 static tree for_each_template_parm_r (tree *, int *, void *);
165 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
166 static void copy_default_args_to_explicit_spec (tree);
167 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
168 static int eq_local_specializations (const void *, const void *);
169 static bool dependent_template_arg_p (tree);
170 static bool any_template_arguments_need_structural_equality_p (tree);
171 static bool dependent_type_p_r (tree);
172 static tree tsubst (tree, tree, tsubst_flags_t, tree);
173 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
174 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
175 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
176
177 /* Make the current scope suitable for access checking when we are
178    processing T.  T can be FUNCTION_DECL for instantiated function
179    template, or VAR_DECL for static member variable (need by
180    instantiate_decl).  */
181
182 static void
183 push_access_scope (tree t)
184 {
185   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
186               || TREE_CODE (t) == VAR_DECL);
187
188   if (DECL_FRIEND_CONTEXT (t))
189     push_nested_class (DECL_FRIEND_CONTEXT (t));
190   else if (DECL_CLASS_SCOPE_P (t))
191     push_nested_class (DECL_CONTEXT (t));
192   else
193     push_to_top_level ();
194
195   if (TREE_CODE (t) == FUNCTION_DECL)
196     {
197       saved_access_scope = tree_cons
198         (NULL_TREE, current_function_decl, saved_access_scope);
199       current_function_decl = t;
200     }
201 }
202
203 /* Restore the scope set up by push_access_scope.  T is the node we
204    are processing.  */
205
206 static void
207 pop_access_scope (tree t)
208 {
209   if (TREE_CODE (t) == FUNCTION_DECL)
210     {
211       current_function_decl = TREE_VALUE (saved_access_scope);
212       saved_access_scope = TREE_CHAIN (saved_access_scope);
213     }
214
215   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
216     pop_nested_class ();
217   else
218     pop_from_top_level ();
219 }
220
221 /* Do any processing required when DECL (a member template
222    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
223    to DECL, unless it is a specialization, in which case the DECL
224    itself is returned.  */
225
226 tree
227 finish_member_template_decl (tree decl)
228 {
229   if (decl == error_mark_node)
230     return error_mark_node;
231
232   gcc_assert (DECL_P (decl));
233
234   if (TREE_CODE (decl) == TYPE_DECL)
235     {
236       tree type;
237
238       type = TREE_TYPE (decl);
239       if (type == error_mark_node)
240         return error_mark_node;
241       if (MAYBE_CLASS_TYPE_P (type)
242           && CLASSTYPE_TEMPLATE_INFO (type)
243           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
244         {
245           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
246           check_member_template (tmpl);
247           return tmpl;
248         }
249       return NULL_TREE;
250     }
251   else if (TREE_CODE (decl) == FIELD_DECL)
252     error ("data member %qD cannot be a member template", decl);
253   else if (DECL_TEMPLATE_INFO (decl))
254     {
255       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
256         {
257           check_member_template (DECL_TI_TEMPLATE (decl));
258           return DECL_TI_TEMPLATE (decl);
259         }
260       else
261         return decl;
262     }
263   else
264     error ("invalid member template declaration %qD", decl);
265
266   return error_mark_node;
267 }
268
269 /* Return the template info node corresponding to T, whatever T is.  */
270
271 tree
272 get_template_info (tree t)
273 {
274   tree tinfo = NULL_TREE;
275
276   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
277     tinfo = DECL_TEMPLATE_INFO (t);
278
279   if (!tinfo && TREE_CODE (t) == TYPE_DECL)
280     t = TREE_TYPE (t);
281
282   if (TAGGED_TYPE_P (t))
283     tinfo = TYPE_TEMPLATE_INFO (t);
284
285   return tinfo;
286 }
287
288 /* Returns the template nesting level of the indicated class TYPE.
289
290    For example, in:
291      template <class T>
292      struct A
293      {
294        template <class U>
295        struct B {};
296      };
297
298    A<T>::B<U> has depth two, while A<T> has depth one.
299    Both A<T>::B<int> and A<int>::B<U> have depth one, if
300    they are instantiations, not specializations.
301
302    This function is guaranteed to return 0 if passed NULL_TREE so
303    that, for example, `template_class_depth (current_class_type)' is
304    always safe.  */
305
306 int
307 template_class_depth (tree type)
308 {
309   int depth;
310
311   for (depth = 0;
312        type && TREE_CODE (type) != NAMESPACE_DECL;
313        type = (TREE_CODE (type) == FUNCTION_DECL)
314          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
315     {
316       tree tinfo = get_template_info (type);
317
318       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
319           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
320         ++depth;
321     }
322
323   return depth;
324 }
325
326 /* Subroutine of maybe_begin_member_template_processing.
327    Returns true if processing DECL needs us to push template parms.  */
328
329 static bool
330 inline_needs_template_parms (tree decl)
331 {
332   if (! DECL_TEMPLATE_INFO (decl))
333     return false;
334
335   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
336           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
337 }
338
339 /* Subroutine of maybe_begin_member_template_processing.
340    Push the template parms in PARMS, starting from LEVELS steps into the
341    chain, and ending at the beginning, since template parms are listed
342    innermost first.  */
343
344 static void
345 push_inline_template_parms_recursive (tree parmlist, int levels)
346 {
347   tree parms = TREE_VALUE (parmlist);
348   int i;
349
350   if (levels > 1)
351     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
352
353   ++processing_template_decl;
354   current_template_parms
355     = tree_cons (size_int (processing_template_decl),
356                  parms, current_template_parms);
357   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
358
359   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
360                NULL);
361   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
362     {
363       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
364
365       if (parm == error_mark_node)
366         continue;
367
368       gcc_assert (DECL_P (parm));
369
370       switch (TREE_CODE (parm))
371         {
372         case TYPE_DECL:
373         case TEMPLATE_DECL:
374           pushdecl (parm);
375           break;
376
377         case PARM_DECL:
378           {
379             /* Make a CONST_DECL as is done in process_template_parm.
380                It is ugly that we recreate this here; the original
381                version built in process_template_parm is no longer
382                available.  */
383             tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
384                                     TREE_TYPE (parm));
385             DECL_ARTIFICIAL (decl) = 1;
386             TREE_CONSTANT (decl) = 1;
387             TREE_READONLY (decl) = 1;
388             DECL_INITIAL (decl) = DECL_INITIAL (parm);
389             SET_DECL_TEMPLATE_PARM_P (decl);
390             pushdecl (decl);
391           }
392           break;
393
394         default:
395           gcc_unreachable ();
396         }
397     }
398 }
399
400 /* Restore the template parameter context for a member template or
401    a friend template defined in a class definition.  */
402
403 void
404 maybe_begin_member_template_processing (tree decl)
405 {
406   tree parms;
407   int levels = 0;
408
409   if (inline_needs_template_parms (decl))
410     {
411       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
412       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
413
414       if (DECL_TEMPLATE_SPECIALIZATION (decl))
415         {
416           --levels;
417           parms = TREE_CHAIN (parms);
418         }
419
420       push_inline_template_parms_recursive (parms, levels);
421     }
422
423   /* Remember how many levels of template parameters we pushed so that
424      we can pop them later.  */
425   VEC_safe_push (int, heap, inline_parm_levels, levels);
426 }
427
428 /* Undo the effects of maybe_begin_member_template_processing.  */
429
430 void
431 maybe_end_member_template_processing (void)
432 {
433   int i;
434   int last;
435
436   if (VEC_length (int, inline_parm_levels) == 0)
437     return;
438
439   last = VEC_pop (int, inline_parm_levels);
440   for (i = 0; i < last; ++i)
441     {
442       --processing_template_decl;
443       current_template_parms = TREE_CHAIN (current_template_parms);
444       poplevel (0, 0, 0);
445     }
446 }
447
448 /* Return a new template argument vector which contains all of ARGS,
449    but has as its innermost set of arguments the EXTRA_ARGS.  */
450
451 static tree
452 add_to_template_args (tree args, tree extra_args)
453 {
454   tree new_args;
455   int extra_depth;
456   int i;
457   int j;
458
459   extra_depth = TMPL_ARGS_DEPTH (extra_args);
460   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
461
462   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
463     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
464
465   for (j = 1; j <= extra_depth; ++j, ++i)
466     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
467
468   return new_args;
469 }
470
471 /* Like add_to_template_args, but only the outermost ARGS are added to
472    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
473    (EXTRA_ARGS) levels are added.  This function is used to combine
474    the template arguments from a partial instantiation with the
475    template arguments used to attain the full instantiation from the
476    partial instantiation.  */
477
478 static tree
479 add_outermost_template_args (tree args, tree extra_args)
480 {
481   tree new_args;
482
483   /* If there are more levels of EXTRA_ARGS than there are ARGS,
484      something very fishy is going on.  */
485   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
486
487   /* If *all* the new arguments will be the EXTRA_ARGS, just return
488      them.  */
489   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
490     return extra_args;
491
492   /* For the moment, we make ARGS look like it contains fewer levels.  */
493   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
494
495   new_args = add_to_template_args (args, extra_args);
496
497   /* Now, we restore ARGS to its full dimensions.  */
498   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
499
500   return new_args;
501 }
502
503 /* Return the N levels of innermost template arguments from the ARGS.  */
504
505 tree
506 get_innermost_template_args (tree args, int n)
507 {
508   tree new_args;
509   int extra_levels;
510   int i;
511
512   gcc_assert (n >= 0);
513
514   /* If N is 1, just return the innermost set of template arguments.  */
515   if (n == 1)
516     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
517
518   /* If we're not removing anything, just return the arguments we were
519      given.  */
520   extra_levels = TMPL_ARGS_DEPTH (args) - n;
521   gcc_assert (extra_levels >= 0);
522   if (extra_levels == 0)
523     return args;
524
525   /* Make a new set of arguments, not containing the outer arguments.  */
526   new_args = make_tree_vec (n);
527   for (i = 1; i <= n; ++i)
528     SET_TMPL_ARGS_LEVEL (new_args, i,
529                          TMPL_ARGS_LEVEL (args, i + extra_levels));
530
531   return new_args;
532 }
533
534 /* The inverse of get_innermost_template_args: Return all but the innermost
535    EXTRA_LEVELS levels of template arguments from the ARGS.  */
536
537 static tree
538 strip_innermost_template_args (tree args, int extra_levels)
539 {
540   tree new_args;
541   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
542   int i;
543
544   gcc_assert (n >= 0);
545
546   /* If N is 1, just return the outermost set of template arguments.  */
547   if (n == 1)
548     return TMPL_ARGS_LEVEL (args, 1);
549
550   /* If we're not removing anything, just return the arguments we were
551      given.  */
552   gcc_assert (extra_levels >= 0);
553   if (extra_levels == 0)
554     return args;
555
556   /* Make a new set of arguments, not containing the inner arguments.  */
557   new_args = make_tree_vec (n);
558   for (i = 1; i <= n; ++i)
559     SET_TMPL_ARGS_LEVEL (new_args, i,
560                          TMPL_ARGS_LEVEL (args, i));
561
562   return new_args;
563 }
564
565 /* We've got a template header coming up; push to a new level for storing
566    the parms.  */
567
568 void
569 begin_template_parm_list (void)
570 {
571   /* We use a non-tag-transparent scope here, which causes pushtag to
572      put tags in this scope, rather than in the enclosing class or
573      namespace scope.  This is the right thing, since we want
574      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
575      global template class, push_template_decl handles putting the
576      TEMPLATE_DECL into top-level scope.  For a nested template class,
577      e.g.:
578
579        template <class T> struct S1 {
580          template <class T> struct S2 {};
581        };
582
583      pushtag contains special code to call pushdecl_with_scope on the
584      TEMPLATE_DECL for S2.  */
585   begin_scope (sk_template_parms, NULL);
586   ++processing_template_decl;
587   ++processing_template_parmlist;
588   note_template_header (0);
589 }
590
591 /* This routine is called when a specialization is declared.  If it is
592    invalid to declare a specialization here, an error is reported and
593    false is returned, otherwise this routine will return true.  */
594
595 static bool
596 check_specialization_scope (void)
597 {
598   tree scope = current_scope ();
599
600   /* [temp.expl.spec]
601
602      An explicit specialization shall be declared in the namespace of
603      which the template is a member, or, for member templates, in the
604      namespace of which the enclosing class or enclosing class
605      template is a member.  An explicit specialization of a member
606      function, member class or static data member of a class template
607      shall be declared in the namespace of which the class template
608      is a member.  */
609   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
610     {
611       error ("explicit specialization in non-namespace scope %qD", scope);
612       return false;
613     }
614
615   /* [temp.expl.spec]
616
617      In an explicit specialization declaration for a member of a class
618      template or a member template that appears in namespace scope,
619      the member template and some of its enclosing class templates may
620      remain unspecialized, except that the declaration shall not
621      explicitly specialize a class member template if its enclosing
622      class templates are not explicitly specialized as well.  */
623   if (current_template_parms)
624     {
625       error ("enclosing class templates are not explicitly specialized");
626       return false;
627     }
628
629   return true;
630 }
631
632 /* We've just seen template <>.  */
633
634 bool
635 begin_specialization (void)
636 {
637   begin_scope (sk_template_spec, NULL);
638   note_template_header (1);
639   return check_specialization_scope ();
640 }
641
642 /* Called at then end of processing a declaration preceded by
643    template<>.  */
644
645 void
646 end_specialization (void)
647 {
648   finish_scope ();
649   reset_specialization ();
650 }
651
652 /* Any template <>'s that we have seen thus far are not referring to a
653    function specialization.  */
654
655 void
656 reset_specialization (void)
657 {
658   processing_specialization = 0;
659   template_header_count = 0;
660 }
661
662 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
663    it was of the form template <>.  */
664
665 static void
666 note_template_header (int specialization)
667 {
668   processing_specialization = specialization;
669   template_header_count++;
670 }
671
672 /* We're beginning an explicit instantiation.  */
673
674 void
675 begin_explicit_instantiation (void)
676 {
677   gcc_assert (!processing_explicit_instantiation);
678   processing_explicit_instantiation = true;
679 }
680
681
682 void
683 end_explicit_instantiation (void)
684 {
685   gcc_assert (processing_explicit_instantiation);
686   processing_explicit_instantiation = false;
687 }
688
689 /* An explicit specialization or partial specialization TMPL is being
690    declared.  Check that the namespace in which the specialization is
691    occurring is permissible.  Returns false iff it is invalid to
692    specialize TMPL in the current namespace.  */
693
694 static bool
695 check_specialization_namespace (tree tmpl)
696 {
697   tree tpl_ns = decl_namespace_context (tmpl);
698
699   /* [tmpl.expl.spec]
700
701      An explicit specialization shall be declared in the namespace of
702      which the template is a member, or, for member templates, in the
703      namespace of which the enclosing class or enclosing class
704      template is a member.  An explicit specialization of a member
705      function, member class or static data member of a class template
706      shall be declared in the namespace of which the class template is
707      a member.  */
708   if (is_associated_namespace (current_namespace, tpl_ns))
709     /* Same or super-using namespace.  */
710     return true;
711   else
712     {
713       pedwarn ("specialization of %qD in different namespace", tmpl);
714       pedwarn ("  from definition of %q+#D", tmpl);
715       return false;
716     }
717 }
718
719 /* SPEC is an explicit instantiation.  Check that it is valid to
720    perform this explicit instantiation in the current namespace.  */
721
722 static void
723 check_explicit_instantiation_namespace (tree spec)
724 {
725   tree ns;
726
727   /* DR 275: An explicit instantiation shall appear in an enclosing
728      namespace of its template.  */
729   ns = decl_namespace_context (spec);
730   if (!is_ancestor (current_namespace, ns))
731     pedwarn ("explicit instantiation of %qD in namespace %qD "
732              "(which does not enclose namespace %qD)",
733              spec, current_namespace, ns);
734 }
735
736 /* The TYPE is being declared.  If it is a template type, that means it
737    is a partial specialization.  Do appropriate error-checking.  */
738
739 tree
740 maybe_process_partial_specialization (tree type)
741 {
742   tree context;
743
744   if (type == error_mark_node)
745     return error_mark_node;
746
747   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
748     {
749       error ("name of class shadows template template parameter %qD",
750              TYPE_NAME (type));
751       return error_mark_node;
752     }
753
754   context = TYPE_CONTEXT (type);
755
756   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
757     {
758       /* This is for ordinary explicit specialization and partial
759          specialization of a template class such as:
760
761            template <> class C<int>;
762
763          or:
764
765            template <class T> class C<T*>;
766
767          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
768
769       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
770           && !COMPLETE_TYPE_P (type))
771         {
772           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
773           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
774           if (processing_template_decl)
775             push_template_decl (TYPE_MAIN_DECL (type));
776         }
777       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
778         error ("specialization of %qT after instantiation", type);
779     }
780   else if (CLASS_TYPE_P (type)
781            && !CLASSTYPE_USE_TEMPLATE (type)
782            && CLASSTYPE_TEMPLATE_INFO (type)
783            && context && CLASS_TYPE_P (context)
784            && CLASSTYPE_TEMPLATE_INFO (context))
785     {
786       /* This is for an explicit specialization of member class
787          template according to [temp.expl.spec/18]:
788
789            template <> template <class U> class C<int>::D;
790
791          The context `C<int>' must be an implicit instantiation.
792          Otherwise this is just a member class template declared
793          earlier like:
794
795            template <> class C<int> { template <class U> class D; };
796            template <> template <class U> class C<int>::D;
797
798          In the first case, `C<int>::D' is a specialization of `C<T>::D'
799          while in the second case, `C<int>::D' is a primary template
800          and `C<T>::D' may not exist.  */
801
802       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
803           && !COMPLETE_TYPE_P (type))
804         {
805           tree t;
806
807           if (current_namespace
808               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
809             {
810               pedwarn ("specializing %q#T in different namespace", type);
811               pedwarn ("  from definition of %q+#D",
812                        CLASSTYPE_TI_TEMPLATE (type));
813             }
814
815           /* Check for invalid specialization after instantiation:
816
817                template <> template <> class C<int>::D<int>;
818                template <> template <class U> class C<int>::D;  */
819
820           for (t = DECL_TEMPLATE_INSTANTIATIONS
821                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
822                t; t = TREE_CHAIN (t))
823             if (TREE_VALUE (t) != type
824                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
825               error ("specialization %qT after instantiation %qT",
826                      type, TREE_VALUE (t));
827
828           /* Mark TYPE as a specialization.  And as a result, we only
829              have one level of template argument for the innermost
830              class template.  */
831           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
832           CLASSTYPE_TI_ARGS (type)
833             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
834         }
835     }
836   else if (processing_specialization)
837     {
838       error ("explicit specialization of non-template %qT", type);
839       return error_mark_node;
840     }
841
842   return type;
843 }
844
845 /* Returns nonzero if we can optimize the retrieval of specializations
846    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
847    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
848
849 static inline bool
850 optimize_specialization_lookup_p (tree tmpl)
851 {
852   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
853           && DECL_CLASS_SCOPE_P (tmpl)
854           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
855              parameter.  */
856           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
857           /* The optimized lookup depends on the fact that the
858              template arguments for the member function template apply
859              purely to the containing class, which is not true if the
860              containing class is an explicit or partial
861              specialization.  */
862           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
863           && !DECL_MEMBER_TEMPLATE_P (tmpl)
864           && !DECL_CONV_FN_P (tmpl)
865           /* It is possible to have a template that is not a member
866              template and is not a member of a template class:
867
868              template <typename T>
869              struct S { friend A::f(); };
870
871              Here, the friend function is a template, but the context does
872              not have template information.  The optimized lookup relies
873              on having ARGS be the template arguments for both the class
874              and the function template.  */
875           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
876 }
877
878 /* Retrieve the specialization (in the sense of [temp.spec] - a
879    specialization is either an instantiation or an explicit
880    specialization) of TMPL for the given template ARGS.  If there is
881    no such specialization, return NULL_TREE.  The ARGS are a vector of
882    arguments, or a vector of vectors of arguments, in the case of
883    templates with more than one level of parameters.
884
885    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
886    then we search for a partial specialization matching ARGS.  This
887    parameter is ignored if TMPL is not a class template.  */
888
889 static tree
890 retrieve_specialization (tree tmpl, tree args,
891                          bool class_specializations_p)
892 {
893   if (args == error_mark_node)
894     return NULL_TREE;
895
896   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
897
898   /* There should be as many levels of arguments as there are
899      levels of parameters.  */
900   gcc_assert (TMPL_ARGS_DEPTH (args)
901               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
902
903   if (optimize_specialization_lookup_p (tmpl))
904     {
905       tree class_template;
906       tree class_specialization;
907       VEC(tree,gc) *methods;
908       tree fns;
909       int idx;
910
911       /* The template arguments actually apply to the containing
912          class.  Find the class specialization with those
913          arguments.  */
914       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
915       class_specialization
916         = retrieve_specialization (class_template, args,
917                                    /*class_specializations_p=*/false);
918       if (!class_specialization)
919         return NULL_TREE;
920       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
921          for the specialization.  */
922       idx = class_method_index_for_fn (class_specialization, tmpl);
923       if (idx == -1)
924         return NULL_TREE;
925       /* Iterate through the methods with the indicated name, looking
926          for the one that has an instance of TMPL.  */
927       methods = CLASSTYPE_METHOD_VEC (class_specialization);
928       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
929         {
930           tree fn = OVL_CURRENT (fns);
931           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
932             return fn;
933         }
934       return NULL_TREE;
935     }
936   else
937     {
938       tree *sp;
939       tree *head;
940
941       /* Class templates store their instantiations on the
942          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
943          DECL_TEMPLATE_SPECIALIZATIONS list.  */
944       if (!class_specializations_p
945           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL
946           && TAGGED_TYPE_P (TREE_TYPE (tmpl)))
947         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
948       else
949         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
950       head = sp;
951       /* Iterate through the list until we find a matching template.  */
952       while (*sp != NULL_TREE)
953         {
954           tree spec = *sp;
955
956           if (comp_template_args (TREE_PURPOSE (spec), args))
957             {
958               /* Use the move-to-front heuristic to speed up future
959                  searches.  */
960               if (spec != *head)
961                 {
962                   *sp = TREE_CHAIN (*sp);
963                   TREE_CHAIN (spec) = *head;
964                   *head = spec;
965                 }
966               return TREE_VALUE (spec);
967             }
968           sp = &TREE_CHAIN (spec);
969         }
970     }
971
972   return NULL_TREE;
973 }
974
975 /* Like retrieve_specialization, but for local declarations.  */
976
977 static tree
978 retrieve_local_specialization (tree tmpl)
979 {
980   tree spec;
981
982   if (local_specializations == NULL)
983     return NULL_TREE;
984
985   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
986                                      htab_hash_pointer (tmpl));
987   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
988 }
989
990 /* Returns nonzero iff DECL is a specialization of TMPL.  */
991
992 int
993 is_specialization_of (tree decl, tree tmpl)
994 {
995   tree t;
996
997   if (TREE_CODE (decl) == FUNCTION_DECL)
998     {
999       for (t = decl;
1000            t != NULL_TREE;
1001            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1002         if (t == tmpl)
1003           return 1;
1004     }
1005   else
1006     {
1007       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1008
1009       for (t = TREE_TYPE (decl);
1010            t != NULL_TREE;
1011            t = CLASSTYPE_USE_TEMPLATE (t)
1012              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1013         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1014           return 1;
1015     }
1016
1017   return 0;
1018 }
1019
1020 /* Returns nonzero iff DECL is a specialization of friend declaration
1021    FRIEND according to [temp.friend].  */
1022
1023 bool
1024 is_specialization_of_friend (tree decl, tree friend)
1025 {
1026   bool need_template = true;
1027   int template_depth;
1028
1029   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1030               || TREE_CODE (decl) == TYPE_DECL);
1031
1032   /* For [temp.friend/6] when FRIEND is an ordinary member function
1033      of a template class, we want to check if DECL is a specialization
1034      if this.  */
1035   if (TREE_CODE (friend) == FUNCTION_DECL
1036       && DECL_TEMPLATE_INFO (friend)
1037       && !DECL_USE_TEMPLATE (friend))
1038     {
1039       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1040       friend = DECL_TI_TEMPLATE (friend);
1041       need_template = false;
1042     }
1043   else if (TREE_CODE (friend) == TEMPLATE_DECL
1044            && !PRIMARY_TEMPLATE_P (friend))
1045     need_template = false;
1046
1047   /* There is nothing to do if this is not a template friend.  */
1048   if (TREE_CODE (friend) != TEMPLATE_DECL)
1049     return false;
1050
1051   if (is_specialization_of (decl, friend))
1052     return true;
1053
1054   /* [temp.friend/6]
1055      A member of a class template may be declared to be a friend of a
1056      non-template class.  In this case, the corresponding member of
1057      every specialization of the class template is a friend of the
1058      class granting friendship.
1059
1060      For example, given a template friend declaration
1061
1062        template <class T> friend void A<T>::f();
1063
1064      the member function below is considered a friend
1065
1066        template <> struct A<int> {
1067          void f();
1068        };
1069
1070      For this type of template friend, TEMPLATE_DEPTH below will be
1071      nonzero.  To determine if DECL is a friend of FRIEND, we first
1072      check if the enclosing class is a specialization of another.  */
1073
1074   template_depth = template_class_depth (DECL_CONTEXT (friend));
1075   if (template_depth
1076       && DECL_CLASS_SCOPE_P (decl)
1077       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1078                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend))))
1079     {
1080       /* Next, we check the members themselves.  In order to handle
1081          a few tricky cases, such as when FRIEND's are
1082
1083            template <class T> friend void A<T>::g(T t);
1084            template <class T> template <T t> friend void A<T>::h();
1085
1086          and DECL's are
1087
1088            void A<int>::g(int);
1089            template <int> void A<int>::h();
1090
1091          we need to figure out ARGS, the template arguments from
1092          the context of DECL.  This is required for template substitution
1093          of `T' in the function parameter of `g' and template parameter
1094          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1095
1096       tree context = DECL_CONTEXT (decl);
1097       tree args = NULL_TREE;
1098       int current_depth = 0;
1099
1100       while (current_depth < template_depth)
1101         {
1102           if (CLASSTYPE_TEMPLATE_INFO (context))
1103             {
1104               if (current_depth == 0)
1105                 args = TYPE_TI_ARGS (context);
1106               else
1107                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1108               current_depth++;
1109             }
1110           context = TYPE_CONTEXT (context);
1111         }
1112
1113       if (TREE_CODE (decl) == FUNCTION_DECL)
1114         {
1115           bool is_template;
1116           tree friend_type;
1117           tree decl_type;
1118           tree friend_args_type;
1119           tree decl_args_type;
1120
1121           /* Make sure that both DECL and FRIEND are templates or
1122              non-templates.  */
1123           is_template = DECL_TEMPLATE_INFO (decl)
1124                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1125           if (need_template ^ is_template)
1126             return false;
1127           else if (is_template)
1128             {
1129               /* If both are templates, check template parameter list.  */
1130               tree friend_parms
1131                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1132                                          args, tf_none);
1133               if (!comp_template_parms
1134                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1135                       friend_parms))
1136                 return false;
1137
1138               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1139             }
1140           else
1141             decl_type = TREE_TYPE (decl);
1142
1143           friend_type = tsubst_function_type (TREE_TYPE (friend), args,
1144                                               tf_none, NULL_TREE);
1145           if (friend_type == error_mark_node)
1146             return false;
1147
1148           /* Check if return types match.  */
1149           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1150             return false;
1151
1152           /* Check if function parameter types match, ignoring the
1153              `this' parameter.  */
1154           friend_args_type = TYPE_ARG_TYPES (friend_type);
1155           decl_args_type = TYPE_ARG_TYPES (decl_type);
1156           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend))
1157             friend_args_type = TREE_CHAIN (friend_args_type);
1158           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1159             decl_args_type = TREE_CHAIN (decl_args_type);
1160
1161           return compparms (decl_args_type, friend_args_type);
1162         }
1163       else
1164         {
1165           /* DECL is a TYPE_DECL */
1166           bool is_template;
1167           tree decl_type = TREE_TYPE (decl);
1168
1169           /* Make sure that both DECL and FRIEND are templates or
1170              non-templates.  */
1171           is_template
1172             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1173               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1174
1175           if (need_template ^ is_template)
1176             return false;
1177           else if (is_template)
1178             {
1179               tree friend_parms;
1180               /* If both are templates, check the name of the two
1181                  TEMPLATE_DECL's first because is_friend didn't.  */
1182               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1183                   != DECL_NAME (friend))
1184                 return false;
1185
1186               /* Now check template parameter list.  */
1187               friend_parms
1188                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1189                                          args, tf_none);
1190               return comp_template_parms
1191                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1192                  friend_parms);
1193             }
1194           else
1195             return (DECL_NAME (decl)
1196                     == DECL_NAME (friend));
1197         }
1198     }
1199   return false;
1200 }
1201
1202 /* Register the specialization SPEC as a specialization of TMPL with
1203    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1204    is actually just a friend declaration.  Returns SPEC, or an
1205    equivalent prior declaration, if available.  */
1206
1207 static tree
1208 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1209 {
1210   tree fn;
1211
1212   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1213
1214   if (TREE_CODE (spec) == FUNCTION_DECL
1215       && uses_template_parms (DECL_TI_ARGS (spec)))
1216     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1217        register it; we want the corresponding TEMPLATE_DECL instead.
1218        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1219        the more obvious `uses_template_parms (spec)' to avoid problems
1220        with default function arguments.  In particular, given
1221        something like this:
1222
1223           template <class T> void f(T t1, T t = T())
1224
1225        the default argument expression is not substituted for in an
1226        instantiation unless and until it is actually needed.  */
1227     return spec;
1228
1229   fn = retrieve_specialization (tmpl, args,
1230                                 /*class_specializations_p=*/false);
1231   /* We can sometimes try to re-register a specialization that we've
1232      already got.  In particular, regenerate_decl_from_template calls
1233      duplicate_decls which will update the specialization list.  But,
1234      we'll still get called again here anyhow.  It's more convenient
1235      to simply allow this than to try to prevent it.  */
1236   if (fn == spec)
1237     return spec;
1238   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1239     {
1240       if (DECL_TEMPLATE_INSTANTIATION (fn))
1241         {
1242           if (TREE_USED (fn)
1243               || DECL_EXPLICIT_INSTANTIATION (fn))
1244             {
1245               error ("specialization of %qD after instantiation",
1246                      fn);
1247               return error_mark_node;
1248             }
1249           else
1250             {
1251               tree clone;
1252               /* This situation should occur only if the first
1253                  specialization is an implicit instantiation, the
1254                  second is an explicit specialization, and the
1255                  implicit instantiation has not yet been used.  That
1256                  situation can occur if we have implicitly
1257                  instantiated a member function and then specialized
1258                  it later.
1259
1260                  We can also wind up here if a friend declaration that
1261                  looked like an instantiation turns out to be a
1262                  specialization:
1263
1264                    template <class T> void foo(T);
1265                    class S { friend void foo<>(int) };
1266                    template <> void foo(int);
1267
1268                  We transform the existing DECL in place so that any
1269                  pointers to it become pointers to the updated
1270                  declaration.
1271
1272                  If there was a definition for the template, but not
1273                  for the specialization, we want this to look as if
1274                  there were no definition, and vice versa.  */
1275               DECL_INITIAL (fn) = NULL_TREE;
1276               duplicate_decls (spec, fn, is_friend);
1277               /* The call to duplicate_decls will have applied
1278                  [temp.expl.spec]:
1279
1280                    An explicit specialization of a function template
1281                    is inline only if it is explicitly declared to be,
1282                    and independently of whether its function template
1283                    is.
1284
1285                 to the primary function; now copy the inline bits to
1286                 the various clones.  */
1287               FOR_EACH_CLONE (clone, fn)
1288                 {
1289                   DECL_DECLARED_INLINE_P (clone)
1290                     = DECL_DECLARED_INLINE_P (fn);
1291                   DECL_INLINE (clone)
1292                     = DECL_INLINE (fn);
1293                 }
1294               check_specialization_namespace (fn);
1295
1296               return fn;
1297             }
1298         }
1299       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1300         {
1301           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1302             /* Dup decl failed, but this is a new definition. Set the
1303                line number so any errors match this new
1304                definition.  */
1305             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1306
1307           return fn;
1308         }
1309     }
1310
1311   /* A specialization must be declared in the same namespace as the
1312      template it is specializing.  */
1313   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1314       && !check_specialization_namespace (tmpl))
1315     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1316
1317   if (!optimize_specialization_lookup_p (tmpl))
1318     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1319       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1320
1321   return spec;
1322 }
1323
1324 /* Unregister the specialization SPEC as a specialization of TMPL.
1325    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1326    if the SPEC was listed as a specialization of TMPL.  */
1327
1328 bool
1329 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1330 {
1331   tree* s;
1332
1333   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1334        *s != NULL_TREE;
1335        s = &TREE_CHAIN (*s))
1336     if (TREE_VALUE (*s) == spec)
1337       {
1338         if (!new_spec)
1339           *s = TREE_CHAIN (*s);
1340         else
1341           TREE_VALUE (*s) = new_spec;
1342         return 1;
1343       }
1344
1345   return 0;
1346 }
1347
1348 /* Compare an entry in the local specializations hash table P1 (which
1349    is really a pointer to a TREE_LIST) with P2 (which is really a
1350    DECL).  */
1351
1352 static int
1353 eq_local_specializations (const void *p1, const void *p2)
1354 {
1355   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1356 }
1357
1358 /* Hash P1, an entry in the local specializations table.  */
1359
1360 static hashval_t
1361 hash_local_specialization (const void* p1)
1362 {
1363   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1364 }
1365
1366 /* Like register_specialization, but for local declarations.  We are
1367    registering SPEC, an instantiation of TMPL.  */
1368
1369 static void
1370 register_local_specialization (tree spec, tree tmpl)
1371 {
1372   void **slot;
1373
1374   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1375                                    htab_hash_pointer (tmpl), INSERT);
1376   *slot = build_tree_list (spec, tmpl);
1377 }
1378
1379 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1380    specialized class.  */
1381
1382 bool
1383 explicit_class_specialization_p (tree type)
1384 {
1385   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1386     return false;
1387   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1388 }
1389
1390 /* Print the list of candidate FNS in an error message.  */
1391
1392 void
1393 print_candidates (tree fns)
1394 {
1395   tree fn;
1396
1397   const char *str = "candidates are:";
1398
1399   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1400     {
1401       tree f;
1402
1403       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1404         error ("%s %+#D", str, OVL_CURRENT (f));
1405       str = "               ";
1406     }
1407 }
1408
1409 /* Returns the template (one of the functions given by TEMPLATE_ID)
1410    which can be specialized to match the indicated DECL with the
1411    explicit template args given in TEMPLATE_ID.  The DECL may be
1412    NULL_TREE if none is available.  In that case, the functions in
1413    TEMPLATE_ID are non-members.
1414
1415    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1416    specialization of a member template.
1417
1418    The TEMPLATE_COUNT is the number of references to qualifying
1419    template classes that appeared in the name of the function. See
1420    check_explicit_specialization for a more accurate description.
1421
1422    TSK indicates what kind of template declaration (if any) is being
1423    declared.  TSK_TEMPLATE indicates that the declaration given by
1424    DECL, though a FUNCTION_DECL, has template parameters, and is
1425    therefore a template function.
1426
1427    The template args (those explicitly specified and those deduced)
1428    are output in a newly created vector *TARGS_OUT.
1429
1430    If it is impossible to determine the result, an error message is
1431    issued.  The error_mark_node is returned to indicate failure.  */
1432
1433 static tree
1434 determine_specialization (tree template_id,
1435                           tree decl,
1436                           tree* targs_out,
1437                           int need_member_template,
1438                           int template_count,
1439                           tmpl_spec_kind tsk)
1440 {
1441   tree fns;
1442   tree targs;
1443   tree explicit_targs;
1444   tree candidates = NULL_TREE;
1445   /* A TREE_LIST of templates of which DECL may be a specialization.
1446      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1447      corresponding TREE_PURPOSE is the set of template arguments that,
1448      when used to instantiate the template, would produce a function
1449      with the signature of DECL.  */
1450   tree templates = NULL_TREE;
1451   int header_count;
1452   struct cp_binding_level *b;
1453
1454   *targs_out = NULL_TREE;
1455
1456   if (template_id == error_mark_node || decl == error_mark_node)
1457     return error_mark_node;
1458
1459   fns = TREE_OPERAND (template_id, 0);
1460   explicit_targs = TREE_OPERAND (template_id, 1);
1461
1462   if (fns == error_mark_node)
1463     return error_mark_node;
1464
1465   /* Check for baselinks.  */
1466   if (BASELINK_P (fns))
1467     fns = BASELINK_FUNCTIONS (fns);
1468
1469   if (!is_overloaded_fn (fns))
1470     {
1471       error ("%qD is not a function template", fns);
1472       return error_mark_node;
1473     }
1474
1475   /* Count the number of template headers specified for this
1476      specialization.  */
1477   header_count = 0;
1478   for (b = current_binding_level;
1479        b->kind == sk_template_parms;
1480        b = b->level_chain)
1481     ++header_count;
1482
1483   for (; fns; fns = OVL_NEXT (fns))
1484     {
1485       tree fn = OVL_CURRENT (fns);
1486
1487       if (TREE_CODE (fn) == TEMPLATE_DECL)
1488         {
1489           tree decl_arg_types;
1490           tree fn_arg_types;
1491
1492           /* In case of explicit specialization, we need to check if
1493              the number of template headers appearing in the specialization
1494              is correct. This is usually done in check_explicit_specialization,
1495              but the check done there cannot be exhaustive when specializing
1496              member functions. Consider the following code:
1497
1498              template <> void A<int>::f(int);
1499              template <> template <> void A<int>::f(int);
1500
1501              Assuming that A<int> is not itself an explicit specialization
1502              already, the first line specializes "f" which is a non-template
1503              member function, whilst the second line specializes "f" which
1504              is a template member function. So both lines are syntactically
1505              correct, and check_explicit_specialization does not reject
1506              them.
1507
1508              Here, we can do better, as we are matching the specialization
1509              against the declarations. We count the number of template
1510              headers, and we check if they match TEMPLATE_COUNT + 1
1511              (TEMPLATE_COUNT is the number of qualifying template classes,
1512              plus there must be another header for the member template
1513              itself).
1514
1515              Notice that if header_count is zero, this is not a
1516              specialization but rather a template instantiation, so there
1517              is no check we can perform here.  */
1518           if (header_count && header_count != template_count + 1)
1519             continue;
1520
1521           /* Check that the number of template arguments at the
1522              innermost level for DECL is the same as for FN.  */
1523           if (current_binding_level->kind == sk_template_parms
1524               && !current_binding_level->explicit_spec_p
1525               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1526                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1527                                       (current_template_parms))))
1528             continue;
1529
1530           /* DECL might be a specialization of FN.  */
1531           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1532           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1533
1534           /* For a non-static member function, we need to make sure
1535              that the const qualification is the same.  Since
1536              get_bindings does not try to merge the "this" parameter,
1537              we must do the comparison explicitly.  */
1538           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1539               && !same_type_p (TREE_VALUE (fn_arg_types),
1540                                TREE_VALUE (decl_arg_types)))
1541             continue;
1542
1543           /* Skip the "this" parameter and, for constructors of
1544              classes with virtual bases, the VTT parameter.  A
1545              full specialization of a constructor will have a VTT
1546              parameter, but a template never will.  */ 
1547           decl_arg_types 
1548             = skip_artificial_parms_for (decl, decl_arg_types);
1549           fn_arg_types 
1550             = skip_artificial_parms_for (fn, fn_arg_types);
1551
1552           /* Check that the number of function parameters matches.
1553              For example,
1554                template <class T> void f(int i = 0);
1555                template <> void f<int>();
1556              The specialization f<int> is invalid but is not caught
1557              by get_bindings below.  */
1558           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1559             continue;
1560
1561           /* Function templates cannot be specializations; there are
1562              no partial specializations of functions.  Therefore, if
1563              the type of DECL does not match FN, there is no
1564              match.  */
1565           if (tsk == tsk_template)
1566             {
1567               if (compparms (fn_arg_types, decl_arg_types))
1568                 candidates = tree_cons (NULL_TREE, fn, candidates);
1569               continue;
1570             }
1571
1572           /* See whether this function might be a specialization of this
1573              template.  */
1574           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1575
1576           if (!targs)
1577             /* We cannot deduce template arguments that when used to
1578                specialize TMPL will produce DECL.  */
1579             continue;
1580
1581           /* Save this template, and the arguments deduced.  */
1582           templates = tree_cons (targs, fn, templates);
1583         }
1584       else if (need_member_template)
1585         /* FN is an ordinary member function, and we need a
1586            specialization of a member template.  */
1587         ;
1588       else if (TREE_CODE (fn) != FUNCTION_DECL)
1589         /* We can get IDENTIFIER_NODEs here in certain erroneous
1590            cases.  */
1591         ;
1592       else if (!DECL_FUNCTION_MEMBER_P (fn))
1593         /* This is just an ordinary non-member function.  Nothing can
1594            be a specialization of that.  */
1595         ;
1596       else if (DECL_ARTIFICIAL (fn))
1597         /* Cannot specialize functions that are created implicitly.  */
1598         ;
1599       else
1600         {
1601           tree decl_arg_types;
1602
1603           /* This is an ordinary member function.  However, since
1604              we're here, we can assume it's enclosing class is a
1605              template class.  For example,
1606
1607                template <typename T> struct S { void f(); };
1608                template <> void S<int>::f() {}
1609
1610              Here, S<int>::f is a non-template, but S<int> is a
1611              template class.  If FN has the same type as DECL, we
1612              might be in business.  */
1613
1614           if (!DECL_TEMPLATE_INFO (fn))
1615             /* Its enclosing class is an explicit specialization
1616                of a template class.  This is not a candidate.  */
1617             continue;
1618
1619           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1620                             TREE_TYPE (TREE_TYPE (fn))))
1621             /* The return types differ.  */
1622             continue;
1623
1624           /* Adjust the type of DECL in case FN is a static member.  */
1625           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1626           if (DECL_STATIC_FUNCTION_P (fn)
1627               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1628             decl_arg_types = TREE_CHAIN (decl_arg_types);
1629
1630           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1631                          decl_arg_types))
1632             /* They match!  */
1633             candidates = tree_cons (NULL_TREE, fn, candidates);
1634         }
1635     }
1636
1637   if (templates && TREE_CHAIN (templates))
1638     {
1639       /* We have:
1640
1641            [temp.expl.spec]
1642
1643            It is possible for a specialization with a given function
1644            signature to be instantiated from more than one function
1645            template.  In such cases, explicit specification of the
1646            template arguments must be used to uniquely identify the
1647            function template specialization being specialized.
1648
1649          Note that here, there's no suggestion that we're supposed to
1650          determine which of the candidate templates is most
1651          specialized.  However, we, also have:
1652
1653            [temp.func.order]
1654
1655            Partial ordering of overloaded function template
1656            declarations is used in the following contexts to select
1657            the function template to which a function template
1658            specialization refers:
1659
1660            -- when an explicit specialization refers to a function
1661               template.
1662
1663          So, we do use the partial ordering rules, at least for now.
1664          This extension can only serve to make invalid programs valid,
1665          so it's safe.  And, there is strong anecdotal evidence that
1666          the committee intended the partial ordering rules to apply;
1667          the EDG front end has that behavior, and John Spicer claims
1668          that the committee simply forgot to delete the wording in
1669          [temp.expl.spec].  */
1670       tree tmpl = most_specialized_instantiation (templates);
1671       if (tmpl != error_mark_node)
1672         {
1673           templates = tmpl;
1674           TREE_CHAIN (templates) = NULL_TREE;
1675         }
1676     }
1677
1678   if (templates == NULL_TREE && candidates == NULL_TREE)
1679     {
1680       error ("template-id %qD for %q+D does not match any template "
1681              "declaration", template_id, decl);
1682       return error_mark_node;
1683     }
1684   else if ((templates && TREE_CHAIN (templates))
1685            || (candidates && TREE_CHAIN (candidates))
1686            || (templates && candidates))
1687     {
1688       error ("ambiguous template specialization %qD for %q+D",
1689              template_id, decl);
1690       chainon (candidates, templates);
1691       print_candidates (candidates);
1692       return error_mark_node;
1693     }
1694
1695   /* We have one, and exactly one, match.  */
1696   if (candidates)
1697     {
1698       tree fn = TREE_VALUE (candidates);
1699       /* DECL is a re-declaration of a template function.  */
1700       if (TREE_CODE (fn) == TEMPLATE_DECL)
1701         return fn;
1702       /* It was a specialization of an ordinary member function in a
1703          template class.  */
1704       *targs_out = copy_node (DECL_TI_ARGS (fn));
1705       return DECL_TI_TEMPLATE (fn);
1706     }
1707
1708   /* It was a specialization of a template.  */
1709   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1710   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1711     {
1712       *targs_out = copy_node (targs);
1713       SET_TMPL_ARGS_LEVEL (*targs_out,
1714                            TMPL_ARGS_DEPTH (*targs_out),
1715                            TREE_PURPOSE (templates));
1716     }
1717   else
1718     *targs_out = TREE_PURPOSE (templates);
1719   return TREE_VALUE (templates);
1720 }
1721
1722 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1723    but with the default argument values filled in from those in the
1724    TMPL_TYPES.  */
1725
1726 static tree
1727 copy_default_args_to_explicit_spec_1 (tree spec_types,
1728                                       tree tmpl_types)
1729 {
1730   tree new_spec_types;
1731
1732   if (!spec_types)
1733     return NULL_TREE;
1734
1735   if (spec_types == void_list_node)
1736     return void_list_node;
1737
1738   /* Substitute into the rest of the list.  */
1739   new_spec_types =
1740     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1741                                           TREE_CHAIN (tmpl_types));
1742
1743   /* Add the default argument for this parameter.  */
1744   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1745                          TREE_VALUE (spec_types),
1746                          new_spec_types);
1747 }
1748
1749 /* DECL is an explicit specialization.  Replicate default arguments
1750    from the template it specializes.  (That way, code like:
1751
1752      template <class T> void f(T = 3);
1753      template <> void f(double);
1754      void g () { f (); }
1755
1756    works, as required.)  An alternative approach would be to look up
1757    the correct default arguments at the call-site, but this approach
1758    is consistent with how implicit instantiations are handled.  */
1759
1760 static void
1761 copy_default_args_to_explicit_spec (tree decl)
1762 {
1763   tree tmpl;
1764   tree spec_types;
1765   tree tmpl_types;
1766   tree new_spec_types;
1767   tree old_type;
1768   tree new_type;
1769   tree t;
1770   tree object_type = NULL_TREE;
1771   tree in_charge = NULL_TREE;
1772   tree vtt = NULL_TREE;
1773
1774   /* See if there's anything we need to do.  */
1775   tmpl = DECL_TI_TEMPLATE (decl);
1776   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1777   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1778     if (TREE_PURPOSE (t))
1779       break;
1780   if (!t)
1781     return;
1782
1783   old_type = TREE_TYPE (decl);
1784   spec_types = TYPE_ARG_TYPES (old_type);
1785
1786   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1787     {
1788       /* Remove the this pointer, but remember the object's type for
1789          CV quals.  */
1790       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1791       spec_types = TREE_CHAIN (spec_types);
1792       tmpl_types = TREE_CHAIN (tmpl_types);
1793
1794       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1795         {
1796           /* DECL may contain more parameters than TMPL due to the extra
1797              in-charge parameter in constructors and destructors.  */
1798           in_charge = spec_types;
1799           spec_types = TREE_CHAIN (spec_types);
1800         }
1801       if (DECL_HAS_VTT_PARM_P (decl))
1802         {
1803           vtt = spec_types;
1804           spec_types = TREE_CHAIN (spec_types);
1805         }
1806     }
1807
1808   /* Compute the merged default arguments.  */
1809   new_spec_types =
1810     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1811
1812   /* Compute the new FUNCTION_TYPE.  */
1813   if (object_type)
1814     {
1815       if (vtt)
1816         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1817                                          TREE_VALUE (vtt),
1818                                          new_spec_types);
1819
1820       if (in_charge)
1821         /* Put the in-charge parameter back.  */
1822         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1823                                          TREE_VALUE (in_charge),
1824                                          new_spec_types);
1825
1826       new_type = build_method_type_directly (object_type,
1827                                              TREE_TYPE (old_type),
1828                                              new_spec_types);
1829     }
1830   else
1831     new_type = build_function_type (TREE_TYPE (old_type),
1832                                     new_spec_types);
1833   new_type = cp_build_type_attribute_variant (new_type,
1834                                               TYPE_ATTRIBUTES (old_type));
1835   new_type = build_exception_variant (new_type,
1836                                       TYPE_RAISES_EXCEPTIONS (old_type));
1837   TREE_TYPE (decl) = new_type;
1838 }
1839
1840 /* Check to see if the function just declared, as indicated in
1841    DECLARATOR, and in DECL, is a specialization of a function
1842    template.  We may also discover that the declaration is an explicit
1843    instantiation at this point.
1844
1845    Returns DECL, or an equivalent declaration that should be used
1846    instead if all goes well.  Issues an error message if something is
1847    amiss.  Returns error_mark_node if the error is not easily
1848    recoverable.
1849
1850    FLAGS is a bitmask consisting of the following flags:
1851
1852    2: The function has a definition.
1853    4: The function is a friend.
1854
1855    The TEMPLATE_COUNT is the number of references to qualifying
1856    template classes that appeared in the name of the function.  For
1857    example, in
1858
1859      template <class T> struct S { void f(); };
1860      void S<int>::f();
1861
1862    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1863    classes are not counted in the TEMPLATE_COUNT, so that in
1864
1865      template <class T> struct S {};
1866      template <> struct S<int> { void f(); }
1867      template <> void S<int>::f();
1868
1869    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1870    invalid; there should be no template <>.)
1871
1872    If the function is a specialization, it is marked as such via
1873    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1874    is set up correctly, and it is added to the list of specializations
1875    for that template.  */
1876
1877 tree
1878 check_explicit_specialization (tree declarator,
1879                                tree decl,
1880                                int template_count,
1881                                int flags)
1882 {
1883   int have_def = flags & 2;
1884   int is_friend = flags & 4;
1885   int specialization = 0;
1886   int explicit_instantiation = 0;
1887   int member_specialization = 0;
1888   tree ctype = DECL_CLASS_CONTEXT (decl);
1889   tree dname = DECL_NAME (decl);
1890   tmpl_spec_kind tsk;
1891
1892   if (is_friend)
1893     {
1894       if (!processing_specialization)
1895         tsk = tsk_none;
1896       else
1897         tsk = tsk_excessive_parms;
1898     }
1899   else
1900     tsk = current_tmpl_spec_kind (template_count);
1901
1902   switch (tsk)
1903     {
1904     case tsk_none:
1905       if (processing_specialization)
1906         {
1907           specialization = 1;
1908           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1909         }
1910       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1911         {
1912           if (is_friend)
1913             /* This could be something like:
1914
1915                template <class T> void f(T);
1916                class S { friend void f<>(int); }  */
1917             specialization = 1;
1918           else
1919             {
1920               /* This case handles bogus declarations like template <>
1921                  template <class T> void f<int>(); */
1922
1923               error ("template-id %qD in declaration of primary template",
1924                      declarator);
1925               return decl;
1926             }
1927         }
1928       break;
1929
1930     case tsk_invalid_member_spec:
1931       /* The error has already been reported in
1932          check_specialization_scope.  */
1933       return error_mark_node;
1934
1935     case tsk_invalid_expl_inst:
1936       error ("template parameter list used in explicit instantiation");
1937
1938       /* Fall through.  */
1939
1940     case tsk_expl_inst:
1941       if (have_def)
1942         error ("definition provided for explicit instantiation");
1943
1944       explicit_instantiation = 1;
1945       break;
1946
1947     case tsk_excessive_parms:
1948     case tsk_insufficient_parms:
1949       if (tsk == tsk_excessive_parms)
1950         error ("too many template parameter lists in declaration of %qD",
1951                decl);
1952       else if (template_header_count)
1953         error("too few template parameter lists in declaration of %qD", decl);
1954       else
1955         error("explicit specialization of %qD must be introduced by "
1956               "%<template <>%>", decl);
1957
1958       /* Fall through.  */
1959     case tsk_expl_spec:
1960       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1961       if (ctype)
1962         member_specialization = 1;
1963       else
1964         specialization = 1;
1965       break;
1966
1967     case tsk_template:
1968       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1969         {
1970           /* This case handles bogus declarations like template <>
1971              template <class T> void f<int>(); */
1972
1973           if (uses_template_parms (declarator))
1974             error ("function template partial specialization %qD "
1975                    "is not allowed", declarator);
1976           else
1977             error ("template-id %qD in declaration of primary template",
1978                    declarator);
1979           return decl;
1980         }
1981
1982       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1983         /* This is a specialization of a member template, without
1984            specialization the containing class.  Something like:
1985
1986              template <class T> struct S {
1987                template <class U> void f (U);
1988              };
1989              template <> template <class U> void S<int>::f(U) {}
1990
1991            That's a specialization -- but of the entire template.  */
1992         specialization = 1;
1993       break;
1994
1995     default:
1996       gcc_unreachable ();
1997     }
1998
1999   if (specialization || member_specialization)
2000     {
2001       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2002       for (; t; t = TREE_CHAIN (t))
2003         if (TREE_PURPOSE (t))
2004           {
2005             pedwarn
2006               ("default argument specified in explicit specialization");
2007             break;
2008           }
2009     }
2010
2011   if (specialization || member_specialization || explicit_instantiation)
2012     {
2013       tree tmpl = NULL_TREE;
2014       tree targs = NULL_TREE;
2015
2016       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2017       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2018         {
2019           tree fns;
2020
2021           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2022           if (ctype)
2023             fns = dname;
2024           else
2025             {
2026               /* If there is no class context, the explicit instantiation
2027                  must be at namespace scope.  */
2028               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2029
2030               /* Find the namespace binding, using the declaration
2031                  context.  */
2032               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2033                                            false, true);
2034               if (fns == error_mark_node || !is_overloaded_fn (fns))
2035                 {
2036                   error ("%qD is not a template function", dname);
2037                   fns = error_mark_node;
2038                 }
2039               else
2040                 {
2041                   tree fn = OVL_CURRENT (fns);
2042                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2043                                                 CP_DECL_CONTEXT (fn)))
2044                     error ("%qD is not declared in %qD",
2045                            decl, current_namespace);
2046                 }
2047             }
2048
2049           declarator = lookup_template_function (fns, NULL_TREE);
2050         }
2051
2052       if (declarator == error_mark_node)
2053         return error_mark_node;
2054
2055       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2056         {
2057           if (!explicit_instantiation)
2058             /* A specialization in class scope.  This is invalid,
2059                but the error will already have been flagged by
2060                check_specialization_scope.  */
2061             return error_mark_node;
2062           else
2063             {
2064               /* It's not valid to write an explicit instantiation in
2065                  class scope, e.g.:
2066
2067                    class C { template void f(); }
2068
2069                    This case is caught by the parser.  However, on
2070                    something like:
2071
2072                    template class C { void f(); };
2073
2074                    (which is invalid) we can get here.  The error will be
2075                    issued later.  */
2076               ;
2077             }
2078
2079           return decl;
2080         }
2081       else if (ctype != NULL_TREE
2082                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2083                    IDENTIFIER_NODE))
2084         {
2085           /* Find the list of functions in ctype that have the same
2086              name as the declared function.  */
2087           tree name = TREE_OPERAND (declarator, 0);
2088           tree fns = NULL_TREE;
2089           int idx;
2090
2091           if (constructor_name_p (name, ctype))
2092             {
2093               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2094
2095               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2096                   : !CLASSTYPE_DESTRUCTORS (ctype))
2097                 {
2098                   /* From [temp.expl.spec]:
2099
2100                      If such an explicit specialization for the member
2101                      of a class template names an implicitly-declared
2102                      special member function (clause _special_), the
2103                      program is ill-formed.
2104
2105                      Similar language is found in [temp.explicit].  */
2106                   error ("specialization of implicitly-declared special member function");
2107                   return error_mark_node;
2108                 }
2109
2110               name = is_constructor ? ctor_identifier : dtor_identifier;
2111             }
2112
2113           if (!DECL_CONV_FN_P (decl))
2114             {
2115               idx = lookup_fnfields_1 (ctype, name);
2116               if (idx >= 0)
2117                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2118             }
2119           else
2120             {
2121               VEC(tree,gc) *methods;
2122               tree ovl;
2123
2124               /* For a type-conversion operator, we cannot do a
2125                  name-based lookup.  We might be looking for `operator
2126                  int' which will be a specialization of `operator T'.
2127                  So, we find *all* the conversion operators, and then
2128                  select from them.  */
2129               fns = NULL_TREE;
2130
2131               methods = CLASSTYPE_METHOD_VEC (ctype);
2132               if (methods)
2133                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2134                      VEC_iterate (tree, methods, idx, ovl);
2135                      ++idx)
2136                   {
2137                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2138                       /* There are no more conversion functions.  */
2139                       break;
2140
2141                     /* Glue all these conversion functions together
2142                        with those we already have.  */
2143                     for (; ovl; ovl = OVL_NEXT (ovl))
2144                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2145                   }
2146             }
2147
2148           if (fns == NULL_TREE)
2149             {
2150               error ("no member function %qD declared in %qT", name, ctype);
2151               return error_mark_node;
2152             }
2153           else
2154             TREE_OPERAND (declarator, 0) = fns;
2155         }
2156
2157       /* Figure out what exactly is being specialized at this point.
2158          Note that for an explicit instantiation, even one for a
2159          member function, we cannot tell apriori whether the
2160          instantiation is for a member template, or just a member
2161          function of a template class.  Even if a member template is
2162          being instantiated, the member template arguments may be
2163          elided if they can be deduced from the rest of the
2164          declaration.  */
2165       tmpl = determine_specialization (declarator, decl,
2166                                        &targs,
2167                                        member_specialization,
2168                                        template_count,
2169                                        tsk);
2170
2171       if (!tmpl || tmpl == error_mark_node)
2172         /* We couldn't figure out what this declaration was
2173            specializing.  */
2174         return error_mark_node;
2175       else
2176         {
2177           tree gen_tmpl = most_general_template (tmpl);
2178
2179           if (explicit_instantiation)
2180             {
2181               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2182                  is done by do_decl_instantiation later.  */
2183
2184               int arg_depth = TMPL_ARGS_DEPTH (targs);
2185               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2186
2187               if (arg_depth > parm_depth)
2188                 {
2189                   /* If TMPL is not the most general template (for
2190                      example, if TMPL is a friend template that is
2191                      injected into namespace scope), then there will
2192                      be too many levels of TARGS.  Remove some of them
2193                      here.  */
2194                   int i;
2195                   tree new_targs;
2196
2197                   new_targs = make_tree_vec (parm_depth);
2198                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2199                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2200                       = TREE_VEC_ELT (targs, i);
2201                   targs = new_targs;
2202                 }
2203
2204               return instantiate_template (tmpl, targs, tf_error);
2205             }
2206
2207           /* If we thought that the DECL was a member function, but it
2208              turns out to be specializing a static member function,
2209              make DECL a static member function as well.  */
2210           if (DECL_STATIC_FUNCTION_P (tmpl)
2211               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2212             revert_static_member_fn (decl);
2213
2214           /* If this is a specialization of a member template of a
2215              template class, we want to return the TEMPLATE_DECL, not
2216              the specialization of it.  */
2217           if (tsk == tsk_template)
2218             {
2219               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2220               DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl)) = NULL_TREE;
2221               if (have_def)
2222                 {
2223                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2224                   DECL_SOURCE_LOCATION (DECL_TEMPLATE_RESULT (tmpl))
2225                     = DECL_SOURCE_LOCATION (decl);
2226                   /* We want to use the argument list specified in the
2227                      definition, not in the original declaration.  */
2228                   DECL_ARGUMENTS (DECL_TEMPLATE_RESULT (tmpl))
2229                     = DECL_ARGUMENTS (decl);
2230                 }
2231               return tmpl;
2232             }
2233
2234           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2235           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2236
2237           /* Inherit default function arguments from the template
2238              DECL is specializing.  */
2239           copy_default_args_to_explicit_spec (decl);
2240
2241           /* This specialization has the same protection as the
2242              template it specializes.  */
2243           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2244           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2245
2246           /* 7.1.1-1 [dcl.stc]
2247
2248              A storage-class-specifier shall not be specified in an
2249              explicit specialization...
2250
2251              The parser rejects these, so unless action is taken here,
2252              explicit function specializations will always appear with
2253              global linkage.
2254
2255              The action recommended by the C++ CWG in response to C++
2256              defect report 605 is to make the storage class and linkage
2257              of the explicit specialization match the templated function:
2258
2259              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2260            */
2261           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2262             {
2263               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2264               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2265
2266               /* This specialization has the same linkage and visibility as
2267                  the function template it specializes.  */
2268               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2269               if (! TREE_PUBLIC (decl))
2270                 {
2271                   DECL_INTERFACE_KNOWN (decl) = 1;
2272                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2273                 }
2274               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2275               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2276                 {
2277                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2278                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2279                 }
2280             }
2281
2282           /* If DECL is a friend declaration, declared using an
2283              unqualified name, the namespace associated with DECL may
2284              have been set incorrectly.  For example, in:
2285
2286                template <typename T> void f(T);
2287                namespace N {
2288                  struct S { friend void f<int>(int); }
2289                }
2290
2291              we will have set the DECL_CONTEXT for the friend
2292              declaration to N, rather than to the global namespace.  */
2293           if (DECL_NAMESPACE_SCOPE_P (decl))
2294             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2295
2296           if (is_friend && !have_def)
2297             /* This is not really a declaration of a specialization.
2298                It's just the name of an instantiation.  But, it's not
2299                a request for an instantiation, either.  */
2300             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2301           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2302             /* This is indeed a specialization.  In case of constructors
2303                and destructors, we need in-charge and not-in-charge
2304                versions in V3 ABI.  */
2305             clone_function_decl (decl, /*update_method_vec_p=*/0);
2306
2307           /* Register this specialization so that we can find it
2308              again.  */
2309           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2310         }
2311     }
2312
2313   return decl;
2314 }
2315
2316 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2317    parameters.  These are represented in the same format used for
2318    DECL_TEMPLATE_PARMS.  */
2319
2320 int
2321 comp_template_parms (const_tree parms1, const_tree parms2)
2322 {
2323   const_tree p1;
2324   const_tree p2;
2325
2326   if (parms1 == parms2)
2327     return 1;
2328
2329   for (p1 = parms1, p2 = parms2;
2330        p1 != NULL_TREE && p2 != NULL_TREE;
2331        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2332     {
2333       tree t1 = TREE_VALUE (p1);
2334       tree t2 = TREE_VALUE (p2);
2335       int i;
2336
2337       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2338       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2339
2340       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2341         return 0;
2342
2343       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2344         {
2345           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2346           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2347
2348           /* If either of the template parameters are invalid, assume
2349              they match for the sake of error recovery. */
2350           if (parm1 == error_mark_node || parm2 == error_mark_node)
2351             return 1;
2352
2353           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2354             return 0;
2355
2356           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2357               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2358                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2359             continue;
2360           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2361             return 0;
2362         }
2363     }
2364
2365   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2366     /* One set of parameters has more parameters lists than the
2367        other.  */
2368     return 0;
2369
2370   return 1;
2371 }
2372
2373 /* Determine whether PARM is a parameter pack.  */
2374 bool 
2375 template_parameter_pack_p (const_tree parm)
2376 {
2377   /* Determine if we have a non-type template parameter pack.  */
2378   if (TREE_CODE (parm) == PARM_DECL)
2379     return (DECL_TEMPLATE_PARM_P (parm) 
2380             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2381
2382   /* If this is a list of template parameters, we could get a
2383      TYPE_DECL or a TEMPLATE_DECL.  */ 
2384   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2385     parm = TREE_TYPE (parm);
2386
2387   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2388            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2389           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2390 }
2391
2392 /* Determine whether ARGS describes a variadic template args list,
2393    i.e., one that is terminated by a template argument pack.  */
2394 static bool 
2395 template_args_variadic_p (tree args)
2396 {
2397   int nargs;
2398   tree last_parm;
2399
2400   if (args == NULL_TREE)
2401     return false;
2402
2403   args = INNERMOST_TEMPLATE_ARGS (args);
2404   nargs = TREE_VEC_LENGTH (args);
2405
2406   if (nargs == 0)
2407     return false;
2408
2409   last_parm = TREE_VEC_ELT (args, nargs - 1);
2410
2411   return ARGUMENT_PACK_P (last_parm);
2412 }
2413
2414 /* Generate a new name for the parameter pack name NAME (an
2415    IDENTIFIER_NODE) that incorporates its */
2416 static tree
2417 make_ith_pack_parameter_name (tree name, int i)
2418 {
2419   /* Munge the name to include the parameter index.  */
2420   char numbuf[128];
2421   char* newname;
2422   
2423   sprintf(numbuf, "%i", i);
2424   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2425   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2426   return get_identifier (newname);
2427 }
2428
2429 /* Structure used to track the progress of find_parameter_packs_r.  */
2430 struct find_parameter_pack_data 
2431 {
2432   /* TREE_LIST that will contain all of the parameter packs found by
2433      the traversal.  */
2434   tree* parameter_packs;
2435
2436   /* Set of AST nodes that have been visited by the traversal.  */
2437   struct pointer_set_t *visited;
2438 };
2439
2440 /* Identifies all of the argument packs that occur in a template
2441    argument and appends them to the TREE_LIST inside DATA, which is a
2442    find_parameter_pack_data structure. This is a subroutine of
2443    make_pack_expansion and uses_parameter_packs.  */
2444 static tree
2445 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2446 {
2447   tree t = *tp;
2448   struct find_parameter_pack_data* ppd = 
2449     (struct find_parameter_pack_data*)data;
2450   bool parameter_pack_p = false;
2451
2452   /* Identify whether this is a parameter pack or not.  */
2453   switch (TREE_CODE (t))
2454     {
2455     case TEMPLATE_PARM_INDEX:
2456       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2457         parameter_pack_p = true;
2458       break;
2459
2460     case TEMPLATE_TYPE_PARM:
2461     case TEMPLATE_TEMPLATE_PARM:
2462       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2463         parameter_pack_p = true;
2464       break;
2465
2466     case PARM_DECL:
2467       if (FUNCTION_PARAMETER_PACK_P (t))
2468         {
2469           /* We don't want to walk into the type of a PARM_DECL,
2470              because we don't want to see the type parameter pack.  */
2471           *walk_subtrees = 0;
2472           parameter_pack_p = true;
2473         }
2474       break;
2475
2476     default:
2477       /* Not a parameter pack.  */
2478       break;
2479     }
2480
2481   if (parameter_pack_p)
2482     {
2483       /* Add this parameter pack to the list.  */
2484       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2485     }
2486
2487   if (TYPE_P (t))
2488     cp_walk_tree (&TYPE_CONTEXT (t), 
2489                   &find_parameter_packs_r, ppd, ppd->visited);
2490
2491   /* This switch statement will return immediately if we don't find a
2492      parameter pack.  */
2493   switch (TREE_CODE (t)) 
2494     {
2495     case TEMPLATE_PARM_INDEX:
2496       return NULL_TREE;
2497
2498     case BOUND_TEMPLATE_TEMPLATE_PARM:
2499       /* Check the template itself.  */
2500       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2501                     &find_parameter_packs_r, ppd, ppd->visited);
2502       /* Check the template arguments.  */
2503       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2504                     ppd->visited);
2505       *walk_subtrees = 0;
2506       return NULL_TREE;
2507
2508     case TEMPLATE_TYPE_PARM:
2509     case TEMPLATE_TEMPLATE_PARM:
2510       return NULL_TREE;
2511
2512     case PARM_DECL:
2513       return NULL_TREE;
2514
2515     case RECORD_TYPE:
2516       if (TYPE_PTRMEMFUNC_P (t))
2517         return NULL_TREE;
2518       /* Fall through.  */
2519
2520     case UNION_TYPE:
2521     case ENUMERAL_TYPE:
2522       if (TYPE_TEMPLATE_INFO (t))
2523         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2524                       &find_parameter_packs_r, ppd, ppd->visited);
2525
2526       *walk_subtrees = 0;
2527       return NULL_TREE;
2528
2529     case TEMPLATE_DECL:
2530       cp_walk_tree (&TREE_TYPE (t),
2531                     &find_parameter_packs_r, ppd, ppd->visited);
2532       return NULL_TREE;
2533  
2534     case TYPENAME_TYPE:
2535       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2536                    ppd, ppd->visited);
2537       *walk_subtrees = 0;
2538       return NULL_TREE;
2539       
2540     case TYPE_PACK_EXPANSION:
2541     case EXPR_PACK_EXPANSION:
2542       *walk_subtrees = 0;
2543       return NULL_TREE;
2544
2545     case INTEGER_TYPE:
2546       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2547                     ppd, ppd->visited);
2548       *walk_subtrees = 0;
2549       return NULL_TREE;
2550
2551     case IDENTIFIER_NODE:
2552       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2553                     ppd->visited);
2554       *walk_subtrees = 0;
2555       return NULL_TREE;
2556
2557     default:
2558       return NULL_TREE;
2559     }
2560
2561   return NULL_TREE;
2562 }
2563
2564 /* Determines if the expression or type T uses any parameter packs.  */
2565 bool
2566 uses_parameter_packs (tree t)
2567 {
2568   tree parameter_packs = NULL_TREE;
2569   struct find_parameter_pack_data ppd;
2570   ppd.parameter_packs = &parameter_packs;
2571   ppd.visited = pointer_set_create ();
2572   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2573   pointer_set_destroy (ppd.visited);
2574   return parameter_packs != NULL_TREE;
2575 }
2576
2577 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2578    representation a base-class initializer into a parameter pack
2579    expansion. If all goes well, the resulting node will be an
2580    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2581    respectively.  */
2582 tree 
2583 make_pack_expansion (tree arg)
2584 {
2585   tree result;
2586   tree parameter_packs = NULL_TREE;
2587   bool for_types = false;
2588   struct find_parameter_pack_data ppd;
2589
2590   if (!arg || arg == error_mark_node)
2591     return arg;
2592
2593   if (TREE_CODE (arg) == TREE_LIST)
2594     {
2595       /* The only time we will see a TREE_LIST here is for a base
2596          class initializer.  In this case, the TREE_PURPOSE will be a
2597          _TYPE node (representing the base class expansion we're
2598          initializing) and the TREE_VALUE will be a TREE_LIST
2599          containing the initialization arguments. 
2600
2601          The resulting expansion looks somewhat different from most
2602          expansions. Rather than returning just one _EXPANSION, we
2603          return a TREE_LIST whose TREE_PURPOSE is a
2604          TYPE_PACK_EXPANSION containing the bases that will be
2605          initialized.  The TREE_VALUE will be identical to the
2606          original TREE_VALUE, which is a list of arguments that will
2607          be passed to each base.  We do not introduce any new pack
2608          expansion nodes into the TREE_VALUE (although it is possible
2609          that some already exist), because the TREE_PURPOSE and
2610          TREE_VALUE all need to be expanded together with the same
2611          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2612          resulting TREE_PURPOSE will mention the parameter packs in
2613          both the bases and the arguments to the bases.  */
2614       tree purpose;
2615       tree value;
2616       tree parameter_packs = NULL_TREE;
2617
2618       /* Determine which parameter packs will be used by the base
2619          class expansion.  */
2620       ppd.visited = pointer_set_create ();
2621       ppd.parameter_packs = &parameter_packs;
2622       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2623                     &ppd, ppd.visited);
2624
2625       if (parameter_packs == NULL_TREE)
2626         {
2627           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2628           pointer_set_destroy (ppd.visited);
2629           return error_mark_node;
2630         }
2631
2632       if (TREE_VALUE (arg) != void_type_node)
2633         {
2634           /* Collect the sets of parameter packs used in each of the
2635              initialization arguments.  */
2636           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2637             {
2638               /* Determine which parameter packs will be expanded in this
2639                  argument.  */
2640               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2641                             &ppd, ppd.visited);
2642             }
2643         }
2644
2645       pointer_set_destroy (ppd.visited);
2646
2647       /* Create the pack expansion type for the base type.  */
2648       purpose = make_node (TYPE_PACK_EXPANSION);
2649       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2650       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2651
2652       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2653          they will rarely be compared to anything.  */
2654       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2655
2656       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2657     }
2658
2659   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2660     for_types = true;
2661
2662   /* Build the PACK_EXPANSION_* node.  */
2663   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2664   SET_PACK_EXPANSION_PATTERN (result, arg);
2665   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2666     {
2667       /* Propagate type and const-expression information.  */
2668       TREE_TYPE (result) = TREE_TYPE (arg);
2669       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2670     }
2671   else
2672     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2673        they will rarely be compared to anything.  */
2674     SET_TYPE_STRUCTURAL_EQUALITY (result);
2675
2676   /* Determine which parameter packs will be expanded.  */
2677   ppd.parameter_packs = &parameter_packs;
2678   ppd.visited = pointer_set_create ();
2679   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2680   pointer_set_destroy (ppd.visited);
2681
2682   /* Make sure we found some parameter packs.  */
2683   if (parameter_packs == NULL_TREE)
2684     {
2685       if (TYPE_P (arg))
2686         error ("expansion pattern %<%T%> contains no argument packs", arg);
2687       else
2688         error ("expansion pattern %<%E%> contains no argument packs", arg);
2689       return error_mark_node;
2690     }
2691   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2692
2693   return result;
2694 }
2695
2696 /* Checks T for any "bare" parameter packs, which have not yet been
2697    expanded, and issues an error if any are found. This operation can
2698    only be done on full expressions or types (e.g., an expression
2699    statement, "if" condition, etc.), because we could have expressions like:
2700
2701      foo(f(g(h(args)))...)
2702
2703    where "args" is a parameter pack. check_for_bare_parameter_packs
2704    should not be called for the subexpressions args, h(args),
2705    g(h(args)), or f(g(h(args))), because we would produce erroneous
2706    error messages. 
2707
2708    Returns TRUE and emits an error if there were bare parameter packs,
2709    returns FALSE otherwise.  */
2710 bool 
2711 check_for_bare_parameter_packs (tree t)
2712 {
2713   tree parameter_packs = NULL_TREE;
2714   struct find_parameter_pack_data ppd;
2715
2716   if (!processing_template_decl || !t || t == error_mark_node)
2717     return false;
2718
2719   if (TREE_CODE (t) == TYPE_DECL)
2720     t = TREE_TYPE (t);
2721
2722   ppd.parameter_packs = &parameter_packs;
2723   ppd.visited = pointer_set_create ();
2724   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2725   pointer_set_destroy (ppd.visited);
2726
2727   if (parameter_packs) 
2728     {
2729       error ("parameter packs not expanded with %<...%>:");
2730       while (parameter_packs)
2731         {
2732           tree pack = TREE_VALUE (parameter_packs);
2733           tree name = NULL_TREE;
2734
2735           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2736               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2737             name = TYPE_NAME (pack);
2738           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2739             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2740           else
2741             name = DECL_NAME (pack);
2742
2743           if (name)
2744             inform ("        %qD", name);
2745           else
2746             inform ("        <anonymous>");
2747
2748           parameter_packs = TREE_CHAIN (parameter_packs);
2749         }
2750
2751       return true;
2752     }
2753
2754   return false;
2755 }
2756
2757 /* Expand any parameter packs that occur in the template arguments in
2758    ARGS.  */
2759 tree
2760 expand_template_argument_pack (tree args)
2761 {
2762   tree result_args = NULL_TREE;
2763   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2764   int num_result_args = -1;
2765
2766   /* First, determine if we need to expand anything, and the number of
2767      slots we'll need.  */
2768   for (in_arg = 0; in_arg < nargs; ++in_arg)
2769     {
2770       tree arg = TREE_VEC_ELT (args, in_arg);
2771       if (ARGUMENT_PACK_P (arg))
2772         {
2773           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2774           if (num_result_args < 0)
2775             num_result_args = in_arg + num_packed;
2776           else
2777             num_result_args += num_packed;
2778         }
2779       else
2780         {
2781           if (num_result_args >= 0)
2782             num_result_args++;
2783         }
2784     }
2785
2786   /* If no expansion is necessary, we're done.  */
2787   if (num_result_args < 0)
2788     return args;
2789
2790   /* Expand arguments.  */
2791   result_args = make_tree_vec (num_result_args);
2792   for (in_arg = 0; in_arg < nargs; ++in_arg)
2793     {
2794       tree arg = TREE_VEC_ELT (args, in_arg);
2795       if (ARGUMENT_PACK_P (arg))
2796         {
2797           tree packed = ARGUMENT_PACK_ARGS (arg);
2798           int i, num_packed = TREE_VEC_LENGTH (packed);
2799           for (i = 0; i < num_packed; ++i, ++out_arg)
2800             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2801         }
2802       else
2803         {
2804           TREE_VEC_ELT (result_args, out_arg) = arg;
2805           ++out_arg;
2806         }
2807     }
2808
2809   return result_args;
2810 }
2811
2812 /* Complain if DECL shadows a template parameter.
2813
2814    [temp.local]: A template-parameter shall not be redeclared within its
2815    scope (including nested scopes).  */
2816
2817 void
2818 check_template_shadow (tree decl)
2819 {
2820   tree olddecl;
2821
2822   /* If we're not in a template, we can't possibly shadow a template
2823      parameter.  */
2824   if (!current_template_parms)
2825     return;
2826
2827   /* Figure out what we're shadowing.  */
2828   if (TREE_CODE (decl) == OVERLOAD)
2829     decl = OVL_CURRENT (decl);
2830   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2831
2832   /* If there's no previous binding for this name, we're not shadowing
2833      anything, let alone a template parameter.  */
2834   if (!olddecl)
2835     return;
2836
2837   /* If we're not shadowing a template parameter, we're done.  Note
2838      that OLDDECL might be an OVERLOAD (or perhaps even an
2839      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2840      node.  */
2841   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2842     return;
2843
2844   /* We check for decl != olddecl to avoid bogus errors for using a
2845      name inside a class.  We check TPFI to avoid duplicate errors for
2846      inline member templates.  */
2847   if (decl == olddecl
2848       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2849     return;
2850
2851   error ("declaration of %q+#D", decl);
2852   error (" shadows template parm %q+#D", olddecl);
2853 }
2854
2855 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2856    ORIG_LEVEL, DECL, and TYPE.  */
2857
2858 static tree
2859 build_template_parm_index (int index,
2860                            int level,
2861                            int orig_level,
2862                            tree decl,
2863                            tree type)
2864 {
2865   tree t = make_node (TEMPLATE_PARM_INDEX);
2866   TEMPLATE_PARM_IDX (t) = index;
2867   TEMPLATE_PARM_LEVEL (t) = level;
2868   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2869   TEMPLATE_PARM_DECL (t) = decl;
2870   TREE_TYPE (t) = type;
2871   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2872   TREE_READONLY (t) = TREE_READONLY (decl);
2873
2874   return t;
2875 }
2876
2877 /* Find the canonical type parameter for the given template type
2878    parameter.  Returns the canonical type parameter, which may be TYPE
2879    if no such parameter existed.  */
2880 static tree
2881 canonical_type_parameter (tree type)
2882 {
2883   tree list;
2884   int idx = TEMPLATE_TYPE_IDX (type);
2885   if (!canonical_template_parms)
2886     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2887
2888   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2889     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2890
2891   list = VEC_index (tree, canonical_template_parms, idx);
2892   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2893     list = TREE_CHAIN (list);
2894
2895   if (list)
2896     return TREE_VALUE (list);
2897   else
2898     {
2899       VEC_replace(tree, canonical_template_parms, idx,
2900                   tree_cons (NULL_TREE, type, 
2901                              VEC_index (tree, canonical_template_parms, idx)));
2902       return type;
2903     }
2904 }
2905
2906 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2907    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2908    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2909    new one is created.  */
2910
2911 static tree
2912 reduce_template_parm_level (tree index, tree type, int levels, tree args,
2913                             tsubst_flags_t complain)
2914 {
2915   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2916       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2917           != TEMPLATE_PARM_LEVEL (index) - levels))
2918     {
2919       tree orig_decl = TEMPLATE_PARM_DECL (index);
2920       tree decl, t;
2921
2922       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2923       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2924       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2925       DECL_ARTIFICIAL (decl) = 1;
2926       SET_DECL_TEMPLATE_PARM_P (decl);
2927
2928       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2929                                      TEMPLATE_PARM_LEVEL (index) - levels,
2930                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2931                                      decl, type);
2932       TEMPLATE_PARM_DESCENDANTS (index) = t;
2933       TEMPLATE_PARM_PARAMETER_PACK (t) 
2934         = TEMPLATE_PARM_PARAMETER_PACK (index);
2935
2936         /* Template template parameters need this.  */
2937       if (TREE_CODE (decl) == TEMPLATE_DECL)
2938         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
2939           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
2940            args, complain);
2941     }
2942
2943   return TEMPLATE_PARM_DESCENDANTS (index);
2944 }
2945
2946 /* Process information from new template parameter PARM and append it to the
2947    LIST being built.  This new parameter is a non-type parameter iff
2948    IS_NON_TYPE is true. This new parameter is a parameter
2949    pack iff IS_PARAMETER_PACK is true.  */
2950
2951 tree
2952 process_template_parm (tree list, tree parm, bool is_non_type, 
2953                        bool is_parameter_pack)
2954 {
2955   tree decl = 0;
2956   tree defval;
2957   tree err_parm_list;
2958   int idx = 0;
2959
2960   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2961   defval = TREE_PURPOSE (parm);
2962
2963   if (list)
2964     {
2965       tree p = tree_last (list);
2966
2967       if (p && TREE_VALUE (p) != error_mark_node)
2968         {
2969           p = TREE_VALUE (p);
2970           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2971             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2972           else
2973             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2974         }
2975
2976       ++idx;
2977     }
2978   else
2979     idx = 0;
2980
2981   if (is_non_type)
2982     {
2983       parm = TREE_VALUE (parm);
2984
2985       SET_DECL_TEMPLATE_PARM_P (parm);
2986
2987       if (TREE_TYPE (parm) == error_mark_node)
2988         {
2989           err_parm_list = build_tree_list (defval, parm);
2990           TREE_VALUE (err_parm_list) = error_mark_node;
2991            return chainon (list, err_parm_list);
2992         }
2993       else
2994       {
2995         /* [temp.param]
2996
2997            The top-level cv-qualifiers on the template-parameter are
2998            ignored when determining its type.  */
2999         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3000         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3001           {
3002             err_parm_list = build_tree_list (defval, parm);
3003             TREE_VALUE (err_parm_list) = error_mark_node;
3004              return chainon (list, err_parm_list);
3005           }
3006
3007         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3008           {
3009             /* This template parameter is not a parameter pack, but it
3010                should be. Complain about "bare" parameter packs.  */
3011             check_for_bare_parameter_packs (TREE_TYPE (parm));
3012             
3013             /* Recover by calling this a parameter pack.  */
3014             is_parameter_pack = true;
3015           }
3016       }
3017
3018       /* A template parameter is not modifiable.  */
3019       TREE_CONSTANT (parm) = 1;
3020       TREE_READONLY (parm) = 1;
3021       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3022       TREE_CONSTANT (decl) = 1;
3023       TREE_READONLY (decl) = 1;
3024       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3025         = build_template_parm_index (idx, processing_template_decl,
3026                                      processing_template_decl,
3027                                      decl, TREE_TYPE (parm));
3028
3029       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3030         = is_parameter_pack;
3031     }
3032   else
3033     {
3034       tree t;
3035       parm = TREE_VALUE (TREE_VALUE (parm));
3036
3037       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3038         {
3039           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3040           /* This is for distinguishing between real templates and template
3041              template parameters */
3042           TREE_TYPE (parm) = t;
3043           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3044           decl = parm;
3045         }
3046       else
3047         {
3048           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3049           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3050           decl = build_decl (TYPE_DECL, parm, t);
3051         }
3052
3053       TYPE_NAME (t) = decl;
3054       TYPE_STUB_DECL (t) = decl;
3055       parm = decl;
3056       TEMPLATE_TYPE_PARM_INDEX (t)
3057         = build_template_parm_index (idx, processing_template_decl,
3058                                      processing_template_decl,
3059                                      decl, TREE_TYPE (parm));
3060       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3061       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3062     }
3063   DECL_ARTIFICIAL (decl) = 1;
3064   SET_DECL_TEMPLATE_PARM_P (decl);
3065   pushdecl (decl);
3066   parm = build_tree_list (defval, parm);
3067   return chainon (list, parm);
3068 }
3069
3070 /* The end of a template parameter list has been reached.  Process the
3071    tree list into a parameter vector, converting each parameter into a more
3072    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3073    as PARM_DECLs.  */
3074
3075 tree
3076 end_template_parm_list (tree parms)
3077 {
3078   int nparms;
3079   tree parm, next;
3080   tree saved_parmlist = make_tree_vec (list_length (parms));
3081
3082   current_template_parms
3083     = tree_cons (size_int (processing_template_decl),
3084                  saved_parmlist, current_template_parms);
3085
3086   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3087     {
3088       next = TREE_CHAIN (parm);
3089       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3090       TREE_CHAIN (parm) = NULL_TREE;
3091     }
3092
3093   --processing_template_parmlist;
3094
3095   return saved_parmlist;
3096 }
3097
3098 /* end_template_decl is called after a template declaration is seen.  */
3099
3100 void
3101 end_template_decl (void)
3102 {
3103   reset_specialization ();
3104
3105   if (! processing_template_decl)
3106     return;
3107
3108   /* This matches the pushlevel in begin_template_parm_list.  */
3109   finish_scope ();
3110
3111   --processing_template_decl;
3112   current_template_parms = TREE_CHAIN (current_template_parms);
3113 }
3114
3115 /* Within the declaration of a template, return all levels of template
3116    parameters that apply.  The template parameters are represented as
3117    a TREE_VEC, in the form documented in cp-tree.h for template
3118    arguments.  */
3119
3120 static tree
3121 current_template_args (void)
3122 {
3123   tree header;
3124   tree args = NULL_TREE;
3125   int length = TMPL_PARMS_DEPTH (current_template_parms);
3126   int l = length;
3127
3128   /* If there is only one level of template parameters, we do not
3129      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3130      TREE_VEC containing the arguments.  */
3131   if (length > 1)
3132     args = make_tree_vec (length);
3133
3134   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3135     {
3136       tree a = copy_node (TREE_VALUE (header));
3137       int i;
3138
3139       TREE_TYPE (a) = NULL_TREE;
3140       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3141         {
3142           tree t = TREE_VEC_ELT (a, i);
3143
3144           /* T will be a list if we are called from within a
3145              begin/end_template_parm_list pair, but a vector directly
3146              if within a begin/end_member_template_processing pair.  */
3147           if (TREE_CODE (t) == TREE_LIST)
3148             {
3149               t = TREE_VALUE (t);
3150
3151               if (!error_operand_p (t))
3152                 {
3153                   if (TREE_CODE (t) == TYPE_DECL
3154                       || TREE_CODE (t) == TEMPLATE_DECL)
3155                     {
3156                       t = TREE_TYPE (t);
3157                       
3158                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3159                         {
3160                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3161                              with a single element, which expands T.  */
3162                           tree vec = make_tree_vec (1);
3163                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3164                           
3165                           t = make_node (TYPE_ARGUMENT_PACK);
3166                           SET_ARGUMENT_PACK_ARGS (t, vec);
3167                         }
3168                     }
3169                   else
3170                     {
3171                       t = DECL_INITIAL (t);
3172                       
3173                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3174                         {
3175                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3176                              with a single element, which expands T.  */
3177                           tree vec = make_tree_vec (1);
3178                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3179                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3180                           
3181                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3182                           SET_ARGUMENT_PACK_ARGS (t, vec);
3183                           TREE_TYPE (t) = type;
3184                         }
3185                     }
3186                   TREE_VEC_ELT (a, i) = t;
3187                 }
3188             }
3189         }
3190
3191       if (length > 1)
3192         TREE_VEC_ELT (args, --l) = a;
3193       else
3194         args = a;
3195     }
3196
3197   return args;
3198 }
3199
3200 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3201    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3202    a member template.  Used by push_template_decl below.  */
3203
3204 static tree
3205 build_template_decl (tree decl, tree parms, bool member_template_p)
3206 {
3207   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3208   DECL_TEMPLATE_PARMS (tmpl) = parms;
3209   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3210   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3211   if (DECL_LANG_SPECIFIC (decl))
3212     {
3213       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3214       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3215       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3216       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3217       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3218       if (DECL_OVERLOADED_OPERATOR_P (decl))
3219         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3220                                       DECL_OVERLOADED_OPERATOR_P (decl));
3221     }
3222
3223   return tmpl;
3224 }
3225
3226 struct template_parm_data
3227 {
3228   /* The level of the template parameters we are currently
3229      processing.  */
3230   int level;
3231
3232   /* The index of the specialization argument we are currently
3233      processing.  */
3234   int current_arg;
3235
3236   /* An array whose size is the number of template parameters.  The
3237      elements are nonzero if the parameter has been used in any one
3238      of the arguments processed so far.  */
3239   int* parms;
3240
3241   /* An array whose size is the number of template arguments.  The
3242      elements are nonzero if the argument makes use of template
3243      parameters of this level.  */
3244   int* arg_uses_template_parms;
3245 };
3246
3247 /* Subroutine of push_template_decl used to see if each template
3248    parameter in a partial specialization is used in the explicit
3249    argument list.  If T is of the LEVEL given in DATA (which is
3250    treated as a template_parm_data*), then DATA->PARMS is marked
3251    appropriately.  */
3252
3253 static int
3254 mark_template_parm (tree t, void* data)
3255 {
3256   int level;
3257   int idx;
3258   struct template_parm_data* tpd = (struct template_parm_data*) data;
3259
3260   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3261     {
3262       level = TEMPLATE_PARM_LEVEL (t);
3263       idx = TEMPLATE_PARM_IDX (t);
3264     }
3265   else
3266     {
3267       level = TEMPLATE_TYPE_LEVEL (t);
3268       idx = TEMPLATE_TYPE_IDX (t);
3269     }
3270
3271   if (level == tpd->level)
3272     {
3273       tpd->parms[idx] = 1;
3274       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3275     }
3276
3277   /* Return zero so that for_each_template_parm will continue the
3278      traversal of the tree; we want to mark *every* template parm.  */
3279   return 0;
3280 }
3281
3282 /* Process the partial specialization DECL.  */
3283
3284 static tree
3285 process_partial_specialization (tree decl)
3286 {
3287   tree type = TREE_TYPE (decl);
3288   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3289   tree specargs = CLASSTYPE_TI_ARGS (type);
3290   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3291   tree inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3292   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3293   int nargs = TREE_VEC_LENGTH (inner_args);
3294   int ntparms = TREE_VEC_LENGTH (inner_parms);
3295   int  i;
3296   int did_error_intro = 0;
3297   struct template_parm_data tpd;
3298   struct template_parm_data tpd2;
3299
3300   /* We check that each of the template parameters given in the
3301      partial specialization is used in the argument list to the
3302      specialization.  For example:
3303
3304        template <class T> struct S;
3305        template <class T> struct S<T*>;
3306
3307      The second declaration is OK because `T*' uses the template
3308      parameter T, whereas
3309
3310        template <class T> struct S<int>;
3311
3312      is no good.  Even trickier is:
3313
3314        template <class T>
3315        struct S1
3316        {
3317           template <class U>
3318           struct S2;
3319           template <class U>
3320           struct S2<T>;
3321        };
3322
3323      The S2<T> declaration is actually invalid; it is a
3324      full-specialization.  Of course,
3325
3326           template <class U>
3327           struct S2<T (*)(U)>;
3328
3329      or some such would have been OK.  */
3330   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3331   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3332   memset (tpd.parms, 0, sizeof (int) * ntparms);
3333
3334   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3335   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3336   for (i = 0; i < nargs; ++i)
3337     {
3338       tpd.current_arg = i;
3339       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3340                               &mark_template_parm,
3341                               &tpd,
3342                               NULL,
3343                               /*include_nondeduced_p=*/false);
3344     }
3345   for (i = 0; i < ntparms; ++i)
3346     if (tpd.parms[i] == 0)
3347       {
3348         /* One of the template parms was not used in the
3349            specialization.  */
3350         if (!did_error_intro)
3351           {
3352             error ("template parameters not used in partial specialization:");
3353             did_error_intro = 1;
3354           }
3355
3356         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3357       }
3358
3359   /* [temp.class.spec]
3360
3361      The argument list of the specialization shall not be identical to
3362      the implicit argument list of the primary template.  */
3363   if (comp_template_args
3364       (inner_args,
3365        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3366                                                    (maintmpl)))))
3367     error ("partial specialization %qT does not specialize any template arguments", type);
3368
3369   /* [temp.class.spec]
3370
3371      A partially specialized non-type argument expression shall not
3372      involve template parameters of the partial specialization except
3373      when the argument expression is a simple identifier.
3374
3375      The type of a template parameter corresponding to a specialized
3376      non-type argument shall not be dependent on a parameter of the
3377      specialization. 
3378
3379      Also, we verify that pack expansions only occur at the
3380      end of the argument list.  */
3381   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3382   tpd2.parms = 0;
3383   for (i = 0; i < nargs; ++i)
3384     {
3385       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3386       tree arg = TREE_VEC_ELT (inner_args, i);
3387       tree packed_args = NULL_TREE;
3388       int j, len = 1;
3389
3390       if (ARGUMENT_PACK_P (arg))
3391         {
3392           /* Extract the arguments from the argument pack. We'll be
3393              iterating over these in the following loop.  */
3394           packed_args = ARGUMENT_PACK_ARGS (arg);
3395           len = TREE_VEC_LENGTH (packed_args);
3396         }
3397
3398       for (j = 0; j < len; j++)
3399         {
3400           if (packed_args)
3401             /* Get the Jth argument in the parameter pack.  */
3402             arg = TREE_VEC_ELT (packed_args, j);
3403
3404           if (PACK_EXPANSION_P (arg))
3405             {
3406               /* Pack expansions must come at the end of the
3407                  argument list.  */
3408               if ((packed_args && j < len - 1)
3409                   || (!packed_args && i < nargs - 1))
3410                 {
3411                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3412                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3413                   else
3414                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3415
3416                   if (packed_args)
3417                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3418                 }
3419             }
3420
3421           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3422             /* We only care about the pattern.  */
3423             arg = PACK_EXPANSION_PATTERN (arg);
3424
3425           if (/* These first two lines are the `non-type' bit.  */
3426               !TYPE_P (arg)
3427               && TREE_CODE (arg) != TEMPLATE_DECL
3428               /* This next line is the `argument expression is not just a
3429                  simple identifier' condition and also the `specialized
3430                  non-type argument' bit.  */
3431               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3432             {
3433               if ((!packed_args && tpd.arg_uses_template_parms[i])
3434                   || (packed_args && uses_template_parms (arg)))
3435                 error ("template argument %qE involves template parameter(s)",
3436                        arg);
3437               else 
3438                 {
3439                   /* Look at the corresponding template parameter,
3440                      marking which template parameters its type depends
3441                      upon.  */
3442                   tree type = TREE_TYPE (parm);
3443
3444                   if (!tpd2.parms)
3445                     {
3446                       /* We haven't yet initialized TPD2.  Do so now.  */
3447                       tpd2.arg_uses_template_parms 
3448                         = (int *) alloca (sizeof (int) * nargs);
3449                       /* The number of parameters here is the number in the
3450                          main template, which, as checked in the assertion
3451                          above, is NARGS.  */
3452                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3453                       tpd2.level = 
3454                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3455                     }
3456
3457                   /* Mark the template parameters.  But this time, we're
3458                      looking for the template parameters of the main
3459                      template, not in the specialization.  */
3460                   tpd2.current_arg = i;
3461                   tpd2.arg_uses_template_parms[i] = 0;
3462                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3463                   for_each_template_parm (type,
3464                                           &mark_template_parm,
3465                                           &tpd2,
3466                                           NULL,
3467                                           /*include_nondeduced_p=*/false);
3468
3469                   if (tpd2.arg_uses_template_parms [i])
3470                     {
3471                       /* The type depended on some template parameters.
3472                          If they are fully specialized in the
3473                          specialization, that's OK.  */
3474                       int j;
3475                       for (j = 0; j < nargs; ++j)
3476                         if (tpd2.parms[j] != 0
3477                             && tpd.arg_uses_template_parms [j])
3478                           {
3479                             error ("type %qT of template argument %qE depends "
3480                                    "on template parameter(s)", 
3481                                    type,
3482                                    arg);
3483                             break;
3484                           }
3485                     }
3486                 }
3487             }
3488         }
3489     }
3490
3491   if (retrieve_specialization (maintmpl, specargs,
3492                                /*class_specializations_p=*/true))
3493     /* We've already got this specialization.  */
3494     return decl;
3495
3496   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3497     = tree_cons (specargs, inner_parms,
3498                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3499   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3500   return decl;
3501 }
3502
3503 /* Check that a template declaration's use of default arguments and
3504    parameter packs is not invalid.  Here, PARMS are the template
3505    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3506    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3507    specialization.
3508    
3509
3510    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3511    declaration (but not a definition); 1 indicates a declaration, 2
3512    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3513    emitted for extraneous default arguments.
3514
3515    Returns TRUE if there were no errors found, FALSE otherwise. */
3516
3517 bool
3518 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3519                          int is_partial, int is_friend_decl)
3520 {
3521   const char *msg;
3522   int last_level_to_check;
3523   tree parm_level;
3524   bool no_errors = true;
3525
3526   /* [temp.param]
3527
3528      A default template-argument shall not be specified in a
3529      function template declaration or a function template definition, nor
3530      in the template-parameter-list of the definition of a member of a
3531      class template.  */
3532
3533   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3534     /* You can't have a function template declaration in a local
3535        scope, nor you can you define a member of a class template in a
3536        local scope.  */
3537     return true;
3538
3539   if (current_class_type
3540       && !TYPE_BEING_DEFINED (current_class_type)
3541       && DECL_LANG_SPECIFIC (decl)
3542       /* If this is either a friend defined in the scope of the class
3543          or a member function.  */
3544       && (DECL_FUNCTION_MEMBER_P (decl)
3545           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3546           : DECL_FRIEND_CONTEXT (decl)
3547           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3548           : false)
3549       /* And, if it was a member function, it really was defined in
3550          the scope of the class.  */
3551       && (!DECL_FUNCTION_MEMBER_P (decl)
3552           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3553     /* We already checked these parameters when the template was
3554        declared, so there's no need to do it again now.  This function
3555        was defined in class scope, but we're processing it's body now
3556        that the class is complete.  */
3557     return true;
3558
3559   /* Core issue 226 (C++0x only): the following only applies to class
3560      templates.  */
3561   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3562     {
3563       /* [temp.param]
3564
3565          If a template-parameter has a default template-argument, all
3566          subsequent template-parameters shall have a default
3567          template-argument supplied.  */
3568       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3569         {
3570           tree inner_parms = TREE_VALUE (parm_level);
3571           int ntparms = TREE_VEC_LENGTH (inner_parms);
3572           int seen_def_arg_p = 0;
3573           int i;
3574
3575           for (i = 0; i < ntparms; ++i)
3576             {
3577               tree parm = TREE_VEC_ELT (inner_parms, i);
3578
3579               if (parm == error_mark_node)
3580                 continue;
3581
3582               if (TREE_PURPOSE (parm))
3583                 seen_def_arg_p = 1;
3584               else if (seen_def_arg_p)
3585                 {
3586                   error ("no default argument for %qD", TREE_VALUE (parm));
3587                   /* For better subsequent error-recovery, we indicate that
3588                      there should have been a default argument.  */
3589                   TREE_PURPOSE (parm) = error_mark_node;
3590                   no_errors = false;
3591                 }
3592               else if (is_primary
3593                        && !is_partial
3594                        && !is_friend_decl
3595                        && TREE_CODE (decl) == TYPE_DECL
3596                        && i < ntparms - 1
3597                        && template_parameter_pack_p (TREE_VALUE (parm)))
3598                 {
3599                   /* A primary class template can only have one
3600                      parameter pack, at the end of the template
3601                      parameter list.  */
3602
3603                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3604                     error ("parameter pack %qE must be at the end of the"
3605                            " template parameter list", TREE_VALUE (parm));
3606                   else
3607                     error ("parameter pack %qT must be at the end of the"
3608                            " template parameter list", 
3609                            TREE_TYPE (TREE_VALUE (parm)));
3610
3611                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3612                     = error_mark_node;
3613                   no_errors = false;
3614                 }
3615             }
3616         }
3617     }
3618
3619   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3620       || is_partial 
3621       || !is_primary
3622       || is_friend_decl)
3623     /* For an ordinary class template, default template arguments are
3624        allowed at the innermost level, e.g.:
3625          template <class T = int>
3626          struct S {};
3627        but, in a partial specialization, they're not allowed even
3628        there, as we have in [temp.class.spec]:
3629
3630          The template parameter list of a specialization shall not
3631          contain default template argument values.
3632
3633        So, for a partial specialization, or for a function template
3634        (in C++98/C++03), we look at all of them.  */
3635     ;
3636   else
3637     /* But, for a primary class template that is not a partial
3638        specialization we look at all template parameters except the
3639        innermost ones.  */
3640     parms = TREE_CHAIN (parms);
3641
3642   /* Figure out what error message to issue.  */
3643   if (is_friend_decl == 2)
3644     msg = "default template arguments may not be used in function template friend re-declaration";
3645   else if (is_friend_decl)
3646     msg = "default template arguments may not be used in function template friend declarations";
3647   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3648     msg = "default template arguments may not be used in function templates";
3649   else if (is_partial)
3650     msg = "default template arguments may not be used in partial specializations";
3651   else
3652     msg = "default argument for template parameter for class enclosing %qD";
3653
3654   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3655     /* If we're inside a class definition, there's no need to
3656        examine the parameters to the class itself.  On the one
3657        hand, they will be checked when the class is defined, and,
3658        on the other, default arguments are valid in things like:
3659          template <class T = double>
3660          struct S { template <class U> void f(U); };
3661        Here the default argument for `S' has no bearing on the
3662        declaration of `f'.  */
3663     last_level_to_check = template_class_depth (current_class_type) + 1;
3664   else
3665     /* Check everything.  */
3666     last_level_to_check = 0;
3667
3668   for (parm_level = parms;
3669        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3670        parm_level = TREE_CHAIN (parm_level))
3671     {
3672       tree inner_parms = TREE_VALUE (parm_level);
3673       int i;
3674       int ntparms;
3675
3676       ntparms = TREE_VEC_LENGTH (inner_parms);
3677       for (i = 0; i < ntparms; ++i)
3678         {
3679           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3680             continue;
3681
3682           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3683             {
3684               if (msg)
3685                 {
3686                   no_errors = false;
3687                   if (is_friend_decl == 2)
3688                     return no_errors;
3689
3690                   error (msg, decl);
3691                   msg = 0;
3692                 }
3693
3694               /* Clear out the default argument so that we are not
3695                  confused later.  */
3696               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3697             }
3698         }
3699
3700       /* At this point, if we're still interested in issuing messages,
3701          they must apply to classes surrounding the object declared.  */
3702       if (msg)
3703         msg = "default argument for template parameter for class enclosing %qD";
3704     }
3705
3706   return no_errors;
3707 }
3708
3709 /* Worker for push_template_decl_real, called via
3710    for_each_template_parm.  DATA is really an int, indicating the
3711    level of the parameters we are interested in.  If T is a template
3712    parameter of that level, return nonzero.  */
3713
3714 static int
3715 template_parm_this_level_p (tree t, void* data)
3716 {
3717   int this_level = *(int *)data;
3718   int level;
3719
3720   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3721     level = TEMPLATE_PARM_LEVEL (t);
3722   else
3723     level = TEMPLATE_TYPE_LEVEL (t);
3724   return level == this_level;
3725 }
3726
3727 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3728    parameters given by current_template_args, or reuses a
3729    previously existing one, if appropriate.  Returns the DECL, or an
3730    equivalent one, if it is replaced via a call to duplicate_decls.
3731
3732    If IS_FRIEND is true, DECL is a friend declaration.  */
3733
3734 tree
3735 push_template_decl_real (tree decl, bool is_friend)
3736 {
3737   tree tmpl;
3738   tree args;
3739   tree info;
3740   tree ctx;
3741   int primary;
3742   int is_partial;
3743   int new_template_p = 0;
3744   /* True if the template is a member template, in the sense of
3745      [temp.mem].  */
3746   bool member_template_p = false;
3747
3748   if (decl == error_mark_node)
3749     return decl;
3750
3751   /* See if this is a partial specialization.  */
3752   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3753                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3754                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3755
3756   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3757     is_friend = true;
3758
3759   if (is_friend)
3760     /* For a friend, we want the context of the friend function, not
3761        the type of which it is a friend.  */
3762     ctx = DECL_CONTEXT (decl);
3763   else if (CP_DECL_CONTEXT (decl)
3764            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3765     /* In the case of a virtual function, we want the class in which
3766        it is defined.  */
3767     ctx = CP_DECL_CONTEXT (decl);
3768   else
3769     /* Otherwise, if we're currently defining some class, the DECL
3770        is assumed to be a member of the class.  */
3771     ctx = current_scope ();
3772
3773   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3774     ctx = NULL_TREE;
3775
3776   if (!DECL_CONTEXT (decl))
3777     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3778
3779   /* See if this is a primary template.  */
3780   if (is_friend && ctx)
3781     /* A friend template that specifies a class context, i.e.
3782          template <typename T> friend void A<T>::f();
3783        is not primary.  */
3784     primary = 0;
3785   else
3786     primary = template_parm_scope_p ();
3787
3788   if (primary)
3789     {
3790       if (DECL_CLASS_SCOPE_P (decl))
3791         member_template_p = true;
3792       if (TREE_CODE (decl) == TYPE_DECL
3793           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3794         error ("template class without a name");
3795       else if (TREE_CODE (decl) == FUNCTION_DECL)
3796         {
3797           if (DECL_DESTRUCTOR_P (decl))
3798             {
3799               /* [temp.mem]
3800
3801                  A destructor shall not be a member template.  */
3802               error ("destructor %qD declared as member template", decl);
3803               return error_mark_node;
3804             }
3805           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3806               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3807                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3808                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3809                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3810                       == void_list_node)))
3811             {
3812               /* [basic.stc.dynamic.allocation]
3813
3814                  An allocation function can be a function
3815                  template. ... Template allocation functions shall
3816                  have two or more parameters.  */
3817               error ("invalid template declaration of %qD", decl);
3818               return error_mark_node;
3819             }
3820         }
3821       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3822                && CLASS_TYPE_P (TREE_TYPE (decl)))
3823         /* OK */;
3824       else
3825         {
3826           error ("template declaration of %q#D", decl);
3827           return error_mark_node;
3828         }
3829     }
3830
3831   /* Check to see that the rules regarding the use of default
3832      arguments are not being violated.  */
3833   check_default_tmpl_args (decl, current_template_parms,
3834                            primary, is_partial, /*is_friend_decl=*/0);
3835
3836   /* Ensure that there are no parameter packs in the type of this
3837      declaration that have not been expanded.  */
3838   if (TREE_CODE (decl) == FUNCTION_DECL)
3839     {
3840       /* Check each of the arguments individually to see if there are
3841          any bare parameter packs.  */
3842       tree type = TREE_TYPE (decl);
3843       tree arg = DECL_ARGUMENTS (decl);
3844       tree argtype = TYPE_ARG_TYPES (type);
3845
3846       while (arg && argtype)
3847         {
3848           if (!FUNCTION_PARAMETER_PACK_P (arg)
3849               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
3850             {
3851             /* This is a PARM_DECL that contains unexpanded parameter
3852                packs. We have already complained about this in the
3853                check_for_bare_parameter_packs call, so just replace
3854                these types with ERROR_MARK_NODE.  */
3855               TREE_TYPE (arg) = error_mark_node;
3856               TREE_VALUE (argtype) = error_mark_node;
3857             }
3858
3859           arg = TREE_CHAIN (arg);
3860           argtype = TREE_CHAIN (argtype);
3861         }
3862
3863       /* Check for bare parameter packs in the return type and the
3864          exception specifiers.  */
3865       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
3866         /* Errors were already issued, set return type to int
3867            as the frontend doesn't expect error_mark_node as
3868            the return type.  */
3869         TREE_TYPE (type) = integer_type_node;
3870       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
3871         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
3872     }
3873   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
3874     {
3875       TREE_TYPE (decl) = error_mark_node;
3876       return error_mark_node;
3877     }
3878
3879   if (is_partial)
3880     return process_partial_specialization (decl);
3881
3882   args = current_template_args ();
3883
3884   if (!ctx
3885       || TREE_CODE (ctx) == FUNCTION_DECL
3886       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3887       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3888     {
3889       if (DECL_LANG_SPECIFIC (decl)
3890           && DECL_TEMPLATE_INFO (decl)
3891           && DECL_TI_TEMPLATE (decl))
3892         tmpl = DECL_TI_TEMPLATE (decl);
3893       /* If DECL is a TYPE_DECL for a class-template, then there won't
3894          be DECL_LANG_SPECIFIC.  The information equivalent to
3895          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3896       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3897                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3898                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3899         {
3900           /* Since a template declaration already existed for this
3901              class-type, we must be redeclaring it here.  Make sure
3902              that the redeclaration is valid.  */
3903           redeclare_class_template (TREE_TYPE (decl),
3904                                     current_template_parms);
3905           /* We don't need to create a new TEMPLATE_DECL; just use the
3906              one we already had.  */
3907           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3908         }
3909       else
3910         {
3911           tmpl = build_template_decl (decl, current_template_parms,
3912                                       member_template_p);
3913           new_template_p = 1;
3914
3915           if (DECL_LANG_SPECIFIC (decl)
3916               && DECL_TEMPLATE_SPECIALIZATION (decl))
3917             {
3918               /* A specialization of a member template of a template
3919                  class.  */
3920               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3921               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3922               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3923             }
3924         }
3925     }
3926   else
3927     {
3928       tree a, t, current, parms;
3929       int i;
3930       tree tinfo = get_template_info (decl);
3931
3932       if (!tinfo)
3933         {
3934           error ("template definition of non-template %q#D", decl);
3935           return error_mark_node;
3936         }
3937
3938       tmpl = TI_TEMPLATE (tinfo);
3939
3940       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3941           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3942           && DECL_TEMPLATE_SPECIALIZATION (decl)
3943           && DECL_MEMBER_TEMPLATE_P (tmpl))
3944         {
3945           tree new_tmpl;
3946
3947           /* The declaration is a specialization of a member
3948              template, declared outside the class.  Therefore, the
3949              innermost template arguments will be NULL, so we
3950              replace them with the arguments determined by the
3951              earlier call to check_explicit_specialization.  */
3952           args = DECL_TI_ARGS (decl);
3953
3954           new_tmpl
3955             = build_template_decl (decl, current_template_parms,
3956                                    member_template_p);
3957           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3958           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3959           DECL_TI_TEMPLATE (decl) = new_tmpl;
3960           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3961           DECL_TEMPLATE_INFO (new_tmpl)
3962             = tree_cons (tmpl, args, NULL_TREE);
3963
3964           register_specialization (new_tmpl,
3965                                    most_general_template (tmpl),
3966                                    args,
3967                                    is_friend);
3968           return decl;
3969         }
3970
3971       /* Make sure the template headers we got make sense.  */
3972
3973       parms = DECL_TEMPLATE_PARMS (tmpl);
3974       i = TMPL_PARMS_DEPTH (parms);
3975       if (TMPL_ARGS_DEPTH (args) != i)
3976         {
3977           error ("expected %d levels of template parms for %q#D, got %d",
3978                  i, decl, TMPL_ARGS_DEPTH (args));
3979         }
3980       else
3981         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
3982           {
3983             a = TMPL_ARGS_LEVEL (args, i);
3984             t = INNERMOST_TEMPLATE_PARMS (parms);
3985
3986             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
3987               {
3988                 if (current == decl)
3989                   error ("got %d template parameters for %q#D",
3990                          TREE_VEC_LENGTH (a), decl);
3991                 else
3992                   error ("got %d template parameters for %q#T",
3993                          TREE_VEC_LENGTH (a), current);
3994                 error ("  but %d required", TREE_VEC_LENGTH (t));
3995                 return error_mark_node;
3996               }
3997
3998             if (current == decl)
3999               current = ctx;
4000             else
4001               current = (TYPE_P (current)
4002                          ? TYPE_CONTEXT (current)
4003                          : DECL_CONTEXT (current));
4004           }
4005
4006       /* Check that the parms are used in the appropriate qualifying scopes
4007          in the declarator.  */
4008       if (!comp_template_args
4009           (TI_ARGS (tinfo),
4010            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4011         {
4012           error ("\
4013 template arguments to %qD do not match original template %qD",
4014                  decl, DECL_TEMPLATE_RESULT (tmpl));
4015           if (!uses_template_parms (TI_ARGS (tinfo)))
4016             inform ("use template<> for an explicit specialization");
4017           /* Avoid crash in import_export_decl.  */
4018           DECL_INTERFACE_KNOWN (decl) = 1;
4019           return error_mark_node;
4020         }
4021     }
4022
4023   DECL_TEMPLATE_RESULT (tmpl) = decl;
4024   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4025
4026   /* Push template declarations for global functions and types.  Note
4027      that we do not try to push a global template friend declared in a
4028      template class; such a thing may well depend on the template
4029      parameters of the class.  */
4030   if (new_template_p && !ctx
4031       && !(is_friend && template_class_depth (current_class_type) > 0))
4032     {
4033       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4034       if (tmpl == error_mark_node)
4035         return error_mark_node;
4036
4037       /* Hide template friend classes that haven't been declared yet.  */
4038       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4039         {
4040           DECL_ANTICIPATED (tmpl) = 1;
4041           DECL_FRIEND_P (tmpl) = 1;
4042         }
4043     }
4044
4045   if (primary)
4046     {
4047       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4048       int i;
4049
4050       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4051       if (DECL_CONV_FN_P (tmpl))
4052         {
4053           int depth = TMPL_PARMS_DEPTH (parms);
4054
4055           /* It is a conversion operator. See if the type converted to
4056              depends on innermost template operands.  */
4057
4058           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4059                                          depth))
4060             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4061         }
4062
4063       /* Give template template parms a DECL_CONTEXT of the template
4064          for which they are a parameter.  */
4065       parms = INNERMOST_TEMPLATE_PARMS (parms);
4066       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4067         {
4068           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4069           if (TREE_CODE (parm) == TEMPLATE_DECL)
4070             DECL_CONTEXT (parm) = tmpl;
4071         }
4072     }
4073
4074   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4075      back to its most general template.  If TMPL is a specialization,
4076      ARGS may only have the innermost set of arguments.  Add the missing
4077      argument levels if necessary.  */
4078   if (DECL_TEMPLATE_INFO (tmpl))
4079     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4080
4081   info = tree_cons (tmpl, args, NULL_TREE);
4082
4083   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4084     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4085   else if (DECL_LANG_SPECIFIC (decl))
4086     DECL_TEMPLATE_INFO (decl) = info;
4087
4088   return DECL_TEMPLATE_RESULT (tmpl);
4089 }
4090
4091 tree
4092 push_template_decl (tree decl)
4093 {
4094   return push_template_decl_real (decl, false);
4095 }
4096
4097 /* Called when a class template TYPE is redeclared with the indicated
4098    template PARMS, e.g.:
4099
4100      template <class T> struct S;
4101      template <class T> struct S {};  */
4102
4103 bool
4104 redeclare_class_template (tree type, tree parms)
4105 {
4106   tree tmpl;
4107   tree tmpl_parms;
4108   int i;
4109
4110   if (!TYPE_TEMPLATE_INFO (type))
4111     {
4112       error ("%qT is not a template type", type);
4113       return false;
4114     }
4115
4116   tmpl = TYPE_TI_TEMPLATE (type);
4117   if (!PRIMARY_TEMPLATE_P (tmpl))
4118     /* The type is nested in some template class.  Nothing to worry
4119        about here; there are no new template parameters for the nested
4120        type.  */
4121     return true;
4122
4123   if (!parms)
4124     {
4125       error ("template specifiers not specified in declaration of %qD",
4126              tmpl);
4127       return false;
4128     }
4129
4130   parms = INNERMOST_TEMPLATE_PARMS (parms);
4131   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4132
4133   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4134     {
4135       error ("redeclared with %d template parameter(s)", 
4136              TREE_VEC_LENGTH (parms));
4137       inform ("previous declaration %q+D used %d template parameter(s)", 
4138              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4139       return false;
4140     }
4141
4142   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4143     {
4144       tree tmpl_parm;
4145       tree parm;
4146       tree tmpl_default;
4147       tree parm_default;
4148
4149       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4150           || TREE_VEC_ELT (parms, i) == error_mark_node)
4151         continue;
4152
4153       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4154       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4155       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4156       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4157
4158       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4159          TEMPLATE_DECL.  */
4160       if (tmpl_parm != error_mark_node
4161           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4162               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4163                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4164               || (TREE_CODE (tmpl_parm) != PARM_DECL
4165                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4166                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4167               || (TREE_CODE (tmpl_parm) == PARM_DECL
4168                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4169                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4170         {
4171           error ("template parameter %q+#D", tmpl_parm);
4172           error ("redeclared here as %q#D", parm);
4173           return false;
4174         }
4175
4176       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4177         {
4178           /* We have in [temp.param]:
4179
4180              A template-parameter may not be given default arguments
4181              by two different declarations in the same scope.  */
4182           error ("redefinition of default argument for %q#D", parm);
4183           inform ("%Joriginal definition appeared here", tmpl_parm);
4184           return false;
4185         }
4186
4187       if (parm_default != NULL_TREE)
4188         /* Update the previous template parameters (which are the ones
4189            that will really count) with the new default value.  */
4190         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4191       else if (tmpl_default != NULL_TREE)
4192         /* Update the new parameters, too; they'll be used as the
4193            parameters for any members.  */
4194         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4195     }
4196
4197     return true;
4198 }
4199
4200 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4201    (possibly simplified) expression.  */
4202
4203 tree
4204 fold_non_dependent_expr (tree expr)
4205 {
4206   if (expr == NULL_TREE)
4207     return NULL_TREE;
4208
4209   /* If we're in a template, but EXPR isn't value dependent, simplify
4210      it.  We're supposed to treat:
4211
4212        template <typename T> void f(T[1 + 1]);
4213        template <typename T> void f(T[2]);
4214
4215      as two declarations of the same function, for example.  */
4216   if (processing_template_decl
4217       && !type_dependent_expression_p (expr)
4218       && !value_dependent_expression_p (expr))
4219     {
4220       HOST_WIDE_INT saved_processing_template_decl;
4221
4222       saved_processing_template_decl = processing_template_decl;
4223       processing_template_decl = 0;
4224       expr = tsubst_copy_and_build (expr,
4225                                     /*args=*/NULL_TREE,
4226                                     tf_error,
4227                                     /*in_decl=*/NULL_TREE,
4228                                     /*function_p=*/false,
4229                                     /*integral_constant_expression_p=*/true);
4230       processing_template_decl = saved_processing_template_decl;
4231     }
4232   return expr;
4233 }
4234
4235 /* EXPR is an expression which is used in a constant-expression context.
4236    For instance, it could be a VAR_DECL with a constant initializer.
4237    Extract the innest constant expression.
4238
4239    This is basically a more powerful version of
4240    integral_constant_value, which can be used also in templates where
4241    initializers can maintain a syntactic rather than semantic form
4242    (even if they are non-dependent, for access-checking purposes).  */
4243
4244 static tree
4245 fold_decl_constant_value (tree expr)
4246 {
4247   tree const_expr = expr;
4248   do
4249     {
4250       expr = fold_non_dependent_expr (const_expr);
4251       const_expr = integral_constant_value (expr);
4252     }
4253   while (expr != const_expr);
4254
4255   return expr;
4256 }
4257
4258 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4259    must be a function or a pointer-to-function type, as specified
4260    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4261    and check that the resulting function has external linkage.  */
4262
4263 static tree
4264 convert_nontype_argument_function (tree type, tree expr)
4265 {
4266   tree fns = expr;
4267   tree fn, fn_no_ptr;
4268
4269   fn = instantiate_type (type, fns, tf_none);
4270   if (fn == error_mark_node)
4271     return error_mark_node;
4272
4273   fn_no_ptr = fn;
4274   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4275     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4276   if (TREE_CODE (fn_no_ptr) == BASELINK)
4277     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4278  
4279   /* [temp.arg.nontype]/1
4280
4281      A template-argument for a non-type, non-template template-parameter
4282      shall be one of:
4283      [...]
4284      -- the address of an object or function with external linkage.  */
4285   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4286     {
4287       error ("%qE is not a valid template argument for type %qT "
4288              "because function %qD has not external linkage",
4289              expr, type, fn_no_ptr);
4290       return NULL_TREE;
4291     }
4292
4293   return fn;
4294 }
4295
4296 /* Attempt to convert the non-type template parameter EXPR to the
4297    indicated TYPE.  If the conversion is successful, return the
4298    converted value.  If the conversion is unsuccessful, return
4299    NULL_TREE if we issued an error message, or error_mark_node if we
4300    did not.  We issue error messages for out-and-out bad template
4301    parameters, but not simply because the conversion failed, since we
4302    might be just trying to do argument deduction.  Both TYPE and EXPR
4303    must be non-dependent.
4304
4305    The conversion follows the special rules described in
4306    [temp.arg.nontype], and it is much more strict than an implicit
4307    conversion.
4308
4309    This function is called twice for each template argument (see
4310    lookup_template_class for a more accurate description of this
4311    problem). This means that we need to handle expressions which
4312    are not valid in a C++ source, but can be created from the
4313    first call (for instance, casts to perform conversions). These
4314    hacks can go away after we fix the double coercion problem.  */
4315
4316 static tree
4317 convert_nontype_argument (tree type, tree expr)
4318 {
4319   tree expr_type;
4320
4321   /* Detect immediately string literals as invalid non-type argument.
4322      This special-case is not needed for correctness (we would easily
4323      catch this later), but only to provide better diagnostic for this
4324      common user mistake. As suggested by DR 100, we do not mention
4325      linkage issues in the diagnostic as this is not the point.  */
4326   if (TREE_CODE (expr) == STRING_CST)
4327     {
4328       error ("%qE is not a valid template argument for type %qT "
4329              "because string literals can never be used in this context",
4330              expr, type);
4331       return NULL_TREE;
4332     }
4333
4334   /* If we are in a template, EXPR may be non-dependent, but still
4335      have a syntactic, rather than semantic, form.  For example, EXPR
4336      might be a SCOPE_REF, rather than the VAR_DECL to which the
4337      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4338      so that access checking can be performed when the template is
4339      instantiated -- but here we need the resolved form so that we can
4340      convert the argument.  */
4341   expr = fold_non_dependent_expr (expr);
4342   if (error_operand_p (expr))
4343     return error_mark_node;
4344   expr_type = TREE_TYPE (expr);
4345
4346   /* HACK: Due to double coercion, we can get a
4347      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4348      which is the tree that we built on the first call (see
4349      below when coercing to reference to object or to reference to
4350      function). We just strip everything and get to the arg.
4351      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4352      for examples.  */
4353   if (TREE_CODE (expr) == NOP_EXPR)
4354     {
4355       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4356         {
4357           /* ??? Maybe we could use convert_from_reference here, but we
4358              would need to relax its constraints because the NOP_EXPR
4359              could actually change the type to something more cv-qualified,
4360              and this is not folded by convert_from_reference.  */
4361           tree addr = TREE_OPERAND (expr, 0);
4362           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4363           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4364           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4365           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4366                       (TREE_TYPE (expr_type),
4367                        TREE_TYPE (TREE_TYPE (addr))));
4368
4369           expr = TREE_OPERAND (addr, 0);
4370           expr_type = TREE_TYPE (expr);
4371         }
4372
4373       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4374          parameter is a pointer to object, through decay and
4375          qualification conversion. Let's strip everything.  */
4376       else if (TYPE_PTROBV_P (type))
4377         {
4378           STRIP_NOPS (expr);
4379           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4380           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4381           /* Skip the ADDR_EXPR only if it is part of the decay for
4382              an array. Otherwise, it is part of the original argument
4383              in the source code.  */
4384           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4385             expr = TREE_OPERAND (expr, 0);
4386           expr_type = TREE_TYPE (expr);
4387         }
4388     }
4389
4390   /* [temp.arg.nontype]/5, bullet 1
4391
4392      For a non-type template-parameter of integral or enumeration type,
4393      integral promotions (_conv.prom_) and integral conversions
4394      (_conv.integral_) are applied.  */
4395   if (INTEGRAL_TYPE_P (type))
4396     {
4397       if (!INTEGRAL_TYPE_P (expr_type))
4398         return error_mark_node;
4399
4400       expr = fold_decl_constant_value (expr);
4401       /* Notice that there are constant expressions like '4 % 0' which
4402          do not fold into integer constants.  */
4403       if (TREE_CODE (expr) != INTEGER_CST)
4404         {
4405           error ("%qE is not a valid template argument for type %qT "
4406                  "because it is a non-constant expression", expr, type);
4407           return NULL_TREE;
4408         }
4409
4410       /* At this point, an implicit conversion does what we want,
4411          because we already know that the expression is of integral
4412          type.  */
4413       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4414       if (expr == error_mark_node)
4415         return error_mark_node;
4416
4417       /* Conversion was allowed: fold it to a bare integer constant.  */
4418       expr = fold (expr);
4419     }
4420   /* [temp.arg.nontype]/5, bullet 2
4421
4422      For a non-type template-parameter of type pointer to object,
4423      qualification conversions (_conv.qual_) and the array-to-pointer
4424      conversion (_conv.array_) are applied.  */
4425   else if (TYPE_PTROBV_P (type))
4426     {
4427       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4428
4429          A template-argument for a non-type, non-template template-parameter
4430          shall be one of: [...]
4431
4432          -- the name of a non-type template-parameter;
4433          -- the address of an object or function with external linkage, [...]
4434             expressed as "& id-expression" where the & is optional if the name
4435             refers to a function or array, or if the corresponding
4436             template-parameter is a reference.
4437
4438         Here, we do not care about functions, as they are invalid anyway
4439         for a parameter of type pointer-to-object.  */
4440
4441       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4442         /* Non-type template parameters are OK.  */
4443         ;
4444       else if (TREE_CODE (expr) != ADDR_EXPR
4445                && TREE_CODE (expr_type) != ARRAY_TYPE)
4446         {
4447           if (TREE_CODE (expr) == VAR_DECL)
4448             {
4449               error ("%qD is not a valid template argument "
4450                      "because %qD is a variable, not the address of "
4451                      "a variable",
4452                      expr, expr);
4453               return NULL_TREE;
4454             }
4455           /* Other values, like integer constants, might be valid
4456              non-type arguments of some other type.  */
4457           return error_mark_node;
4458         }
4459       else
4460         {
4461           tree decl;
4462
4463           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4464                   ? TREE_OPERAND (expr, 0) : expr);
4465           if (TREE_CODE (decl) != VAR_DECL)
4466             {
4467               error ("%qE is not a valid template argument of type %qT "
4468                      "because %qE is not a variable",
4469                      expr, type, decl);
4470               return NULL_TREE;
4471             }
4472           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4473             {
4474               error ("%qE is not a valid template argument of type %qT "
4475                      "because %qD does not have external linkage",
4476                      expr, type, decl);
4477               return NULL_TREE;
4478             }
4479         }
4480
4481       expr = decay_conversion (expr);
4482       if (expr == error_mark_node)
4483         return error_mark_node;
4484
4485       expr = perform_qualification_conversions (type, expr);
4486       if (expr == error_mark_node)
4487         return error_mark_node;
4488     }
4489   /* [temp.arg.nontype]/5, bullet 3
4490
4491      For a non-type template-parameter of type reference to object, no
4492      conversions apply. The type referred to by the reference may be more
4493      cv-qualified than the (otherwise identical) type of the
4494      template-argument. The template-parameter is bound directly to the
4495      template-argument, which must be an lvalue.  */
4496   else if (TYPE_REF_OBJ_P (type))
4497     {
4498       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4499                                                       expr_type))
4500         return error_mark_node;
4501
4502       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4503         {
4504           error ("%qE is not a valid template argument for type %qT "
4505                  "because of conflicts in cv-qualification", expr, type);
4506           return NULL_TREE;
4507         }
4508
4509       if (!real_lvalue_p (expr))
4510         {
4511           error ("%qE is not a valid template argument for type %qT "
4512                  "because it is not an lvalue", expr, type);
4513           return NULL_TREE;
4514         }
4515
4516       /* [temp.arg.nontype]/1
4517
4518          A template-argument for a non-type, non-template template-parameter
4519          shall be one of: [...]
4520
4521          -- the address of an object or function with external linkage.  */
4522       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4523         {
4524           error ("%qE is not a valid template argument for type %qT "
4525                  "because object %qD has not external linkage",
4526                  expr, type, expr);
4527           return NULL_TREE;
4528         }
4529
4530       expr = build_nop (type, build_address (expr));
4531     }
4532   /* [temp.arg.nontype]/5, bullet 4
4533
4534      For a non-type template-parameter of type pointer to function, only
4535      the function-to-pointer conversion (_conv.func_) is applied. If the
4536      template-argument represents a set of overloaded functions (or a
4537      pointer to such), the matching function is selected from the set
4538      (_over.over_).  */
4539   else if (TYPE_PTRFN_P (type))
4540     {
4541       /* If the argument is a template-id, we might not have enough
4542          context information to decay the pointer.  */
4543       if (!type_unknown_p (expr_type))
4544         {
4545           expr = decay_conversion (expr);
4546           if (expr == error_mark_node)
4547             return error_mark_node;
4548         }
4549
4550       expr = convert_nontype_argument_function (type, expr);
4551       if (!expr || expr == error_mark_node)
4552         return expr;
4553     }
4554   /* [temp.arg.nontype]/5, bullet 5
4555
4556      For a non-type template-parameter of type reference to function, no
4557      conversions apply. If the template-argument represents a set of
4558      overloaded functions, the matching function is selected from the set
4559      (_over.over_).  */
4560   else if (TYPE_REFFN_P (type))
4561     {
4562       if (TREE_CODE (expr) == ADDR_EXPR)
4563         {
4564           error ("%qE is not a valid template argument for type %qT "
4565                  "because it is a pointer", expr, type);
4566           inform ("try using %qE instead", TREE_OPERAND (expr, 0));
4567           return NULL_TREE;
4568         }
4569
4570       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4571       if (!expr || expr == error_mark_node)
4572         return expr;
4573
4574       expr = build_nop (type, build_address (expr));
4575     }
4576   /* [temp.arg.nontype]/5, bullet 6
4577
4578      For a non-type template-parameter of type pointer to member function,
4579      no conversions apply. If the template-argument represents a set of
4580      overloaded member functions, the matching member function is selected
4581      from the set (_over.over_).  */
4582   else if (TYPE_PTRMEMFUNC_P (type))
4583     {
4584       expr = instantiate_type (type, expr, tf_none);
4585       if (expr == error_mark_node)
4586         return error_mark_node;
4587
4588       /* There is no way to disable standard conversions in
4589          resolve_address_of_overloaded_function (called by
4590          instantiate_type). It is possible that the call succeeded by
4591          converting &B::I to &D::I (where B is a base of D), so we need
4592          to reject this conversion here.
4593
4594          Actually, even if there was a way to disable standard conversions,
4595          it would still be better to reject them here so that we can
4596          provide a superior diagnostic.  */
4597       if (!same_type_p (TREE_TYPE (expr), type))
4598         {
4599           /* Make sure we are just one standard conversion off.  */
4600           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4601           error ("%qE is not a valid template argument for type %qT "
4602                  "because it is of type %qT", expr, type,
4603                  TREE_TYPE (expr));
4604           inform ("standard conversions are not allowed in this context");
4605           return NULL_TREE;
4606         }
4607     }
4608   /* [temp.arg.nontype]/5, bullet 7
4609
4610      For a non-type template-parameter of type pointer to data member,
4611      qualification conversions (_conv.qual_) are applied.  */
4612   else if (TYPE_PTRMEM_P (type))
4613     {
4614       expr = perform_qualification_conversions (type, expr);
4615       if (expr == error_mark_node)
4616         return expr;
4617     }
4618   /* A template non-type parameter must be one of the above.  */
4619   else
4620     gcc_unreachable ();
4621
4622   /* Sanity check: did we actually convert the argument to the
4623      right type?  */
4624   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4625   return expr;
4626 }
4627
4628 /* Subroutine of coerce_template_template_parms, which returns 1 if
4629    PARM_PARM and ARG_PARM match using the rule for the template
4630    parameters of template template parameters. Both PARM and ARG are
4631    template parameters; the rest of the arguments are the same as for
4632    coerce_template_template_parms.
4633  */
4634 static int
4635 coerce_template_template_parm (tree parm,
4636                               tree arg,
4637                               tsubst_flags_t complain,
4638                               tree in_decl,
4639                               tree outer_args)
4640 {
4641   if (arg == NULL_TREE || arg == error_mark_node
4642       || parm == NULL_TREE || parm == error_mark_node)
4643     return 0;
4644   
4645   if (TREE_CODE (arg) != TREE_CODE (parm))
4646     return 0;
4647   
4648   switch (TREE_CODE (parm))
4649     {
4650     case TEMPLATE_DECL:
4651       /* We encounter instantiations of templates like
4652          template <template <template <class> class> class TT>
4653          class C;  */
4654       {
4655         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4656         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4657         
4658         if (!coerce_template_template_parms
4659             (parmparm, argparm, complain, in_decl, outer_args))
4660           return 0;
4661       }
4662       /* Fall through.  */
4663       
4664     case TYPE_DECL:
4665       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
4666           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4667         /* Argument is a parameter pack but parameter is not.  */
4668         return 0;
4669       break;
4670       
4671     case PARM_DECL:
4672       /* The tsubst call is used to handle cases such as
4673          
4674            template <int> class C {};
4675            template <class T, template <T> class TT> class D {};
4676            D<int, C> d;
4677
4678          i.e. the parameter list of TT depends on earlier parameters.  */
4679       if (!dependent_type_p (TREE_TYPE (arg))
4680           && !same_type_p
4681                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4682                  TREE_TYPE (arg)))
4683         return 0;
4684       
4685       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
4686           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4687         /* Argument is a parameter pack but parameter is not.  */
4688         return 0;
4689       
4690       break;
4691
4692     default:
4693       gcc_unreachable ();
4694     }
4695
4696   return 1;
4697 }
4698
4699
4700 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4701    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4702    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4703    or PARM_DECL.
4704
4705    Consider the example:
4706      template <class T> class A;
4707      template<template <class U> class TT> class B;
4708
4709    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4710    the parameters to A, and OUTER_ARGS contains A.  */
4711
4712 static int
4713 coerce_template_template_parms (tree parm_parms,
4714                                 tree arg_parms,
4715                                 tsubst_flags_t complain,
4716                                 tree in_decl,
4717                                 tree outer_args)
4718 {
4719   int nparms, nargs, i;
4720   tree parm, arg;
4721   int variadic_p = 0;
4722
4723   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4724   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4725
4726   nparms = TREE_VEC_LENGTH (parm_parms);
4727   nargs = TREE_VEC_LENGTH (arg_parms);
4728
4729   /* Determine whether we have a parameter pack at the end of the
4730      template template parameter's template parameter list.  */
4731   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
4732     {
4733       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
4734       
4735       switch (TREE_CODE (parm))
4736         {
4737         case TEMPLATE_DECL:
4738         case TYPE_DECL:
4739           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4740             variadic_p = 1;
4741           break;
4742           
4743         case PARM_DECL:
4744           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4745             variadic_p = 1;
4746           break;
4747           
4748         default:
4749           gcc_unreachable ();
4750         }
4751     }
4752  
4753   if (nargs != nparms
4754       && !(variadic_p && nargs >= nparms - 1))
4755     return 0;
4756
4757   /* Check all of the template parameters except the parameter pack at
4758      the end (if any).  */
4759   for (i = 0; i < nparms - variadic_p; ++i)
4760     {
4761       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4762           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4763         continue;
4764
4765       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4766       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4767
4768       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4769                                           outer_args))
4770         return 0;
4771
4772     }
4773
4774   if (variadic_p)
4775     {
4776       /* Check each of the template parameters in the template
4777          argument against the template parameter pack at the end of
4778          the template template parameter.  */
4779       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
4780         return 0;
4781
4782       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4783
4784       for (; i < nargs; ++i)
4785         {
4786           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4787             continue;
4788  
4789           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4790  
4791           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4792                                               outer_args))
4793             return 0;
4794         }
4795     }
4796
4797   return 1;
4798 }
4799
4800 /* Verifies that the deduced template arguments (in TARGS) for the
4801    template template parameters (in TPARMS) represent valid bindings,
4802    by comparing the template parameter list of each template argument
4803    to the template parameter list of its corresponding template
4804    template parameter, in accordance with DR150. This
4805    routine can only be called after all template arguments have been
4806    deduced. It will return TRUE if all of the template template
4807    parameter bindings are okay, FALSE otherwise.  */
4808 bool 
4809 template_template_parm_bindings_ok_p (tree tparms, tree targs)
4810 {
4811   int i, ntparms = TREE_VEC_LENGTH (tparms);
4812   bool ret = true;
4813
4814   /* We're dealing with template parms in this process.  */
4815   ++processing_template_decl;
4816
4817   targs = INNERMOST_TEMPLATE_ARGS (targs);
4818
4819   for (i = 0; i < ntparms; ++i)
4820     {
4821       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
4822       tree targ = TREE_VEC_ELT (targs, i);
4823
4824       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
4825         {
4826           tree packed_args = NULL_TREE;
4827           int idx, len = 1;
4828
4829           if (ARGUMENT_PACK_P (targ))
4830             {
4831               /* Look inside the argument pack.  */
4832               packed_args = ARGUMENT_PACK_ARGS (targ);
4833               len = TREE_VEC_LENGTH (packed_args);
4834             }
4835
4836           for (idx = 0; idx < len; ++idx)
4837             {
4838               tree targ_parms = NULL_TREE;
4839
4840               if (packed_args)
4841                 /* Extract the next argument from the argument
4842                    pack.  */
4843                 targ = TREE_VEC_ELT (packed_args, idx);
4844
4845               if (PACK_EXPANSION_P (targ))
4846                 /* Look at the pattern of the pack expansion.  */
4847                 targ = PACK_EXPANSION_PATTERN (targ);
4848
4849               /* Extract the template parameters from the template
4850                  argument.  */
4851               if (TREE_CODE (targ) == TEMPLATE_DECL)
4852                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
4853               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
4854                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
4855
4856               /* Verify that we can coerce the template template
4857                  parameters from the template argument to the template
4858                  parameter.  This requires an exact match.  */
4859               if (targ_parms
4860                   && !coerce_template_template_parms
4861                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
4862                         targ_parms,
4863                         tf_none,
4864                         tparm,
4865                         targs))
4866                 {
4867                   ret = false;
4868                   goto out;
4869                 }
4870             }
4871         }
4872     }
4873
4874  out:
4875
4876   --processing_template_decl;
4877   return ret;
4878 }
4879
4880 /* Convert the indicated template ARG as necessary to match the
4881    indicated template PARM.  Returns the converted ARG, or
4882    error_mark_node if the conversion was unsuccessful.  Error and
4883    warning messages are issued under control of COMPLAIN.  This
4884    conversion is for the Ith parameter in the parameter list.  ARGS is
4885    the full set of template arguments deduced so far.  */
4886
4887 static tree
4888 convert_template_argument (tree parm,
4889                            tree arg,
4890                            tree args,
4891                            tsubst_flags_t complain,
4892                            int i,
4893                            tree in_decl)
4894 {
4895   tree orig_arg;
4896   tree val;
4897   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4898
4899   if (TREE_CODE (arg) == TREE_LIST
4900       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4901     {
4902       /* The template argument was the name of some
4903          member function.  That's usually
4904          invalid, but static members are OK.  In any
4905          case, grab the underlying fields/functions
4906          and issue an error later if required.  */
4907       orig_arg = TREE_VALUE (arg);
4908       TREE_TYPE (arg) = unknown_type_node;
4909     }
4910
4911   orig_arg = arg;
4912
4913   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4914   requires_type = (TREE_CODE (parm) == TYPE_DECL
4915                    || requires_tmpl_type);
4916
4917   /* When determining whether an argument pack expansion is a template,
4918      look at the pattern.  */
4919   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
4920     arg = PACK_EXPANSION_PATTERN (arg);
4921
4922   is_tmpl_type = 
4923     ((TREE_CODE (arg) == TEMPLATE_DECL
4924       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
4925      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4926      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
4927
4928   if (is_tmpl_type
4929       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4930           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4931     arg = TYPE_STUB_DECL (arg);
4932
4933   is_type = TYPE_P (arg) || is_tmpl_type;
4934
4935   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4936       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4937     {
4938       pedwarn ("to refer to a type member of a template parameter, "
4939                "use %<typename %E%>", orig_arg);
4940
4941       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
4942                                      TREE_OPERAND (arg, 1),
4943                                      typename_type,
4944                                      complain & tf_error);
4945       arg = orig_arg;
4946       is_type = 1;
4947     }
4948   if (is_type != requires_type)
4949     {
4950       if (in_decl)
4951         {
4952           if (complain & tf_error)
4953             {
4954               error ("type/value mismatch at argument %d in template "
4955                      "parameter list for %qD",
4956                      i + 1, in_decl);
4957               if (is_type)
4958                 error ("  expected a constant of type %qT, got %qT",
4959                        TREE_TYPE (parm),
4960                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
4961               else if (requires_tmpl_type)
4962                 error ("  expected a class template, got %qE", orig_arg);
4963               else
4964                 error ("  expected a type, got %qE", orig_arg);
4965             }
4966         }
4967       return error_mark_node;
4968     }
4969   if (is_tmpl_type ^ requires_tmpl_type)
4970     {
4971       if (in_decl && (complain & tf_error))
4972         {
4973           error ("type/value mismatch at argument %d in template "
4974                  "parameter list for %qD",
4975                  i + 1, in_decl);
4976           if (is_tmpl_type)
4977             error ("  expected a type, got %qT", DECL_NAME (arg));
4978           else
4979             error ("  expected a class template, got %qT", orig_arg);
4980         }
4981       return error_mark_node;
4982     }
4983
4984   if (is_type)
4985     {
4986       if (requires_tmpl_type)
4987         {
4988           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
4989             /* The number of argument required is not known yet.
4990                Just accept it for now.  */
4991             val = TREE_TYPE (arg);
4992           else
4993             {
4994               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4995               tree argparm;
4996
4997               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4998
4999               if (coerce_template_template_parms (parmparm, argparm,
5000                                                   complain, in_decl,
5001                                                   args))
5002                 {
5003                   val = orig_arg;
5004
5005                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5006                      TEMPLATE_DECL.  */
5007                   if (val != error_mark_node)
5008                     {
5009                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5010                         val = TREE_TYPE (val);
5011                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5012                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5013                         {
5014                           val = TREE_TYPE (arg);
5015                           val = make_pack_expansion (val);
5016                         }
5017                     }
5018                 }
5019               else
5020                 {
5021                   if (in_decl && (complain & tf_error))
5022                     {
5023                       error ("type/value mismatch at argument %d in "
5024                              "template parameter list for %qD",
5025                              i + 1, in_decl);
5026                       error ("  expected a template of type %qD, got %qD",
5027                              parm, orig_arg);
5028                     }
5029
5030                   val = error_mark_node;
5031                 }
5032             }
5033         }
5034       else
5035         val = orig_arg;
5036       /* We only form one instance of each template specialization.
5037          Therefore, if we use a non-canonical variant (i.e., a
5038          typedef), any future messages referring to the type will use
5039          the typedef, which is confusing if those future uses do not
5040          themselves also use the typedef.  */
5041       if (TYPE_P (val))
5042         val = canonical_type_variant (val);
5043     }
5044   else
5045     {
5046       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5047
5048       if (invalid_nontype_parm_type_p (t, complain))
5049         return error_mark_node;
5050
5051       if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5052         /* We used to call digest_init here.  However, digest_init
5053            will report errors, which we don't want when complain
5054            is zero.  More importantly, digest_init will try too
5055            hard to convert things: for example, `0' should not be
5056            converted to pointer type at this point according to
5057            the standard.  Accepting this is not merely an
5058            extension, since deciding whether or not these
5059            conversions can occur is part of determining which
5060            function template to call, or whether a given explicit
5061            argument specification is valid.  */
5062         val = convert_nontype_argument (t, orig_arg);
5063       else
5064         val = orig_arg;
5065
5066       if (val == NULL_TREE)
5067         val = error_mark_node;
5068       else if (val == error_mark_node && (complain & tf_error))
5069         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5070     }
5071
5072   return val;
5073 }
5074
5075 /* Coerces the remaining template arguments in INNER_ARGS (from
5076    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5077    Returns the coerced argument pack. PARM_IDX is the position of this
5078    parameter in the template parameter list. ARGS is the original
5079    template argument list.  */
5080 static tree
5081 coerce_template_parameter_pack (tree parms,
5082                                 int parm_idx,
5083                                 tree args,
5084                                 tree inner_args,
5085                                 int arg_idx,
5086                                 tree new_args,
5087                                 int* lost,
5088                                 tree in_decl,
5089                                 tsubst_flags_t complain)
5090 {
5091   tree parm = TREE_VEC_ELT (parms, parm_idx);
5092   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5093   tree packed_args;
5094   tree argument_pack;
5095   tree packed_types = NULL_TREE;
5096
5097   if (arg_idx > nargs)
5098     arg_idx = nargs;
5099
5100   packed_args = make_tree_vec (nargs - arg_idx);
5101
5102   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5103       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5104     {
5105       /* When the template parameter is a non-type template
5106          parameter pack whose type uses parameter packs, we need
5107          to look at each of the template arguments
5108          separately. Build a vector of the types for these
5109          non-type template parameters in PACKED_TYPES.  */
5110       tree expansion 
5111         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5112       packed_types = tsubst_pack_expansion (expansion, args,
5113                                             complain, in_decl);
5114
5115       if (packed_types == error_mark_node)
5116         return error_mark_node;
5117
5118       /* Check that we have the right number of arguments.  */
5119       if (arg_idx < nargs
5120           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5121           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5122         {
5123           int needed_parms 
5124             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5125           error ("wrong number of template arguments (%d, should be %d)",
5126                  nargs, needed_parms);
5127           return error_mark_node;
5128         }
5129
5130       /* If we aren't able to check the actual arguments now
5131          (because they haven't been expanded yet), we can at least
5132          verify that all of the types used for the non-type
5133          template parameter pack are, in fact, valid for non-type
5134          template parameters.  */
5135       if (arg_idx < nargs 
5136           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5137         {
5138           int j, len = TREE_VEC_LENGTH (packed_types);
5139           for (j = 0; j < len; ++j)
5140             {
5141               tree t = TREE_VEC_ELT (packed_types, j);
5142               if (invalid_nontype_parm_type_p (t, complain))
5143                 return error_mark_node;
5144             }
5145         }
5146     }
5147
5148   /* Convert the remaining arguments, which will be a part of the
5149      parameter pack "parm".  */
5150   for (; arg_idx < nargs; ++arg_idx)
5151     {
5152       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5153       tree actual_parm = TREE_VALUE (parm);
5154
5155       if (packed_types && !PACK_EXPANSION_P (arg))
5156         {
5157           /* When we have a vector of types (corresponding to the
5158              non-type template parameter pack that uses parameter
5159              packs in its type, as mention above), and the
5160              argument is not an expansion (which expands to a
5161              currently unknown number of arguments), clone the
5162              parm and give it the next type in PACKED_TYPES.  */
5163           actual_parm = copy_node (actual_parm);
5164           TREE_TYPE (actual_parm) = 
5165             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5166         }
5167
5168       if (arg != error_mark_node)
5169         arg = convert_template_argument (actual_parm, 
5170                                          arg, new_args, complain, parm_idx,
5171                                          in_decl);
5172       if (arg == error_mark_node)
5173         (*lost)++;
5174       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5175     }
5176
5177   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5178       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5179     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5180   else
5181     {
5182       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5183       TREE_TYPE (argument_pack) 
5184         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5185       TREE_CONSTANT (argument_pack) = 1;
5186     }
5187
5188   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5189   return argument_pack;
5190 }
5191
5192 /* Convert all template arguments to their appropriate types, and
5193    return a vector containing the innermost resulting template
5194    arguments.  If any error occurs, return error_mark_node. Error and
5195    warning messages are issued under control of COMPLAIN.
5196
5197    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5198    for arguments not specified in ARGS.  Otherwise, if
5199    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5200    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5201    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5202    ARGS.  */
5203
5204 static tree
5205 coerce_template_parms (tree parms,
5206                        tree args,
5207                        tree in_decl,
5208                        tsubst_flags_t complain,
5209                        bool require_all_args,
5210                        bool use_default_args)
5211 {
5212   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5213   tree inner_args;
5214   tree new_args;
5215   tree new_inner_args;
5216   bool saved_skip_evaluation;
5217
5218   /* When used as a boolean value, indicates whether this is a
5219      variadic template parameter list. Since it's an int, we can also
5220      subtract it from nparms to get the number of non-variadic
5221      parameters.  */
5222   int variadic_p = 0;
5223
5224   inner_args 
5225     = expand_template_argument_pack (INNERMOST_TEMPLATE_ARGS (args));
5226
5227   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5228   nparms = TREE_VEC_LENGTH (parms);
5229
5230   /* Determine if there are any parameter packs.  */
5231   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5232     {
5233       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5234       if (template_parameter_pack_p (tparm))
5235         {
5236           variadic_p = 1;
5237           break;
5238         }
5239     }
5240
5241   if ((nargs > nparms - variadic_p && !variadic_p)
5242       || (nargs < nparms - variadic_p
5243           && require_all_args
5244           && (!use_default_args
5245               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5246                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5247     {
5248       if (complain & tf_error)
5249         {
5250           const char *or_more = "";
5251           if (variadic_p)
5252             {
5253               or_more = " or more";
5254               --nparms;
5255             }
5256
5257           error ("wrong number of template arguments (%d, should be %d%s)",
5258                  nargs, nparms, or_more);
5259
5260           if (in_decl)
5261             error ("provided for %q+D", in_decl);
5262         }
5263
5264       return error_mark_node;
5265     }
5266
5267   /* We need to evaluate the template arguments, even though this
5268      template-id may be nested within a "sizeof".  */
5269   saved_skip_evaluation = skip_evaluation;
5270   skip_evaluation = false;
5271   new_inner_args = make_tree_vec (nparms);
5272   new_args = add_outermost_template_args (args, new_inner_args);
5273   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5274     {
5275       tree arg;
5276       tree parm;
5277
5278       /* Get the Ith template parameter.  */
5279       parm = TREE_VEC_ELT (parms, parm_idx);
5280  
5281       if (parm == error_mark_node)
5282       {
5283         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5284         continue;
5285       }
5286
5287       /* Calculate the next argument.  */
5288       if (template_parameter_pack_p (TREE_VALUE (parm)))
5289         {
5290           /* All remaining arguments will be placed in the
5291              template parameter pack PARM.  */
5292           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5293                                                 inner_args, arg_idx,
5294                                                 new_args, &lost,
5295                                                 in_decl, complain);
5296           
5297           /* Store this argument.  */
5298           if (arg == error_mark_node)
5299             lost++;
5300           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5301
5302           /* We are done with all of the arguments.  */
5303           arg_idx = nargs;
5304
5305           continue;
5306         }
5307       else if (arg_idx < nargs)
5308         {
5309           arg = TREE_VEC_ELT (inner_args, arg_idx);
5310
5311           if (arg && PACK_EXPANSION_P (arg))
5312             {
5313               if (complain & tf_error)
5314                 {
5315                   /* If ARG is a pack expansion, but PARM is not a
5316                      template parameter pack (if it were, we would have
5317                      handled it above), we're trying to expand into a
5318                      fixed-length argument list.  */
5319                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5320                     error ("cannot expand %<%E%> into a fixed-length "
5321                            "argument list", arg);
5322                   else
5323                     error ("cannot expand %<%T%> into a fixed-length "
5324                            "argument list", arg);
5325                 }
5326               return error_mark_node;
5327             }
5328         }
5329       else if (require_all_args)
5330         /* There must be a default arg in this case.  */
5331         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5332                                    complain, in_decl);
5333       else
5334         break;
5335
5336       if (arg == error_mark_node)
5337         {
5338           if (complain & tf_error)
5339             error ("template argument %d is invalid", arg_idx + 1);
5340         }
5341       else if (!arg)
5342         /* This only occurs if there was an error in the template
5343            parameter list itself (which we would already have
5344            reported) that we are trying to recover from, e.g., a class
5345            template with a parameter list such as
5346            template<typename..., typename>.  */
5347         return error_mark_node;
5348       else
5349         arg = convert_template_argument (TREE_VALUE (parm),
5350                                          arg, new_args, complain, 
5351                                          parm_idx, in_decl);
5352
5353       if (arg == error_mark_node)
5354         lost++;
5355       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5356     }
5357   skip_evaluation = saved_skip_evaluation;
5358
5359   if (lost)
5360     return error_mark_node;
5361
5362   return new_inner_args;
5363 }
5364
5365 /* Returns 1 if template args OT and NT are equivalent.  */
5366
5367 static int
5368 template_args_equal (tree ot, tree nt)
5369 {
5370   if (nt == ot)
5371     return 1;
5372
5373   if (TREE_CODE (nt) == TREE_VEC)
5374     /* For member templates */
5375     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5376   else if (PACK_EXPANSION_P (ot))
5377     return PACK_EXPANSION_P (nt) 
5378       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5379                               PACK_EXPANSION_PATTERN (nt));
5380   else if (TYPE_P (nt))
5381     return TYPE_P (ot) && same_type_p (ot, nt);
5382   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5383     return 0;
5384   else
5385     return cp_tree_equal (ot, nt);
5386 }
5387
5388 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5389    of template arguments.  Returns 0 otherwise.  */
5390
5391 int
5392 comp_template_args (tree oldargs, tree newargs)
5393 {
5394   int i;
5395
5396   oldargs = expand_template_argument_pack (oldargs);
5397   newargs = expand_template_argument_pack (newargs);
5398
5399   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5400     return 0;
5401
5402   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5403     {
5404       tree nt = TREE_VEC_ELT (newargs, i);
5405       tree ot = TREE_VEC_ELT (oldargs, i);
5406
5407       if (! template_args_equal (ot, nt))
5408         return 0;
5409     }
5410   return 1;
5411 }
5412
5413 static void
5414 add_pending_template (tree d)
5415 {
5416   tree ti = (TYPE_P (d)
5417              ? CLASSTYPE_TEMPLATE_INFO (d)
5418              : DECL_TEMPLATE_INFO (d));
5419   struct pending_template *pt;
5420   int level;
5421
5422   if (TI_PENDING_TEMPLATE_FLAG (ti))
5423     return;
5424
5425   /* We are called both from instantiate_decl, where we've already had a
5426      tinst_level pushed, and instantiate_template, where we haven't.
5427      Compensate.  */
5428   level = !current_tinst_level || current_tinst_level->decl != d;
5429
5430   if (level)
5431     push_tinst_level (d);
5432
5433   pt = GGC_NEW (struct pending_template);
5434   pt->next = NULL;
5435   pt->tinst = current_tinst_level;
5436   if (last_pending_template)
5437     last_pending_template->next = pt;
5438   else
5439     pending_templates = pt;
5440
5441   last_pending_template = pt;
5442
5443   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5444
5445   if (level)
5446     pop_tinst_level ();
5447 }
5448
5449
5450 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5451    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5452    documentation for TEMPLATE_ID_EXPR.  */
5453
5454 tree
5455 lookup_template_function (tree fns, tree arglist)
5456 {
5457   tree type;
5458
5459   if (fns == error_mark_node || arglist == error_mark_node)
5460     return error_mark_node;
5461
5462   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5463   gcc_assert (fns && (is_overloaded_fn (fns)
5464                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5465
5466   if (BASELINK_P (fns))
5467     {
5468       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5469                                          unknown_type_node,
5470                                          BASELINK_FUNCTIONS (fns),
5471                                          arglist);
5472       return fns;
5473     }
5474
5475   type = TREE_TYPE (fns);
5476   if (TREE_CODE (fns) == OVERLOAD || !type)
5477     type = unknown_type_node;
5478
5479   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5480 }
5481
5482 /* Within the scope of a template class S<T>, the name S gets bound
5483    (in build_self_reference) to a TYPE_DECL for the class, not a
5484    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5485    or one of its enclosing classes, and that type is a template,
5486    return the associated TEMPLATE_DECL.  Otherwise, the original
5487    DECL is returned.  */
5488
5489 tree
5490 maybe_get_template_decl_from_type_decl (tree decl)
5491 {
5492   return (decl != NULL_TREE
5493           && TREE_CODE (decl) == TYPE_DECL
5494           && DECL_ARTIFICIAL (decl)
5495           && CLASS_TYPE_P (TREE_TYPE (decl))
5496           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5497     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5498 }
5499
5500 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5501    parameters, find the desired type.
5502
5503    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5504
5505    IN_DECL, if non-NULL, is the template declaration we are trying to
5506    instantiate.
5507
5508    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5509    the class we are looking up.
5510
5511    Issue error and warning messages under control of COMPLAIN.
5512
5513    If the template class is really a local class in a template
5514    function, then the FUNCTION_CONTEXT is the function in which it is
5515    being instantiated.
5516
5517    ??? Note that this function is currently called *twice* for each
5518    template-id: the first time from the parser, while creating the
5519    incomplete type (finish_template_type), and the second type during the
5520    real instantiation (instantiate_template_class). This is surely something
5521    that we want to avoid. It also causes some problems with argument
5522    coercion (see convert_nontype_argument for more information on this).  */
5523
5524 tree
5525 lookup_template_class (tree d1,
5526                        tree arglist,
5527                        tree in_decl,
5528                        tree context,
5529                        int entering_scope,
5530                        tsubst_flags_t complain)
5531 {
5532   tree template = NULL_TREE, parmlist;
5533   tree t;
5534
5535   timevar_push (TV_NAME_LOOKUP);
5536
5537   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5538     {
5539       tree value = innermost_non_namespace_value (d1);
5540       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5541         template = value;
5542       else
5543         {
5544           if (context)
5545             push_decl_namespace (context);
5546           template = lookup_name (d1);
5547           template = maybe_get_template_decl_from_type_decl (template);
5548           if (context)
5549             pop_decl_namespace ();
5550         }
5551       if (template)
5552         context = DECL_CONTEXT (template);
5553     }
5554   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
5555     {
5556       tree type = TREE_TYPE (d1);
5557
5558       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5559          an implicit typename for the second A.  Deal with it.  */
5560       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5561         type = TREE_TYPE (type);
5562
5563       if (CLASSTYPE_TEMPLATE_INFO (type))
5564         {
5565           template = CLASSTYPE_TI_TEMPLATE (type);
5566           d1 = DECL_NAME (template);
5567         }
5568     }
5569   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5570            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
5571     {
5572       template = TYPE_TI_TEMPLATE (d1);
5573       d1 = DECL_NAME (template);
5574     }
5575   else if (TREE_CODE (d1) == TEMPLATE_DECL
5576            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5577     {
5578       template = d1;
5579       d1 = DECL_NAME (template);
5580       context = DECL_CONTEXT (template);
5581     }
5582
5583   /* Issue an error message if we didn't find a template.  */
5584   if (! template)
5585     {
5586       if (complain & tf_error)
5587         error ("%qT is not a template", d1);
5588       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5589     }
5590
5591   if (TREE_CODE (template) != TEMPLATE_DECL
5592          /* Make sure it's a user visible template, if it was named by
5593             the user.  */
5594       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (template)
5595           && !PRIMARY_TEMPLATE_P (template)))
5596     {
5597       if (complain & tf_error)
5598         {
5599           error ("non-template type %qT used as a template", d1);
5600           if (in_decl)
5601             error ("for template declaration %q+D", in_decl);
5602         }
5603       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5604     }
5605
5606   complain &= ~tf_user;
5607
5608   if (DECL_TEMPLATE_TEMPLATE_PARM_P (template))
5609     {
5610       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5611          template arguments */
5612
5613       tree parm;
5614       tree arglist2;
5615       tree outer;
5616
5617       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (template);
5618
5619       /* Consider an example where a template template parameter declared as
5620
5621            template <class T, class U = std::allocator<T> > class TT
5622
5623          The template parameter level of T and U are one level larger than
5624          of TT.  To proper process the default argument of U, say when an
5625          instantiation `TT<int>' is seen, we need to build the full
5626          arguments containing {int} as the innermost level.  Outer levels,
5627          available when not appearing as default template argument, can be
5628          obtained from the arguments of the enclosing template.
5629
5630          Suppose that TT is later substituted with std::vector.  The above
5631          instantiation is `TT<int, std::allocator<T> >' with TT at
5632          level 1, and T at level 2, while the template arguments at level 1
5633          becomes {std::vector} and the inner level 2 is {int}.  */
5634
5635       outer = DECL_CONTEXT (template);
5636       if (outer)
5637         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5638       else if (current_template_parms)
5639         /* This is an argument of the current template, so we haven't set
5640            DECL_CONTEXT yet.  */
5641         outer = current_template_args ();
5642
5643       if (outer)
5644         arglist = add_to_template_args (outer, arglist);
5645
5646       arglist2 = coerce_template_parms (parmlist, arglist, template,
5647                                         complain,
5648                                         /*require_all_args=*/true,
5649                                         /*use_default_args=*/true);
5650       if (arglist2 == error_mark_node
5651           || (!uses_template_parms (arglist2)
5652               && check_instantiated_args (template, arglist2, complain)))
5653         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5654
5655       parm = bind_template_template_parm (TREE_TYPE (template), arglist2);
5656       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5657     }
5658   else
5659     {
5660       tree template_type = TREE_TYPE (template);
5661       tree gen_tmpl;
5662       tree type_decl;
5663       tree found = NULL_TREE;
5664       int arg_depth;
5665       int parm_depth;
5666       int is_partial_instantiation;
5667
5668       gen_tmpl = most_general_template (template);
5669       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5670       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5671       arg_depth = TMPL_ARGS_DEPTH (arglist);
5672
5673       if (arg_depth == 1 && parm_depth > 1)
5674         {
5675           /* We've been given an incomplete set of template arguments.
5676              For example, given:
5677
5678                template <class T> struct S1 {
5679                  template <class U> struct S2 {};
5680                  template <class U> struct S2<U*> {};
5681                 };
5682
5683              we will be called with an ARGLIST of `U*', but the
5684              TEMPLATE will be `template <class T> template
5685              <class U> struct S1<T>::S2'.  We must fill in the missing
5686              arguments.  */
5687           arglist
5688             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (template)),
5689                                            arglist);
5690           arg_depth = TMPL_ARGS_DEPTH (arglist);
5691         }
5692
5693       /* Now we should have enough arguments.  */
5694       gcc_assert (parm_depth == arg_depth);
5695
5696       /* From here on, we're only interested in the most general
5697          template.  */
5698       template = gen_tmpl;
5699
5700       /* Calculate the BOUND_ARGS.  These will be the args that are
5701          actually tsubst'd into the definition to create the
5702          instantiation.  */
5703       if (parm_depth > 1)
5704         {
5705           /* We have multiple levels of arguments to coerce, at once.  */
5706           int i;
5707           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5708
5709           tree bound_args = make_tree_vec (parm_depth);
5710
5711           for (i = saved_depth,
5712                  t = DECL_TEMPLATE_PARMS (template);
5713                i > 0 && t != NULL_TREE;
5714                --i, t = TREE_CHAIN (t))
5715             {
5716               tree a = coerce_template_parms (TREE_VALUE (t),
5717                                               arglist, template,
5718                                               complain,
5719                                               /*require_all_args=*/true,
5720                                               /*use_default_args=*/true);
5721
5722               /* Don't process further if one of the levels fails.  */
5723               if (a == error_mark_node)
5724                 {
5725                   /* Restore the ARGLIST to its full size.  */
5726                   TREE_VEC_LENGTH (arglist) = saved_depth;
5727                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5728                 }
5729
5730               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5731
5732               /* We temporarily reduce the length of the ARGLIST so
5733                  that coerce_template_parms will see only the arguments
5734                  corresponding to the template parameters it is
5735                  examining.  */
5736               TREE_VEC_LENGTH (arglist)--;
5737             }
5738
5739           /* Restore the ARGLIST to its full size.  */
5740           TREE_VEC_LENGTH (arglist) = saved_depth;
5741
5742           arglist = bound_args;
5743         }
5744       else
5745         arglist
5746           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5747                                    INNERMOST_TEMPLATE_ARGS (arglist),
5748                                    template,
5749                                    complain,
5750                                    /*require_all_args=*/true,
5751                                    /*use_default_args=*/true);
5752
5753       if (arglist == error_mark_node)
5754         /* We were unable to bind the arguments.  */
5755         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5756
5757       /* In the scope of a template class, explicit references to the
5758          template class refer to the type of the template, not any
5759          instantiation of it.  For example, in:
5760
5761            template <class T> class C { void f(C<T>); }
5762
5763          the `C<T>' is just the same as `C'.  Outside of the
5764          class, however, such a reference is an instantiation.  */
5765       if (comp_template_args (TYPE_TI_ARGS (template_type),
5766                               arglist))
5767         {
5768           found = template_type;
5769
5770           if (!entering_scope && PRIMARY_TEMPLATE_P (template))
5771             {
5772               tree ctx;
5773
5774               for (ctx = current_class_type;
5775                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5776                    ctx = (TYPE_P (ctx)
5777                           ? TYPE_CONTEXT (ctx)
5778                           : DECL_CONTEXT (ctx)))
5779                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5780                   goto found_ctx;
5781
5782               /* We're not in the scope of the class, so the
5783                  TEMPLATE_TYPE is not the type we want after all.  */
5784               found = NULL_TREE;
5785             found_ctx:;
5786             }
5787         }
5788       if (found)
5789         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5790
5791       /* If we already have this specialization, return it.  */
5792       found = retrieve_specialization (template, arglist,
5793                                        /*class_specializations_p=*/false);
5794       if (found)
5795         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5796
5797       /* This type is a "partial instantiation" if any of the template
5798          arguments still involve template parameters.  Note that we set
5799          IS_PARTIAL_INSTANTIATION for partial specializations as
5800          well.  */
5801       is_partial_instantiation = uses_template_parms (arglist);
5802
5803       /* If the deduced arguments are invalid, then the binding
5804          failed.  */
5805       if (!is_partial_instantiation
5806           && check_instantiated_args (template,
5807                                       INNERMOST_TEMPLATE_ARGS (arglist),
5808                                       complain))
5809         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5810
5811       if (!is_partial_instantiation
5812           && !PRIMARY_TEMPLATE_P (template)
5813           && TREE_CODE (CP_DECL_CONTEXT (template)) == NAMESPACE_DECL)
5814         {
5815           found = xref_tag_from_type (TREE_TYPE (template),
5816                                       DECL_NAME (template),
5817                                       /*tag_scope=*/ts_global);
5818           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5819         }
5820
5821       context = tsubst (DECL_CONTEXT (template), arglist,
5822                         complain, in_decl);
5823       if (!context)
5824         context = global_namespace;
5825
5826       /* Create the type.  */
5827       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5828         {
5829           if (!is_partial_instantiation)
5830             {
5831               set_current_access_from_decl (TYPE_NAME (template_type));
5832               t = start_enum (TYPE_IDENTIFIER (template_type));
5833             }
5834           else
5835             /* We don't want to call start_enum for this type, since
5836                the values for the enumeration constants may involve
5837                template parameters.  And, no one should be interested
5838                in the enumeration constants for such a type.  */
5839             t = make_node (ENUMERAL_TYPE);
5840         }
5841       else
5842         {
5843           t = make_class_type (TREE_CODE (template_type));
5844           CLASSTYPE_DECLARED_CLASS (t)
5845             = CLASSTYPE_DECLARED_CLASS (template_type);
5846           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5847           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5848
5849           /* A local class.  Make sure the decl gets registered properly.  */
5850           if (context == current_function_decl)
5851             pushtag (DECL_NAME (template), t, /*tag_scope=*/ts_current);
5852
5853           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5854             /* This instantiation is another name for the primary
5855                template type. Set the TYPE_CANONICAL field
5856                appropriately. */
5857             TYPE_CANONICAL (t) = template_type;
5858           else if (any_template_arguments_need_structural_equality_p (arglist))
5859             /* Some of the template arguments require structural
5860                equality testing, so this template class requires
5861                structural equality testing. */
5862             SET_TYPE_STRUCTURAL_EQUALITY (t);
5863         }
5864
5865       /* If we called start_enum or pushtag above, this information
5866          will already be set up.  */
5867       if (!TYPE_NAME (t))
5868         {
5869           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5870
5871           type_decl = create_implicit_typedef (DECL_NAME (template), t);
5872           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5873           TYPE_STUB_DECL (t) = type_decl;
5874           DECL_SOURCE_LOCATION (type_decl)
5875             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5876         }
5877       else
5878         type_decl = TYPE_NAME (t);
5879
5880       TREE_PRIVATE (type_decl)
5881         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5882       TREE_PROTECTED (type_decl)
5883         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5884       DECL_IN_SYSTEM_HEADER (type_decl)
5885         = DECL_IN_SYSTEM_HEADER (template);
5886       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5887         {
5888           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5889           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5890         }
5891
5892       /* Set up the template information.  We have to figure out which
5893          template is the immediate parent if this is a full
5894          instantiation.  */
5895       if (parm_depth == 1 || is_partial_instantiation
5896           || !PRIMARY_TEMPLATE_P (template))
5897         /* This case is easy; there are no member templates involved.  */
5898         found = template;
5899       else
5900         {
5901           /* This is a full instantiation of a member template.  Look
5902              for a partial instantiation of which this is an instance.  */
5903
5904           for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
5905                found; found = TREE_CHAIN (found))
5906             {
5907               int success;
5908               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5909
5910               /* We only want partial instantiations, here, not
5911                  specializations or full instantiations.  */
5912               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5913                   || !uses_template_parms (TREE_VALUE (found)))
5914                 continue;
5915
5916               /* Temporarily reduce by one the number of levels in the
5917                  ARGLIST and in FOUND so as to avoid comparing the
5918                  last set of arguments.  */
5919               TREE_VEC_LENGTH (arglist)--;
5920               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
5921
5922               /* See if the arguments match.  If they do, then TMPL is
5923                  the partial instantiation we want.  */
5924               success = comp_template_args (TREE_PURPOSE (found), arglist);
5925
5926               /* Restore the argument vectors to their full size.  */
5927               TREE_VEC_LENGTH (arglist)++;
5928               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
5929
5930               if (success)
5931                 {
5932                   found = tmpl;
5933                   break;
5934                 }
5935             }
5936
5937           if (!found)
5938             {
5939               /* There was no partial instantiation. This happens
5940                  where C<T> is a member template of A<T> and it's used
5941                  in something like
5942
5943                   template <typename T> struct B { A<T>::C<int> m; };
5944                   B<float>;
5945
5946                  Create the partial instantiation.
5947                */
5948               TREE_VEC_LENGTH (arglist)--;
5949               found = tsubst (template, arglist, complain, NULL_TREE);
5950               TREE_VEC_LENGTH (arglist)++;
5951             }
5952         }
5953
5954       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
5955       DECL_TEMPLATE_INSTANTIATIONS (template)
5956         = tree_cons (arglist, t,
5957                      DECL_TEMPLATE_INSTANTIATIONS (template));
5958
5959       if (TREE_CODE (t) == ENUMERAL_TYPE
5960           && !is_partial_instantiation)
5961         /* Now that the type has been registered on the instantiations
5962            list, we set up the enumerators.  Because the enumeration
5963            constants may involve the enumeration type itself, we make
5964            sure to register the type first, and then create the
5965            constants.  That way, doing tsubst_expr for the enumeration
5966            constants won't result in recursive calls here; we'll find
5967            the instantiation and exit above.  */
5968         tsubst_enum (template_type, t, arglist);
5969
5970       if (is_partial_instantiation)
5971         /* If the type makes use of template parameters, the
5972            code that generates debugging information will crash.  */
5973         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
5974
5975       /* Possibly limit visibility based on template args.  */
5976       TREE_PUBLIC (type_decl) = 1;
5977       determine_visibility (type_decl);
5978
5979       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
5980     }
5981   timevar_pop (TV_NAME_LOOKUP);
5982 }
5983 \f
5984 struct pair_fn_data
5985 {
5986   tree_fn_t fn;
5987   void *data;
5988   /* True when we should also visit template parameters that occur in
5989      non-deduced contexts.  */
5990   bool include_nondeduced_p;
5991   struct pointer_set_t *visited;
5992 };
5993
5994 /* Called from for_each_template_parm via walk_tree.  */
5995
5996 static tree
5997 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
5998 {
5999   tree t = *tp;
6000   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6001   tree_fn_t fn = pfd->fn;
6002   void *data = pfd->data;
6003
6004   if (TYPE_P (t)
6005       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6006       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6007                                  pfd->include_nondeduced_p))
6008     return error_mark_node;
6009
6010   switch (TREE_CODE (t))
6011     {
6012     case RECORD_TYPE:
6013       if (TYPE_PTRMEMFUNC_P (t))
6014         break;
6015       /* Fall through.  */
6016
6017     case UNION_TYPE:
6018     case ENUMERAL_TYPE:
6019       if (!TYPE_TEMPLATE_INFO (t))
6020         *walk_subtrees = 0;
6021       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6022                                        fn, data, pfd->visited, 
6023                                        pfd->include_nondeduced_p))
6024         return error_mark_node;
6025       break;
6026
6027     case INTEGER_TYPE:
6028       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6029                                   fn, data, pfd->visited, 
6030                                   pfd->include_nondeduced_p)
6031           || for_each_template_parm (TYPE_MAX_VALUE (t),
6032                                      fn, data, pfd->visited,
6033                                      pfd->include_nondeduced_p))
6034         return error_mark_node;
6035       break;
6036
6037     case METHOD_TYPE:
6038       /* Since we're not going to walk subtrees, we have to do this
6039          explicitly here.  */
6040       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6041                                   pfd->visited, pfd->include_nondeduced_p))
6042         return error_mark_node;
6043       /* Fall through.  */
6044
6045     case FUNCTION_TYPE:
6046       /* Check the return type.  */
6047       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6048                                   pfd->include_nondeduced_p))
6049         return error_mark_node;
6050
6051       /* Check the parameter types.  Since default arguments are not
6052          instantiated until they are needed, the TYPE_ARG_TYPES may
6053          contain expressions that involve template parameters.  But,
6054          no-one should be looking at them yet.  And, once they're
6055          instantiated, they don't contain template parameters, so
6056          there's no point in looking at them then, either.  */
6057       {
6058         tree parm;
6059
6060         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6061           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6062                                       pfd->visited, pfd->include_nondeduced_p))
6063             return error_mark_node;
6064
6065         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6066            want walk_tree walking into them itself.  */
6067         *walk_subtrees = 0;
6068       }
6069       break;
6070
6071     case TYPEOF_TYPE:
6072       if (pfd->include_nondeduced_p
6073           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6074                                      pfd->visited, 
6075                                      pfd->include_nondeduced_p))
6076         return error_mark_node;
6077       break;
6078
6079     case FUNCTION_DECL:
6080     case VAR_DECL:
6081       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6082           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6083                                      pfd->visited, pfd->include_nondeduced_p))
6084         return error_mark_node;
6085       /* Fall through.  */
6086
6087     case PARM_DECL:
6088     case CONST_DECL:
6089       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6090           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6091                                      pfd->visited, pfd->include_nondeduced_p))
6092         return error_mark_node;
6093       if (DECL_CONTEXT (t)
6094           && pfd->include_nondeduced_p
6095           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6096                                      pfd->visited, pfd->include_nondeduced_p))
6097         return error_mark_node;
6098       break;
6099
6100     case BOUND_TEMPLATE_TEMPLATE_PARM:
6101       /* Record template parameters such as `T' inside `TT<T>'.  */
6102       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6103                                   pfd->include_nondeduced_p))
6104         return error_mark_node;
6105       /* Fall through.  */
6106
6107     case TEMPLATE_TEMPLATE_PARM:
6108     case TEMPLATE_TYPE_PARM:
6109     case TEMPLATE_PARM_INDEX:
6110       if (fn && (*fn)(t, data))
6111         return error_mark_node;
6112       else if (!fn)
6113         return error_mark_node;
6114       break;
6115
6116     case TEMPLATE_DECL:
6117       /* A template template parameter is encountered.  */
6118       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6119           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6120                                      pfd->include_nondeduced_p))
6121         return error_mark_node;
6122
6123       /* Already substituted template template parameter */
6124       *walk_subtrees = 0;
6125       break;
6126
6127     case TYPENAME_TYPE:
6128       if (!fn
6129           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6130                                      data, pfd->visited, 
6131                                      pfd->include_nondeduced_p))
6132         return error_mark_node;
6133       break;
6134
6135     case CONSTRUCTOR:
6136       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6137           && pfd->include_nondeduced_p
6138           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6139                                      (TREE_TYPE (t)), fn, data,
6140                                      pfd->visited, pfd->include_nondeduced_p))
6141         return error_mark_node;
6142       break;
6143
6144     case INDIRECT_REF:
6145     case COMPONENT_REF:
6146       /* If there's no type, then this thing must be some expression
6147          involving template parameters.  */
6148       if (!fn && !TREE_TYPE (t))
6149         return error_mark_node;
6150       break;
6151
6152     case MODOP_EXPR:
6153     case CAST_EXPR:
6154     case REINTERPRET_CAST_EXPR:
6155     case CONST_CAST_EXPR:
6156     case STATIC_CAST_EXPR:
6157     case DYNAMIC_CAST_EXPR:
6158     case ARROW_EXPR:
6159     case DOTSTAR_EXPR:
6160     case TYPEID_EXPR:
6161     case PSEUDO_DTOR_EXPR:
6162       if (!fn)
6163         return error_mark_node;
6164       break;
6165
6166     default:
6167       break;
6168     }
6169
6170   /* We didn't find any template parameters we liked.  */
6171   return NULL_TREE;
6172 }
6173
6174 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6175    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6176    call FN with the parameter and the DATA.
6177    If FN returns nonzero, the iteration is terminated, and
6178    for_each_template_parm returns 1.  Otherwise, the iteration
6179    continues.  If FN never returns a nonzero value, the value
6180    returned by for_each_template_parm is 0.  If FN is NULL, it is
6181    considered to be the function which always returns 1.
6182
6183    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6184    parameters that occur in non-deduced contexts.  When false, only
6185    visits those template parameters that can be deduced.  */
6186
6187 static int
6188 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6189                         struct pointer_set_t *visited,
6190                         bool include_nondeduced_p)
6191 {
6192   struct pair_fn_data pfd;
6193   int result;
6194
6195   /* Set up.  */
6196   pfd.fn = fn;
6197   pfd.data = data;
6198   pfd.include_nondeduced_p = include_nondeduced_p;
6199
6200   /* Walk the tree.  (Conceptually, we would like to walk without
6201      duplicates, but for_each_template_parm_r recursively calls
6202      for_each_template_parm, so we would need to reorganize a fair
6203      bit to use walk_tree_without_duplicates, so we keep our own
6204      visited list.)  */
6205   if (visited)
6206     pfd.visited = visited;
6207   else
6208     pfd.visited = pointer_set_create ();
6209   result = cp_walk_tree (&t,
6210                          for_each_template_parm_r,
6211                          &pfd,
6212                          pfd.visited) != NULL_TREE;
6213
6214   /* Clean up.  */
6215   if (!visited)
6216     {
6217       pointer_set_destroy (pfd.visited);
6218       pfd.visited = 0;
6219     }
6220
6221   return result;
6222 }
6223
6224 /* Returns true if T depends on any template parameter.  */
6225
6226 int
6227 uses_template_parms (tree t)
6228 {
6229   bool dependent_p;
6230   int saved_processing_template_decl;
6231
6232   saved_processing_template_decl = processing_template_decl;
6233   if (!saved_processing_template_decl)
6234     processing_template_decl = 1;
6235   if (TYPE_P (t))
6236     dependent_p = dependent_type_p (t);
6237   else if (TREE_CODE (t) == TREE_VEC)
6238     dependent_p = any_dependent_template_arguments_p (t);
6239   else if (TREE_CODE (t) == TREE_LIST)
6240     dependent_p = (uses_template_parms (TREE_VALUE (t))
6241                    || uses_template_parms (TREE_CHAIN (t)));
6242   else if (TREE_CODE (t) == TYPE_DECL)
6243     dependent_p = dependent_type_p (TREE_TYPE (t));
6244   else if (DECL_P (t)
6245            || EXPR_P (t)
6246            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6247            || TREE_CODE (t) == OVERLOAD
6248            || TREE_CODE (t) == BASELINK
6249            || TREE_CODE (t) == IDENTIFIER_NODE
6250            || TREE_CODE (t) == TRAIT_EXPR
6251            || CONSTANT_CLASS_P (t))
6252     dependent_p = (type_dependent_expression_p (t)
6253                    || value_dependent_expression_p (t));
6254   else
6255     {
6256       gcc_assert (t == error_mark_node);
6257       dependent_p = false;
6258     }
6259
6260   processing_template_decl = saved_processing_template_decl;
6261
6262   return dependent_p;
6263 }
6264
6265 /* Returns true if T depends on any template parameter with level LEVEL.  */
6266
6267 int
6268 uses_template_parms_level (tree t, int level)
6269 {
6270   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6271                                  /*include_nondeduced_p=*/true);
6272 }
6273
6274 static int tinst_depth;
6275 extern int max_tinst_depth;
6276 #ifdef GATHER_STATISTICS
6277 int depth_reached;
6278 #endif
6279 static int tinst_level_tick;
6280 static int last_template_error_tick;
6281
6282 /* We're starting to instantiate D; record the template instantiation context
6283    for diagnostics and to restore it later.  */
6284
6285 static int
6286 push_tinst_level (tree d)
6287 {
6288   struct tinst_level *new;
6289
6290   if (tinst_depth >= max_tinst_depth)
6291     {
6292       /* If the instantiation in question still has unbound template parms,
6293          we don't really care if we can't instantiate it, so just return.
6294          This happens with base instantiation for implicit `typename'.  */
6295       if (uses_template_parms (d))
6296         return 0;
6297
6298       last_template_error_tick = tinst_level_tick;
6299       error ("template instantiation depth exceeds maximum of %d (use "
6300              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6301              max_tinst_depth, d);
6302
6303       print_instantiation_context ();
6304
6305       return 0;
6306     }
6307
6308   new = GGC_NEW (struct tinst_level);
6309   new->decl = d;
6310   new->locus = input_location;
6311   new->in_system_header_p = in_system_header;
6312   new->next = current_tinst_level;
6313   current_tinst_level = new;
6314
6315   ++tinst_depth;
6316 #ifdef GATHER_STATISTICS
6317   if (tinst_depth > depth_reached)
6318     depth_reached = tinst_depth;
6319 #endif
6320
6321   ++tinst_level_tick;
6322   return 1;
6323 }
6324
6325 /* We're done instantiating this template; return to the instantiation
6326    context.  */
6327
6328 static void
6329 pop_tinst_level (void)
6330 {
6331   /* Restore the filename and line number stashed away when we started
6332      this instantiation.  */
6333   input_location = current_tinst_level->locus;
6334   in_system_header = current_tinst_level->in_system_header_p;
6335   current_tinst_level = current_tinst_level->next;
6336   --tinst_depth;
6337   ++tinst_level_tick;
6338 }
6339
6340 /* We're instantiating a deferred template; restore the template
6341    instantiation context in which the instantiation was requested, which
6342    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6343
6344 static tree
6345 reopen_tinst_level (struct tinst_level *level)
6346 {
6347   struct tinst_level *t;
6348
6349   tinst_depth = 0;
6350   for (t = level; t; t = t->next)
6351     ++tinst_depth;
6352
6353   current_tinst_level = level;
6354   pop_tinst_level ();
6355   return level->decl;
6356 }
6357
6358 /* Returns the TINST_LEVEL which gives the original instantiation
6359    context.  */
6360
6361 struct tinst_level *
6362 outermost_tinst_level (void)
6363 {
6364   struct tinst_level *level = current_tinst_level;
6365   if (level)
6366     while (level->next)
6367       level = level->next;
6368   return level;
6369 }
6370
6371 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6372    vector of template arguments, as for tsubst.
6373
6374    Returns an appropriate tsubst'd friend declaration.  */
6375
6376 static tree
6377 tsubst_friend_function (tree decl, tree args)
6378 {
6379   tree new_friend;
6380
6381   if (TREE_CODE (decl) == FUNCTION_DECL
6382       && DECL_TEMPLATE_INSTANTIATION (decl)
6383       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6384     /* This was a friend declared with an explicit template
6385        argument list, e.g.:
6386
6387        friend void f<>(T);
6388
6389        to indicate that f was a template instantiation, not a new
6390        function declaration.  Now, we have to figure out what
6391        instantiation of what template.  */
6392     {
6393       tree template_id, arglist, fns;
6394       tree new_args;
6395       tree tmpl;
6396       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6397
6398       /* Friend functions are looked up in the containing namespace scope.
6399          We must enter that scope, to avoid finding member functions of the
6400          current cless with same name.  */
6401       push_nested_namespace (ns);
6402       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6403                          tf_warning_or_error, NULL_TREE,
6404                          /*integral_constant_expression_p=*/false);
6405       pop_nested_namespace (ns);
6406       arglist = tsubst (DECL_TI_ARGS (decl), args,
6407                         tf_warning_or_error, NULL_TREE);
6408       template_id = lookup_template_function (fns, arglist);
6409
6410       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6411       tmpl = determine_specialization (template_id, new_friend,
6412                                        &new_args,
6413                                        /*need_member_template=*/0,
6414                                        TREE_VEC_LENGTH (args),
6415                                        tsk_none);
6416       return instantiate_template (tmpl, new_args, tf_error);
6417     }
6418
6419   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6420
6421   /* The NEW_FRIEND will look like an instantiation, to the
6422      compiler, but is not an instantiation from the point of view of
6423      the language.  For example, we might have had:
6424
6425      template <class T> struct S {
6426        template <class U> friend void f(T, U);
6427      };
6428
6429      Then, in S<int>, template <class U> void f(int, U) is not an
6430      instantiation of anything.  */
6431   if (new_friend == error_mark_node)
6432     return error_mark_node;
6433
6434   DECL_USE_TEMPLATE (new_friend) = 0;
6435   if (TREE_CODE (decl) == TEMPLATE_DECL)
6436     {
6437       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6438       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6439         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6440     }
6441
6442   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6443      is not a template instantiation and should not be mangled like
6444      one.  Therefore, we forget the mangling here; we'll recompute it
6445      later if we need it.  */
6446   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6447     {
6448       SET_DECL_RTL (new_friend, NULL_RTX);
6449       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6450     }
6451
6452   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6453     {
6454       tree old_decl;
6455       tree new_friend_template_info;
6456       tree new_friend_result_template_info;
6457       tree ns;
6458       int  new_friend_is_defn;
6459
6460       /* We must save some information from NEW_FRIEND before calling
6461          duplicate decls since that function will free NEW_FRIEND if
6462          possible.  */
6463       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6464       new_friend_is_defn =
6465             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6466                            (template_for_substitution (new_friend)))
6467              != NULL_TREE);
6468       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6469         {
6470           /* This declaration is a `primary' template.  */
6471           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6472
6473           new_friend_result_template_info
6474             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6475         }
6476       else
6477         new_friend_result_template_info = NULL_TREE;
6478
6479       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6480       if (new_friend_is_defn)
6481         DECL_INITIAL (new_friend) = error_mark_node;
6482
6483       /* Inside pushdecl_namespace_level, we will push into the
6484          current namespace. However, the friend function should go
6485          into the namespace of the template.  */
6486       ns = decl_namespace_context (new_friend);
6487       push_nested_namespace (ns);
6488       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6489       pop_nested_namespace (ns);
6490
6491       if (old_decl == error_mark_node)
6492         return error_mark_node;
6493
6494       if (old_decl != new_friend)
6495         {
6496           /* This new friend declaration matched an existing
6497              declaration.  For example, given:
6498
6499                template <class T> void f(T);
6500                template <class U> class C {
6501                  template <class T> friend void f(T) {}
6502                };
6503
6504              the friend declaration actually provides the definition
6505              of `f', once C has been instantiated for some type.  So,
6506              old_decl will be the out-of-class template declaration,
6507              while new_friend is the in-class definition.
6508
6509              But, if `f' was called before this point, the
6510              instantiation of `f' will have DECL_TI_ARGS corresponding
6511              to `T' but not to `U', references to which might appear
6512              in the definition of `f'.  Previously, the most general
6513              template for an instantiation of `f' was the out-of-class
6514              version; now it is the in-class version.  Therefore, we
6515              run through all specialization of `f', adding to their
6516              DECL_TI_ARGS appropriately.  In particular, they need a
6517              new set of outer arguments, corresponding to the
6518              arguments for this class instantiation.
6519
6520              The same situation can arise with something like this:
6521
6522                friend void f(int);
6523                template <class T> class C {
6524                  friend void f(T) {}
6525                };
6526
6527              when `C<int>' is instantiated.  Now, `f(int)' is defined
6528              in the class.  */
6529
6530           if (!new_friend_is_defn)
6531             /* On the other hand, if the in-class declaration does
6532                *not* provide a definition, then we don't want to alter
6533                existing definitions.  We can just leave everything
6534                alone.  */
6535             ;
6536           else
6537             {
6538               /* Overwrite whatever template info was there before, if
6539                  any, with the new template information pertaining to
6540                  the declaration.  */
6541               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6542
6543               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6544                 reregister_specialization (new_friend,
6545                                            most_general_template (old_decl),
6546                                            old_decl);
6547               else
6548                 {
6549                   tree t;
6550                   tree new_friend_args;
6551
6552                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6553                     = new_friend_result_template_info;
6554
6555                   new_friend_args = TI_ARGS (new_friend_template_info);
6556                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6557                        t != NULL_TREE;
6558                        t = TREE_CHAIN (t))
6559                     {
6560                       tree spec = TREE_VALUE (t);
6561
6562                       DECL_TI_ARGS (spec)
6563                         = add_outermost_template_args (new_friend_args,
6564                                                        DECL_TI_ARGS (spec));
6565                     }
6566
6567                   /* Now, since specializations are always supposed to
6568                      hang off of the most general template, we must move
6569                      them.  */
6570                   t = most_general_template (old_decl);
6571                   if (t != old_decl)
6572                     {
6573                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6574                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6575                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6576                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6577                     }
6578                 }
6579             }
6580
6581           /* The information from NEW_FRIEND has been merged into OLD_DECL
6582              by duplicate_decls.  */
6583           new_friend = old_decl;
6584         }
6585     }
6586   else
6587     {
6588       tree context = DECL_CONTEXT (new_friend);
6589       bool dependent_p;
6590
6591       /* In the code
6592            template <class T> class C {
6593              template <class U> friend void C1<U>::f (); // case 1
6594              friend void C2<T>::f ();                    // case 2
6595            };
6596          we only need to make sure CONTEXT is a complete type for
6597          case 2.  To distinguish between the two cases, we note that
6598          CONTEXT of case 1 remains dependent type after tsubst while
6599          this isn't true for case 2.  */
6600       ++processing_template_decl;
6601       dependent_p = dependent_type_p (context);
6602       --processing_template_decl;
6603
6604       if (!dependent_p
6605           && !complete_type_or_else (context, NULL_TREE))
6606         return error_mark_node;
6607
6608       if (COMPLETE_TYPE_P (context))
6609         {
6610           /* Check to see that the declaration is really present, and,
6611              possibly obtain an improved declaration.  */
6612           tree fn = check_classfn (context,
6613                                    new_friend, NULL_TREE);
6614
6615           if (fn)
6616             new_friend = fn;
6617         }
6618     }
6619
6620   return new_friend;
6621 }
6622
6623 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6624    template arguments, as for tsubst.
6625
6626    Returns an appropriate tsubst'd friend type or error_mark_node on
6627    failure.  */
6628
6629 static tree
6630 tsubst_friend_class (tree friend_tmpl, tree args)
6631 {
6632   tree friend_type;
6633   tree tmpl;
6634   tree context;
6635
6636   context = DECL_CONTEXT (friend_tmpl);
6637
6638   if (context)
6639     {
6640       if (TREE_CODE (context) == NAMESPACE_DECL)
6641         push_nested_namespace (context);
6642       else
6643         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6644     }
6645
6646   /* Look for a class template declaration.  We look for hidden names
6647      because two friend declarations of the same template are the
6648      same.  For example, in:
6649
6650        struct A { 
6651          template <typename> friend class F;
6652        };
6653        template <typename> struct B { 
6654          template <typename> friend class F;
6655        };
6656
6657      both F templates are the same.  */
6658   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6659                            /*block_p=*/true, 0, 
6660                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6661
6662   /* But, if we don't find one, it might be because we're in a
6663      situation like this:
6664
6665        template <class T>
6666        struct S {
6667          template <class U>
6668          friend struct S;
6669        };
6670
6671      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6672      for `S<int>', not the TEMPLATE_DECL.  */
6673   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6674     {
6675       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6676       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6677     }
6678
6679   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6680     {
6681       /* The friend template has already been declared.  Just
6682          check to see that the declarations match, and install any new
6683          default parameters.  We must tsubst the default parameters,
6684          of course.  We only need the innermost template parameters
6685          because that is all that redeclare_class_template will look
6686          at.  */
6687       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6688           > TMPL_ARGS_DEPTH (args))
6689         {
6690           tree parms;
6691           location_t saved_input_location;
6692           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6693                                          args, tf_warning_or_error);
6694
6695           saved_input_location = input_location;
6696           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6697           redeclare_class_template (TREE_TYPE (tmpl), parms);
6698           input_location = saved_input_location;
6699           
6700         }
6701
6702       friend_type = TREE_TYPE (tmpl);
6703     }
6704   else
6705     {
6706       /* The friend template has not already been declared.  In this
6707          case, the instantiation of the template class will cause the
6708          injection of this template into the global scope.  */
6709       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6710       if (tmpl == error_mark_node)
6711         return error_mark_node;
6712
6713       /* The new TMPL is not an instantiation of anything, so we
6714          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6715          the new type because that is supposed to be the corresponding
6716          template decl, i.e., TMPL.  */
6717       DECL_USE_TEMPLATE (tmpl) = 0;
6718       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6719       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6720       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6721         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6722
6723       /* Inject this template into the global scope.  */
6724       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6725     }
6726
6727   if (context)
6728     {
6729       if (TREE_CODE (context) == NAMESPACE_DECL)
6730         pop_nested_namespace (context);
6731       else
6732         pop_nested_class ();
6733     }
6734
6735   return friend_type;
6736 }
6737
6738 /* Returns zero if TYPE cannot be completed later due to circularity.
6739    Otherwise returns one.  */
6740
6741 static int
6742 can_complete_type_without_circularity (tree type)
6743 {
6744   if (type == NULL_TREE || type == error_mark_node)
6745     return 0;
6746   else if (COMPLETE_TYPE_P (type))
6747     return 1;
6748   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6749     return can_complete_type_without_circularity (TREE_TYPE (type));
6750   else if (CLASS_TYPE_P (type)
6751            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6752     return 0;
6753   else
6754     return 1;
6755 }
6756
6757 /* Apply any attributes which had to be deferred until instantiation
6758    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6759    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6760
6761 static void
6762 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6763                                 tree args, tsubst_flags_t complain, tree in_decl)
6764 {
6765   tree last_dep = NULL_TREE;
6766   tree t;
6767   tree *p;
6768
6769   for (t = attributes; t; t = TREE_CHAIN (t))
6770     if (ATTR_IS_DEPENDENT (t))
6771       {
6772         last_dep = t;
6773         attributes = copy_list (attributes);
6774         break;
6775       }
6776
6777   if (DECL_P (*decl_p))
6778     {
6779       if (TREE_TYPE (*decl_p) == error_mark_node)
6780         return;
6781       p = &DECL_ATTRIBUTES (*decl_p);
6782     }
6783   else
6784     p = &TYPE_ATTRIBUTES (*decl_p);
6785
6786   if (last_dep)
6787     {
6788       tree late_attrs = NULL_TREE;
6789       tree *q = &late_attrs;
6790
6791       for (*p = attributes; *p; )
6792         {
6793           t = *p;
6794           if (ATTR_IS_DEPENDENT (t))
6795             {
6796               *p = TREE_CHAIN (t);
6797               TREE_CHAIN (t) = NULL_TREE;
6798               /* If the first attribute argument is an identifier, don't
6799                  pass it through tsubst.  Attributes like mode, format,
6800                  cleanup and several target specific attributes expect it
6801                  unmodified.  */
6802               if (TREE_VALUE (t)
6803                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
6804                   && TREE_VALUE (TREE_VALUE (t))
6805                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
6806                       == IDENTIFIER_NODE))
6807                 {
6808                   tree chain
6809                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
6810                                    in_decl,
6811                                    /*integral_constant_expression_p=*/false);
6812                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
6813                     TREE_VALUE (t)
6814                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
6815                                    chain);
6816                 }
6817               else
6818                 TREE_VALUE (t)
6819                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6820                                  /*integral_constant_expression_p=*/false);
6821               *q = t;
6822               q = &TREE_CHAIN (t);
6823             }
6824           else
6825             p = &TREE_CHAIN (t);
6826         }
6827
6828       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
6829     }
6830 }
6831
6832 tree
6833 instantiate_class_template (tree type)
6834 {
6835   tree template, args, pattern, t, member;
6836   tree typedecl;
6837   tree pbinfo;
6838   tree base_list;
6839
6840   if (type == error_mark_node)
6841     return error_mark_node;
6842
6843   if (TYPE_BEING_DEFINED (type)
6844       || COMPLETE_TYPE_P (type)
6845       || dependent_type_p (type))
6846     return type;
6847
6848   /* Figure out which template is being instantiated.  */
6849   template = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6850   gcc_assert (TREE_CODE (template) == TEMPLATE_DECL);
6851
6852   /* Determine what specialization of the original template to
6853      instantiate.  */
6854   t = most_specialized_class (type, template);
6855   if (t == error_mark_node)
6856     {
6857       TYPE_BEING_DEFINED (type) = 1;
6858       return error_mark_node;
6859     }
6860   else if (t)
6861     {
6862       /* This TYPE is actually an instantiation of a partial
6863          specialization.  We replace the innermost set of ARGS with
6864          the arguments appropriate for substitution.  For example,
6865          given:
6866
6867            template <class T> struct S {};
6868            template <class T> struct S<T*> {};
6869
6870          and supposing that we are instantiating S<int*>, ARGS will
6871          presently be {int*} -- but we need {int}.  */
6872       pattern = TREE_TYPE (t);
6873       args = TREE_PURPOSE (t);
6874     }
6875   else
6876     {
6877       pattern = TREE_TYPE (template);
6878       args = CLASSTYPE_TI_ARGS (type);
6879     }
6880
6881   /* If the template we're instantiating is incomplete, then clearly
6882      there's nothing we can do.  */
6883   if (!COMPLETE_TYPE_P (pattern))
6884     return type;
6885
6886   /* If we've recursively instantiated too many templates, stop.  */
6887   if (! push_tinst_level (type))
6888     return type;
6889
6890   /* Now we're really doing the instantiation.  Mark the type as in
6891      the process of being defined.  */
6892   TYPE_BEING_DEFINED (type) = 1;
6893
6894   /* We may be in the middle of deferred access check.  Disable
6895      it now.  */
6896   push_deferring_access_checks (dk_no_deferred);
6897
6898   push_to_top_level ();
6899
6900   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
6901
6902   /* Set the input location to the template definition. This is needed
6903      if tsubsting causes an error.  */
6904   typedecl = TYPE_MAIN_DECL (type);
6905   input_location = DECL_SOURCE_LOCATION (typedecl);
6906   in_system_header = DECL_IN_SYSTEM_HEADER (typedecl);
6907
6908   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
6909   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
6910   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
6911   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
6912   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
6913   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
6914   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
6915   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
6916   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
6917   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
6918   TYPE_PACKED (type) = TYPE_PACKED (pattern);
6919   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
6920   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
6921   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
6922   if (ANON_AGGR_TYPE_P (pattern))
6923     SET_ANON_AGGR_TYPE_P (type);
6924   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
6925     {
6926       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
6927       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
6928     }
6929
6930   pbinfo = TYPE_BINFO (pattern);
6931
6932   /* We should never instantiate a nested class before its enclosing
6933      class; we need to look up the nested class by name before we can
6934      instantiate it, and that lookup should instantiate the enclosing
6935      class.  */
6936   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
6937               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
6938               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
6939
6940   base_list = NULL_TREE;
6941   if (BINFO_N_BASE_BINFOS (pbinfo))
6942     {
6943       tree pbase_binfo;
6944       tree context = TYPE_CONTEXT (type);
6945       tree pushed_scope;
6946       int i;
6947
6948       /* We must enter the scope containing the type, as that is where
6949          the accessibility of types named in dependent bases are
6950          looked up from.  */
6951       pushed_scope = push_scope (context ? context : global_namespace);
6952
6953       /* Substitute into each of the bases to determine the actual
6954          basetypes.  */
6955       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
6956         {
6957           tree base;
6958           tree access = BINFO_BASE_ACCESS (pbinfo, i);
6959           tree expanded_bases = NULL_TREE;
6960           int idx, len = 1;
6961
6962           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
6963             {
6964               expanded_bases = 
6965                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
6966                                        args, tf_error, NULL_TREE);
6967               if (expanded_bases == error_mark_node)
6968                 continue;
6969
6970               len = TREE_VEC_LENGTH (expanded_bases);
6971             }
6972
6973           for (idx = 0; idx < len; idx++)
6974             {
6975               if (expanded_bases)
6976                 /* Extract the already-expanded base class.  */
6977                 base = TREE_VEC_ELT (expanded_bases, idx);
6978               else
6979                 /* Substitute to figure out the base class.  */
6980                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
6981                                NULL_TREE);
6982
6983               if (base == error_mark_node)
6984                 continue;
6985
6986               base_list = tree_cons (access, base, base_list);
6987               if (BINFO_VIRTUAL_P (pbase_binfo))
6988                 TREE_TYPE (base_list) = integer_type_node;
6989             }
6990         }
6991
6992       /* The list is now in reverse order; correct that.  */
6993       base_list = nreverse (base_list);
6994
6995       if (pushed_scope)
6996         pop_scope (pushed_scope);
6997     }
6998   /* Now call xref_basetypes to set up all the base-class
6999      information.  */
7000   xref_basetypes (type, base_list);
7001
7002   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7003                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7004                                   args, tf_error, NULL_TREE);
7005
7006   /* Now that our base classes are set up, enter the scope of the
7007      class, so that name lookups into base classes, etc. will work
7008      correctly.  This is precisely analogous to what we do in
7009      begin_class_definition when defining an ordinary non-template
7010      class, except we also need to push the enclosing classes.  */
7011   push_nested_class (type);
7012
7013   /* Now members are processed in the order of declaration.  */
7014   for (member = CLASSTYPE_DECL_LIST (pattern);
7015        member; member = TREE_CHAIN (member))
7016     {
7017       tree t = TREE_VALUE (member);
7018
7019       if (TREE_PURPOSE (member))
7020         {
7021           if (TYPE_P (t))
7022             {
7023               /* Build new CLASSTYPE_NESTED_UTDS.  */
7024
7025               tree newtag;
7026               bool class_template_p;
7027
7028               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7029                                   && TYPE_LANG_SPECIFIC (t)
7030                                   && CLASSTYPE_IS_TEMPLATE (t));
7031               /* If the member is a class template, then -- even after
7032                  substitution -- there may be dependent types in the
7033                  template argument list for the class.  We increment
7034                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7035                  that function will assume that no types are dependent
7036                  when outside of a template.  */
7037               if (class_template_p)
7038                 ++processing_template_decl;
7039               newtag = tsubst (t, args, tf_error, NULL_TREE);
7040               if (class_template_p)
7041                 --processing_template_decl;
7042               if (newtag == error_mark_node)
7043                 continue;
7044
7045               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7046                 {
7047                   tree name = TYPE_IDENTIFIER (t);
7048
7049                   if (class_template_p)
7050                     /* Unfortunately, lookup_template_class sets
7051                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7052                        instantiation (i.e., for the type of a member
7053                        template class nested within a template class.)
7054                        This behavior is required for
7055                        maybe_process_partial_specialization to work
7056                        correctly, but is not accurate in this case;
7057                        the TAG is not an instantiation of anything.
7058                        (The corresponding TEMPLATE_DECL is an
7059                        instantiation, but the TYPE is not.) */
7060                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7061
7062                   /* Now, we call pushtag to put this NEWTAG into the scope of
7063                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7064                      pushtag calling push_template_decl.  We don't have to do
7065                      this for enums because it will already have been done in
7066                      tsubst_enum.  */
7067                   if (name)
7068                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7069                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7070                 }
7071             }
7072           else if (TREE_CODE (t) == FUNCTION_DECL
7073                    || DECL_FUNCTION_TEMPLATE_P (t))
7074             {
7075               /* Build new TYPE_METHODS.  */
7076               tree r;
7077
7078               if (TREE_CODE (t) == TEMPLATE_DECL)
7079                 ++processing_template_decl;
7080               r = tsubst (t, args, tf_error, NULL_TREE);
7081               if (TREE_CODE (t) == TEMPLATE_DECL)
7082                 --processing_template_decl;
7083               set_current_access_from_decl (r);
7084               finish_member_declaration (r);
7085             }
7086           else
7087             {
7088               /* Build new TYPE_FIELDS.  */
7089               if (TREE_CODE (t) == STATIC_ASSERT)
7090                 {
7091                   tree condition = 
7092                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7093                                  tf_warning_or_error, NULL_TREE,
7094                                  /*integral_constant_expression_p=*/true);
7095                   finish_static_assert (condition,
7096                                         STATIC_ASSERT_MESSAGE (t), 
7097                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7098                                         /*member_p=*/true);
7099                 }
7100               else if (TREE_CODE (t) != CONST_DECL)
7101                 {
7102                   tree r;
7103
7104                   /* The the file and line for this declaration, to
7105                      assist in error message reporting.  Since we
7106                      called push_tinst_level above, we don't need to
7107                      restore these.  */
7108                   input_location = DECL_SOURCE_LOCATION (t);
7109
7110                   if (TREE_CODE (t) == TEMPLATE_DECL)
7111                     ++processing_template_decl;
7112                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7113                   if (TREE_CODE (t) == TEMPLATE_DECL)
7114                     --processing_template_decl;
7115                   if (TREE_CODE (r) == VAR_DECL)
7116                     {
7117                       /* In [temp.inst]:
7118
7119                            [t]he initialization (and any associated
7120                            side-effects) of a static data member does
7121                            not occur unless the static data member is
7122                            itself used in a way that requires the
7123                            definition of the static data member to
7124                            exist.
7125
7126                          Therefore, we do not substitute into the
7127                          initialized for the static data member here.  */
7128                       finish_static_data_member_decl
7129                         (r,
7130                          /*init=*/NULL_TREE,
7131                          /*init_const_expr_p=*/false,
7132                          /*asmspec_tree=*/NULL_TREE,
7133                          /*flags=*/0);
7134                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7135                         check_static_variable_definition (r, TREE_TYPE (r));
7136                     }
7137                   else if (TREE_CODE (r) == FIELD_DECL)
7138                     {
7139                       /* Determine whether R has a valid type and can be
7140                          completed later.  If R is invalid, then it is
7141                          replaced by error_mark_node so that it will not be
7142                          added to TYPE_FIELDS.  */
7143                       tree rtype = TREE_TYPE (r);
7144                       if (can_complete_type_without_circularity (rtype))
7145                         complete_type (rtype);
7146
7147                       if (!COMPLETE_TYPE_P (rtype))
7148                         {
7149                           cxx_incomplete_type_error (r, rtype);
7150                           r = error_mark_node;
7151                         }
7152                     }
7153
7154                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7155                      such a thing will already have been added to the field
7156                      list by tsubst_enum in finish_member_declaration in the
7157                      CLASSTYPE_NESTED_UTDS case above.  */
7158                   if (!(TREE_CODE (r) == TYPE_DECL
7159                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7160                         && DECL_ARTIFICIAL (r)))
7161                     {
7162                       set_current_access_from_decl (r);
7163                       finish_member_declaration (r);
7164                     }
7165                 }
7166             }
7167         }
7168       else
7169         {
7170           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7171             {
7172               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7173
7174               tree friend_type = t;
7175               bool adjust_processing_template_decl = false;
7176
7177               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7178                 {
7179                   /* template <class T> friend class C;  */
7180                   friend_type = tsubst_friend_class (friend_type, args);
7181                   adjust_processing_template_decl = true;
7182                 }
7183               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7184                 {
7185                   /* template <class T> friend class C::D;  */
7186                   friend_type = tsubst (friend_type, args,
7187                                         tf_warning_or_error, NULL_TREE);
7188                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7189                     friend_type = TREE_TYPE (friend_type);
7190                   adjust_processing_template_decl = true;
7191                 }
7192               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7193                 {
7194                   /* This could be either
7195
7196                        friend class T::C;
7197
7198                      when dependent_type_p is false or
7199
7200                        template <class U> friend class T::C;
7201
7202                      otherwise.  */
7203                   friend_type = tsubst (friend_type, args,
7204                                         tf_warning_or_error, NULL_TREE);
7205                   /* Bump processing_template_decl for correct
7206                      dependent_type_p calculation.  */
7207                   ++processing_template_decl;
7208                   if (dependent_type_p (friend_type))
7209                     adjust_processing_template_decl = true;
7210                   --processing_template_decl;
7211                 }
7212               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7213                        && hidden_name_p (TYPE_NAME (friend_type)))
7214                 {
7215                   /* friend class C;
7216
7217                      where C hasn't been declared yet.  Let's lookup name
7218                      from namespace scope directly, bypassing any name that
7219                      come from dependent base class.  */
7220                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7221
7222                   /* The call to xref_tag_from_type does injection for friend
7223                      classes.  */
7224                   push_nested_namespace (ns);
7225                   friend_type =
7226                     xref_tag_from_type (friend_type, NULL_TREE,
7227                                         /*tag_scope=*/ts_current);
7228                   pop_nested_namespace (ns);
7229                 }
7230               else if (uses_template_parms (friend_type))
7231                 /* friend class C<T>;  */
7232                 friend_type = tsubst (friend_type, args,
7233                                       tf_warning_or_error, NULL_TREE);
7234               /* Otherwise it's
7235
7236                    friend class C;
7237
7238                  where C is already declared or
7239
7240                    friend class C<int>;
7241
7242                  We don't have to do anything in these cases.  */
7243
7244               if (adjust_processing_template_decl)
7245                 /* Trick make_friend_class into realizing that the friend
7246                    we're adding is a template, not an ordinary class.  It's
7247                    important that we use make_friend_class since it will
7248                    perform some error-checking and output cross-reference
7249                    information.  */
7250                 ++processing_template_decl;
7251
7252               if (friend_type != error_mark_node)
7253                 make_friend_class (type, friend_type, /*complain=*/false);
7254
7255               if (adjust_processing_template_decl)
7256                 --processing_template_decl;
7257             }
7258           else
7259             {
7260               /* Build new DECL_FRIENDLIST.  */
7261               tree r;
7262
7263               /* The the file and line for this declaration, to
7264                  assist in error message reporting.  Since we
7265                  called push_tinst_level above, we don't need to
7266                  restore these.  */
7267               input_location = DECL_SOURCE_LOCATION (t);
7268
7269               if (TREE_CODE (t) == TEMPLATE_DECL)
7270                 {
7271                   ++processing_template_decl;
7272                   push_deferring_access_checks (dk_no_check);
7273                 }
7274
7275               r = tsubst_friend_function (t, args);
7276               add_friend (type, r, /*complain=*/false);
7277               if (TREE_CODE (t) == TEMPLATE_DECL)
7278                 {
7279                   pop_deferring_access_checks ();
7280                   --processing_template_decl;
7281                 }
7282             }
7283         }
7284     }
7285
7286   /* Set the file and line number information to whatever is given for
7287      the class itself.  This puts error messages involving generated
7288      implicit functions at a predictable point, and the same point
7289      that would be used for non-template classes.  */
7290   input_location = DECL_SOURCE_LOCATION (typedecl);
7291
7292   unreverse_member_declarations (type);
7293   finish_struct_1 (type);
7294   TYPE_BEING_DEFINED (type) = 0;
7295
7296   /* Now that the class is complete, instantiate default arguments for
7297      any member functions.  We don't do this earlier because the
7298      default arguments may reference members of the class.  */
7299   if (!PRIMARY_TEMPLATE_P (template))
7300     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7301       if (TREE_CODE (t) == FUNCTION_DECL
7302           /* Implicitly generated member functions will not have template
7303              information; they are not instantiations, but instead are
7304              created "fresh" for each instantiation.  */
7305           && DECL_TEMPLATE_INFO (t))
7306         tsubst_default_arguments (t);
7307
7308   pop_nested_class ();
7309   pop_from_top_level ();
7310   pop_deferring_access_checks ();
7311   pop_tinst_level ();
7312
7313   /* The vtable for a template class can be emitted in any translation
7314      unit in which the class is instantiated.  When there is no key
7315      method, however, finish_struct_1 will already have added TYPE to
7316      the keyed_classes list.  */
7317   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7318     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7319
7320   return type;
7321 }
7322
7323 static tree
7324 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7325 {
7326   tree r;
7327
7328   if (!t)
7329     r = t;
7330   else if (TYPE_P (t))
7331     r = tsubst (t, args, complain, in_decl);
7332   else
7333     {
7334       r = tsubst_expr (t, args, complain, in_decl,
7335                        /*integral_constant_expression_p=*/true);
7336       r = fold_non_dependent_expr (r);
7337     }
7338   return r;
7339 }
7340
7341 /* Substitute ARGS into T, which is an pack expansion
7342    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7343    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7344    (if only a partial substitution could be performed) or
7345    ERROR_MARK_NODE if there was an error.  */
7346 tree
7347 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7348                        tree in_decl)
7349 {
7350   tree pattern;
7351   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7352   tree first_arg_pack; int i, len = -1;
7353   tree result;
7354   int incomplete = 0;
7355
7356   gcc_assert (PACK_EXPANSION_P (t));
7357   pattern = PACK_EXPANSION_PATTERN (t);
7358
7359   /* Determine the argument packs that will instantiate the parameter
7360      packs used in the expansion expression. While we're at it,
7361      compute the number of arguments to be expanded and make sure it
7362      is consistent.  */
7363   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7364        pack = TREE_CHAIN (pack))
7365     {
7366       tree parm_pack = TREE_VALUE (pack);
7367       tree arg_pack = NULL_TREE;
7368       tree orig_arg = NULL_TREE;
7369
7370       if (TREE_CODE (parm_pack) == PARM_DECL)
7371         arg_pack = retrieve_local_specialization (parm_pack);
7372       else
7373         {
7374           int level, idx, levels;
7375           template_parm_level_and_index (parm_pack, &level, &idx);
7376
7377           levels = TMPL_ARGS_DEPTH (args);
7378           if (level <= levels)
7379             arg_pack = TMPL_ARG (args, level, idx);
7380         }
7381
7382       orig_arg = arg_pack;
7383       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7384         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7385       
7386       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7387         /* This can only happen if we forget to expand an argument
7388            pack somewhere else. Just return an error, silently.  */
7389         {
7390           result = make_tree_vec (1);
7391           TREE_VEC_ELT (result, 0) = error_mark_node;
7392           return result;
7393         }
7394
7395       if (arg_pack
7396           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7397           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7398         {
7399           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7400           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7401           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7402               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7403             /* The argument pack that the parameter maps to is just an
7404                expansion of the parameter itself, such as one would
7405                find in the implicit typedef of a class inside the
7406                class itself.  Consider this parameter "unsubstituted",
7407                so that we will maintain the outer pack expansion.  */
7408             arg_pack = NULL_TREE;
7409         }
7410           
7411       if (arg_pack)
7412         {
7413           int my_len = 
7414             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7415
7416           /* It's all-or-nothing with incomplete argument packs.  */
7417           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7418             return error_mark_node;
7419           
7420           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7421             incomplete = 1;
7422
7423           if (len < 0)
7424             {
7425               len = my_len;
7426               first_arg_pack = arg_pack;
7427             }
7428           else if (len != my_len)
7429             {
7430               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7431                 error ("mismatched argument pack lengths while expanding "
7432                        "%<%T%>",
7433                        pattern);
7434               else
7435                 error ("mismatched argument pack lengths while expanding "
7436                        "%<%E%>",
7437                        pattern);
7438               return error_mark_node;
7439             }
7440
7441           /* Keep track of the parameter packs and their corresponding
7442              argument packs.  */
7443           packs = tree_cons (parm_pack, arg_pack, packs);
7444           TREE_TYPE (packs) = orig_arg;
7445         }
7446       else
7447         /* We can't substitute for this parameter pack.  */
7448         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7449                                          TREE_VALUE (pack),
7450                                          unsubstituted_packs);
7451     }
7452
7453   /* We cannot expand this expansion expression, because we don't have
7454      all of the argument packs we need. Substitute into the pattern
7455      and return a PACK_EXPANSION_*. The caller will need to deal with
7456      that.  */
7457   if (unsubstituted_packs)
7458     return make_pack_expansion (tsubst (pattern, args, complain, 
7459                                         in_decl));
7460
7461   /* We could not find any argument packs that work.  */
7462   if (len < 0)
7463     return error_mark_node;
7464
7465   /* For each argument in each argument pack, substitute into the
7466      pattern.  */
7467   result = make_tree_vec (len + incomplete);
7468   for (i = 0; i < len + incomplete; ++i)
7469     {
7470       /* For parameter pack, change the substitution of the parameter
7471          pack to the ith argument in its argument pack, then expand
7472          the pattern.  */
7473       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7474         {
7475           tree parm = TREE_PURPOSE (pack);
7476
7477           if (TREE_CODE (parm) == PARM_DECL)
7478             {
7479               /* Select the Ith argument from the pack.  */
7480               tree arg = make_node (ARGUMENT_PACK_SELECT);
7481               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7482               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7483               mark_used (parm);
7484               register_local_specialization (arg, parm);
7485             }
7486           else
7487             {
7488               tree value = parm;
7489               int idx, level;
7490               template_parm_level_and_index (parm, &level, &idx);
7491               
7492               if (i < len) 
7493                 {
7494                   /* Select the Ith argument from the pack. */
7495                   value = make_node (ARGUMENT_PACK_SELECT);
7496                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7497                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7498                 }
7499
7500               /* Update the corresponding argument.  */
7501               TMPL_ARG (args, level, idx) = value;
7502             }
7503         }
7504
7505       /* Substitute into the PATTERN with the altered arguments.  */
7506       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7507         TREE_VEC_ELT (result, i) = 
7508           tsubst_expr (pattern, args, complain, in_decl,
7509                        /*integral_constant_expression_p=*/false);
7510       else
7511         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7512
7513       if (i == len)
7514         /* When we have incomplete argument packs, the last "expanded"
7515            result is itself a pack expansion, which allows us
7516            to deduce more arguments.  */
7517         TREE_VEC_ELT (result, i) = 
7518           make_pack_expansion (TREE_VEC_ELT (result, i));
7519
7520       if (TREE_VEC_ELT (result, i) == error_mark_node)
7521         {
7522           result = error_mark_node;
7523           break;
7524         }
7525     }
7526   
7527   /* Update ARGS to restore the substitution from parameter packs to
7528      their argument packs.  */
7529   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7530     {
7531       tree parm = TREE_PURPOSE (pack);
7532
7533       if (TREE_CODE (parm) == PARM_DECL)
7534         register_local_specialization (TREE_TYPE (pack), parm);
7535       else
7536         {
7537           int idx, level;
7538           template_parm_level_and_index (parm, &level, &idx);
7539           
7540           /* Update the corresponding argument.  */
7541           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7542             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7543               TREE_TYPE (pack);
7544           else
7545             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7546         }
7547     }
7548
7549   return result;
7550 }
7551
7552 /* Substitute ARGS into the vector or list of template arguments T.  */
7553
7554 static tree
7555 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7556 {
7557   tree orig_t = t;
7558   int len = TREE_VEC_LENGTH (t);
7559   int need_new = 0, i, expanded_len_adjust = 0, out;
7560   tree *elts = (tree *) alloca (len * sizeof (tree));
7561
7562   for (i = 0; i < len; i++)
7563     {
7564       tree orig_arg = TREE_VEC_ELT (t, i);
7565       tree new_arg;
7566
7567       if (TREE_CODE (orig_arg) == TREE_VEC)
7568         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7569       else if (PACK_EXPANSION_P (orig_arg))
7570         {
7571           /* Substitute into an expansion expression.  */
7572           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7573
7574           if (TREE_CODE (new_arg) == TREE_VEC)
7575             /* Add to the expanded length adjustment the number of
7576                expanded arguments. We subtract one from this
7577                measurement, because the argument pack expression
7578                itself is already counted as 1 in
7579                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7580                the argument pack is empty.  */
7581             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7582         }
7583       else if (ARGUMENT_PACK_P (orig_arg))
7584         {
7585           /* Substitute into each of the arguments.  */
7586           new_arg = make_node (TREE_CODE (orig_arg));
7587           
7588           SET_ARGUMENT_PACK_ARGS (
7589             new_arg,
7590             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7591                                   args, complain, in_decl));
7592
7593           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7594             new_arg = error_mark_node;
7595
7596           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7597             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7598                                           complain, in_decl);
7599             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7600
7601             if (TREE_TYPE (new_arg) == error_mark_node)
7602               new_arg = error_mark_node;
7603           }
7604         }
7605       else
7606         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7607
7608       if (new_arg == error_mark_node)
7609         return error_mark_node;
7610
7611       elts[i] = new_arg;
7612       if (new_arg != orig_arg)
7613         need_new = 1;
7614     }
7615
7616   if (!need_new)
7617     return t;
7618
7619   /* Make space for the expanded arguments coming from template
7620      argument packs.  */
7621   t = make_tree_vec (len + expanded_len_adjust);
7622   for (i = 0, out = 0; i < len; i++)
7623     {
7624       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7625            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7626           && TREE_CODE (elts[i]) == TREE_VEC)
7627         {
7628           int idx;
7629
7630           /* Now expand the template argument pack "in place".  */
7631           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7632             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7633         }
7634       else
7635         {
7636           TREE_VEC_ELT (t, out) = elts[i];
7637           out++;
7638         }
7639     }
7640
7641   return t;
7642 }
7643
7644 /* Return the result of substituting ARGS into the template parameters
7645    given by PARMS.  If there are m levels of ARGS and m + n levels of
7646    PARMS, then the result will contain n levels of PARMS.  For
7647    example, if PARMS is `template <class T> template <class U>
7648    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7649    result will be `template <int*, double, class V>'.  */
7650
7651 static tree
7652 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7653 {
7654   tree r = NULL_TREE;
7655   tree* new_parms;
7656
7657   /* When substituting into a template, we must set
7658      PROCESSING_TEMPLATE_DECL as the template parameters may be
7659      dependent if they are based on one-another, and the dependency
7660      predicates are short-circuit outside of templates.  */
7661   ++processing_template_decl;
7662
7663   for (new_parms = &r;
7664        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7665        new_parms = &(TREE_CHAIN (*new_parms)),
7666          parms = TREE_CHAIN (parms))
7667     {
7668       tree new_vec =
7669         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7670       int i;
7671
7672       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7673         {
7674           tree tuple;
7675           tree default_value;
7676           tree parm_decl;
7677
7678           if (parms == error_mark_node)
7679             continue;
7680
7681           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7682
7683           if (tuple == error_mark_node)
7684             continue;
7685
7686           default_value = TREE_PURPOSE (tuple);
7687           parm_decl = TREE_VALUE (tuple);
7688
7689           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7690           if (TREE_CODE (parm_decl) == PARM_DECL
7691               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7692             parm_decl = error_mark_node;
7693           default_value = tsubst_template_arg (default_value, args,
7694                                                complain, NULL_TREE);
7695
7696           tuple = build_tree_list (default_value, parm_decl);
7697           TREE_VEC_ELT (new_vec, i) = tuple;
7698         }
7699
7700       *new_parms =
7701         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7702                              - TMPL_ARGS_DEPTH (args)),
7703                    new_vec, NULL_TREE);
7704     }
7705
7706   --processing_template_decl;
7707
7708   return r;
7709 }
7710
7711 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7712    type T.  If T is not an aggregate or enumeration type, it is
7713    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7714    ENTERING_SCOPE is nonzero, T is the context for a template which
7715    we are presently tsubst'ing.  Return the substituted value.  */
7716
7717 static tree
7718 tsubst_aggr_type (tree t,
7719                   tree args,
7720                   tsubst_flags_t complain,
7721                   tree in_decl,
7722                   int entering_scope)
7723 {
7724   if (t == NULL_TREE)
7725     return NULL_TREE;
7726
7727   switch (TREE_CODE (t))
7728     {
7729     case RECORD_TYPE:
7730       if (TYPE_PTRMEMFUNC_P (t))
7731         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7732
7733       /* Else fall through.  */
7734     case ENUMERAL_TYPE:
7735     case UNION_TYPE:
7736       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
7737         {
7738           tree argvec;
7739           tree context;
7740           tree r;
7741           bool saved_skip_evaluation;
7742
7743           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7744           saved_skip_evaluation = skip_evaluation;
7745           skip_evaluation = false;
7746
7747           /* First, determine the context for the type we are looking
7748              up.  */
7749           context = TYPE_CONTEXT (t);
7750           if (context)
7751             {
7752               context = tsubst_aggr_type (context, args, complain,
7753                                           in_decl, /*entering_scope=*/1);
7754               /* If context is a nested class inside a class template,
7755                  it may still need to be instantiated (c++/33959).  */
7756               if (TYPE_P (context))
7757                 context = complete_type (context);
7758             }
7759
7760           /* Then, figure out what arguments are appropriate for the
7761              type we are trying to find.  For example, given:
7762
7763                template <class T> struct S;
7764                template <class T, class U> void f(T, U) { S<U> su; }
7765
7766              and supposing that we are instantiating f<int, double>,
7767              then our ARGS will be {int, double}, but, when looking up
7768              S we only want {double}.  */
7769           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7770                                          complain, in_decl);
7771           if (argvec == error_mark_node)
7772             r = error_mark_node;
7773           else
7774             {
7775               r = lookup_template_class (t, argvec, in_decl, context,
7776                                          entering_scope, complain);
7777               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7778             }
7779
7780           skip_evaluation = saved_skip_evaluation;
7781
7782           return r;
7783         }
7784       else
7785         /* This is not a template type, so there's nothing to do.  */
7786         return t;
7787
7788     default:
7789       return tsubst (t, args, complain, in_decl);
7790     }
7791 }
7792
7793 /* Substitute into the default argument ARG (a default argument for
7794    FN), which has the indicated TYPE.  */
7795
7796 tree
7797 tsubst_default_argument (tree fn, tree type, tree arg)
7798 {
7799   tree saved_class_ptr = NULL_TREE;
7800   tree saved_class_ref = NULL_TREE;
7801
7802   /* This default argument came from a template.  Instantiate the
7803      default argument here, not in tsubst.  In the case of
7804      something like:
7805
7806        template <class T>
7807        struct S {
7808          static T t();
7809          void f(T = t());
7810        };
7811
7812      we must be careful to do name lookup in the scope of S<T>,
7813      rather than in the current class.  */
7814   push_access_scope (fn);
7815   /* The "this" pointer is not valid in a default argument.  */
7816   if (cfun)
7817     {
7818       saved_class_ptr = current_class_ptr;
7819       cp_function_chain->x_current_class_ptr = NULL_TREE;
7820       saved_class_ref = current_class_ref;
7821       cp_function_chain->x_current_class_ref = NULL_TREE;
7822     }
7823
7824   push_deferring_access_checks(dk_no_deferred);
7825   /* The default argument expression may cause implicitly defined
7826      member functions to be synthesized, which will result in garbage
7827      collection.  We must treat this situation as if we were within
7828      the body of function so as to avoid collecting live data on the
7829      stack.  */
7830   ++function_depth;
7831   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
7832                      tf_warning_or_error, NULL_TREE,
7833                      /*integral_constant_expression_p=*/false);
7834   --function_depth;
7835   pop_deferring_access_checks();
7836
7837   /* Restore the "this" pointer.  */
7838   if (cfun)
7839     {
7840       cp_function_chain->x_current_class_ptr = saved_class_ptr;
7841       cp_function_chain->x_current_class_ref = saved_class_ref;
7842     }
7843
7844   pop_access_scope (fn);
7845
7846   /* Make sure the default argument is reasonable.  */
7847   arg = check_default_argument (type, arg);
7848
7849   return arg;
7850 }
7851
7852 /* Substitute into all the default arguments for FN.  */
7853
7854 static void
7855 tsubst_default_arguments (tree fn)
7856 {
7857   tree arg;
7858   tree tmpl_args;
7859
7860   tmpl_args = DECL_TI_ARGS (fn);
7861
7862   /* If this function is not yet instantiated, we certainly don't need
7863      its default arguments.  */
7864   if (uses_template_parms (tmpl_args))
7865     return;
7866
7867   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
7868        arg;
7869        arg = TREE_CHAIN (arg))
7870     if (TREE_PURPOSE (arg))
7871       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
7872                                                     TREE_VALUE (arg),
7873                                                     TREE_PURPOSE (arg));
7874 }
7875
7876 /* Substitute the ARGS into the T, which is a _DECL.  Return the
7877    result of the substitution.  Issue error and warning messages under
7878    control of COMPLAIN.  */
7879
7880 static tree
7881 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
7882 {
7883   location_t saved_loc;
7884   tree r = NULL_TREE;
7885   tree in_decl = t;
7886
7887   /* Set the filename and linenumber to improve error-reporting.  */
7888   saved_loc = input_location;
7889   input_location = DECL_SOURCE_LOCATION (t);
7890
7891   switch (TREE_CODE (t))
7892     {
7893     case TEMPLATE_DECL:
7894       {
7895         /* We can get here when processing a member function template,
7896            member class template, and template template parameter of
7897            a template class.  */
7898         tree decl = DECL_TEMPLATE_RESULT (t);
7899         tree spec;
7900         tree tmpl_args;
7901         tree full_args;
7902
7903         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
7904           {
7905             /* Template template parameter is treated here.  */
7906             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7907             if (new_type == error_mark_node)
7908               return error_mark_node;
7909
7910             r = copy_decl (t);
7911             TREE_CHAIN (r) = NULL_TREE;
7912             TREE_TYPE (r) = new_type;
7913             DECL_TEMPLATE_RESULT (r)
7914               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
7915             DECL_TEMPLATE_PARMS (r)
7916               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
7917                                        complain);
7918             TYPE_NAME (new_type) = r;
7919             break;
7920           }
7921
7922         /* We might already have an instance of this template.
7923            The ARGS are for the surrounding class type, so the
7924            full args contain the tsubst'd args for the context,
7925            plus the innermost args from the template decl.  */
7926         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
7927           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
7928           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
7929         /* Because this is a template, the arguments will still be
7930            dependent, even after substitution.  If
7931            PROCESSING_TEMPLATE_DECL is not set, the dependency
7932            predicates will short-circuit.  */
7933         ++processing_template_decl;
7934         full_args = tsubst_template_args (tmpl_args, args,
7935                                           complain, in_decl);
7936         --processing_template_decl;
7937         if (full_args == error_mark_node)
7938           return error_mark_node;
7939
7940         /* tsubst_template_args doesn't copy the vector if
7941            nothing changed.  But, *something* should have
7942            changed.  */
7943         gcc_assert (full_args != tmpl_args);
7944
7945         spec = retrieve_specialization (t, full_args,
7946                                         /*class_specializations_p=*/true);
7947         if (spec != NULL_TREE)
7948           {
7949             r = spec;
7950             break;
7951           }
7952
7953         /* Make a new template decl.  It will be similar to the
7954            original, but will record the current template arguments.
7955            We also create a new function declaration, which is just
7956            like the old one, but points to this new template, rather
7957            than the old one.  */
7958         r = copy_decl (t);
7959         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
7960         TREE_CHAIN (r) = NULL_TREE;
7961
7962         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
7963
7964         if (TREE_CODE (decl) == TYPE_DECL)
7965           {
7966             tree new_type;
7967             ++processing_template_decl;
7968             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7969             --processing_template_decl;
7970             if (new_type == error_mark_node)
7971               return error_mark_node;
7972
7973             TREE_TYPE (r) = new_type;
7974             CLASSTYPE_TI_TEMPLATE (new_type) = r;
7975             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
7976             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
7977             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
7978           }
7979         else
7980           {
7981             tree new_decl;
7982             ++processing_template_decl;
7983             new_decl = tsubst (decl, args, complain, in_decl);
7984             --processing_template_decl;
7985             if (new_decl == error_mark_node)
7986               return error_mark_node;
7987
7988             DECL_TEMPLATE_RESULT (r) = new_decl;
7989             DECL_TI_TEMPLATE (new_decl) = r;
7990             TREE_TYPE (r) = TREE_TYPE (new_decl);
7991             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
7992             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
7993           }
7994
7995         SET_DECL_IMPLICIT_INSTANTIATION (r);
7996         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
7997         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
7998
7999         /* The template parameters for this new template are all the
8000            template parameters for the old template, except the
8001            outermost level of parameters.  */
8002         DECL_TEMPLATE_PARMS (r)
8003           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8004                                    complain);
8005
8006         if (PRIMARY_TEMPLATE_P (t))
8007           DECL_PRIMARY_TEMPLATE (r) = r;
8008
8009         if (TREE_CODE (decl) != TYPE_DECL)
8010           /* Record this non-type partial instantiation.  */
8011           register_specialization (r, t,
8012                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8013                                    false);
8014       }
8015       break;
8016
8017     case FUNCTION_DECL:
8018       {
8019         tree ctx;
8020         tree argvec = NULL_TREE;
8021         tree *friends;
8022         tree gen_tmpl;
8023         tree type;
8024         int member;
8025         int args_depth;
8026         int parms_depth;
8027
8028         /* Nobody should be tsubst'ing into non-template functions.  */
8029         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8030
8031         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8032           {
8033             tree spec;
8034             bool dependent_p;
8035
8036             /* If T is not dependent, just return it.  We have to
8037                increment PROCESSING_TEMPLATE_DECL because
8038                value_dependent_expression_p assumes that nothing is
8039                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8040             ++processing_template_decl;
8041             dependent_p = value_dependent_expression_p (t);
8042             --processing_template_decl;
8043             if (!dependent_p)
8044               return t;
8045
8046             /* Calculate the most general template of which R is a
8047                specialization, and the complete set of arguments used to
8048                specialize R.  */
8049             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8050             argvec = tsubst_template_args (DECL_TI_ARGS
8051                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8052                                            args, complain, in_decl);
8053
8054             /* Check to see if we already have this specialization.  */
8055             spec = retrieve_specialization (gen_tmpl, argvec,
8056                                             /*class_specializations_p=*/false);
8057
8058             if (spec)
8059               {
8060                 r = spec;
8061                 break;
8062               }
8063
8064             /* We can see more levels of arguments than parameters if
8065                there was a specialization of a member template, like
8066                this:
8067
8068                  template <class T> struct S { template <class U> void f(); }
8069                  template <> template <class U> void S<int>::f(U);
8070
8071                Here, we'll be substituting into the specialization,
8072                because that's where we can find the code we actually
8073                want to generate, but we'll have enough arguments for
8074                the most general template.
8075
8076                We also deal with the peculiar case:
8077
8078                  template <class T> struct S {
8079                    template <class U> friend void f();
8080                  };
8081                  template <class U> void f() {}
8082                  template S<int>;
8083                  template void f<double>();
8084
8085                Here, the ARGS for the instantiation of will be {int,
8086                double}.  But, we only need as many ARGS as there are
8087                levels of template parameters in CODE_PATTERN.  We are
8088                careful not to get fooled into reducing the ARGS in
8089                situations like:
8090
8091                  template <class T> struct S { template <class U> void f(U); }
8092                  template <class T> template <> void S<T>::f(int) {}
8093
8094                which we can spot because the pattern will be a
8095                specialization in this case.  */
8096             args_depth = TMPL_ARGS_DEPTH (args);
8097             parms_depth =
8098               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8099             if (args_depth > parms_depth
8100                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8101               args = get_innermost_template_args (args, parms_depth);
8102           }
8103         else
8104           {
8105             /* This special case arises when we have something like this:
8106
8107                  template <class T> struct S {
8108                    friend void f<int>(int, double);
8109                  };
8110
8111                Here, the DECL_TI_TEMPLATE for the friend declaration
8112                will be an IDENTIFIER_NODE.  We are being called from
8113                tsubst_friend_function, and we want only to create a
8114                new decl (R) with appropriate types so that we can call
8115                determine_specialization.  */
8116             gen_tmpl = NULL_TREE;
8117           }
8118
8119         if (DECL_CLASS_SCOPE_P (t))
8120           {
8121             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8122               member = 2;
8123             else
8124               member = 1;
8125             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8126                                     complain, t, /*entering_scope=*/1);
8127           }
8128         else
8129           {
8130             member = 0;
8131             ctx = DECL_CONTEXT (t);
8132           }
8133         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8134         if (type == error_mark_node)
8135           return error_mark_node;
8136
8137         /* We do NOT check for matching decls pushed separately at this
8138            point, as they may not represent instantiations of this
8139            template, and in any case are considered separate under the
8140            discrete model.  */
8141         r = copy_decl (t);
8142         DECL_USE_TEMPLATE (r) = 0;
8143         TREE_TYPE (r) = type;
8144         /* Clear out the mangled name and RTL for the instantiation.  */
8145         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8146         SET_DECL_RTL (r, NULL_RTX);
8147         DECL_INITIAL (r) = NULL_TREE;
8148         DECL_CONTEXT (r) = ctx;
8149
8150         if (member && DECL_CONV_FN_P (r))
8151           /* Type-conversion operator.  Reconstruct the name, in
8152              case it's the name of one of the template's parameters.  */
8153           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8154
8155         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8156                                      complain, t);
8157         DECL_RESULT (r) = NULL_TREE;
8158
8159         TREE_STATIC (r) = 0;
8160         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8161         DECL_EXTERNAL (r) = 1;
8162         /* If this is an instantiation of a function with internal
8163            linkage, we already know what object file linkage will be
8164            assigned to the instantiation.  */
8165         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8166         DECL_DEFER_OUTPUT (r) = 0;
8167         TREE_CHAIN (r) = NULL_TREE;
8168         DECL_PENDING_INLINE_INFO (r) = 0;
8169         DECL_PENDING_INLINE_P (r) = 0;
8170         DECL_SAVED_TREE (r) = NULL_TREE;
8171         TREE_USED (r) = 0;
8172         if (DECL_CLONED_FUNCTION (r))
8173           {
8174             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
8175                                                args, complain, t);
8176             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
8177             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
8178           }
8179
8180         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8181            this in the special friend case mentioned above where
8182            GEN_TMPL is NULL.  */
8183         if (gen_tmpl)
8184           {
8185             DECL_TEMPLATE_INFO (r)
8186               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8187             SET_DECL_IMPLICIT_INSTANTIATION (r);
8188             register_specialization (r, gen_tmpl, argvec, false);
8189
8190             /* We're not supposed to instantiate default arguments
8191                until they are called, for a template.  But, for a
8192                declaration like:
8193
8194                  template <class T> void f ()
8195                  { extern void g(int i = T()); }
8196
8197                we should do the substitution when the template is
8198                instantiated.  We handle the member function case in
8199                instantiate_class_template since the default arguments
8200                might refer to other members of the class.  */
8201             if (!member
8202                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8203                 && !uses_template_parms (argvec))
8204               tsubst_default_arguments (r);
8205           }
8206         else
8207           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8208
8209         /* Copy the list of befriending classes.  */
8210         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8211              *friends;
8212              friends = &TREE_CHAIN (*friends))
8213           {
8214             *friends = copy_node (*friends);
8215             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8216                                             args, complain,
8217                                             in_decl);
8218           }
8219
8220         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8221           {
8222             maybe_retrofit_in_chrg (r);
8223             if (DECL_CONSTRUCTOR_P (r))
8224               grok_ctor_properties (ctx, r);
8225             /* If this is an instantiation of a member template, clone it.
8226                If it isn't, that'll be handled by
8227                clone_constructors_and_destructors.  */
8228             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8229               clone_function_decl (r, /*update_method_vec_p=*/0);
8230           }
8231         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8232                  && !grok_op_properties (r, (complain & tf_error) != 0))
8233           return error_mark_node;
8234
8235         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8236           SET_DECL_FRIEND_CONTEXT (r,
8237                                    tsubst (DECL_FRIEND_CONTEXT (t),
8238                                             args, complain, in_decl));
8239
8240         /* Possibly limit visibility based on template args.  */
8241         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8242         if (DECL_VISIBILITY_SPECIFIED (t))
8243           {
8244             DECL_VISIBILITY_SPECIFIED (r) = 0;
8245             DECL_ATTRIBUTES (r)
8246               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8247           }
8248         determine_visibility (r);
8249
8250         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8251                                         args, complain, in_decl);
8252       }
8253       break;
8254
8255     case PARM_DECL:
8256       {
8257         tree type = NULL_TREE;
8258         int i, len = 1;
8259         tree expanded_types = NULL_TREE;
8260         tree prev_r = NULL_TREE;
8261         tree first_r = NULL_TREE;
8262
8263         if (FUNCTION_PARAMETER_PACK_P (t))
8264           {
8265             /* If there is a local specialization that isn't a
8266                parameter pack, it means that we're doing a "simple"
8267                substitution from inside tsubst_pack_expansion. Just
8268                return the local specialization (which will be a single
8269                parm).  */
8270             tree spec = retrieve_local_specialization (t);
8271             if (spec 
8272                 && TREE_CODE (spec) == PARM_DECL
8273                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8274               return spec;
8275
8276             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8277                the parameters in this function parameter pack.  */
8278             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8279                                                     complain, in_decl);
8280             if (TREE_CODE (expanded_types) == TREE_VEC)
8281               {
8282                 len = TREE_VEC_LENGTH (expanded_types);
8283
8284                 /* Zero-length parameter packs are boring. Just substitute
8285                    into the chain.  */
8286                 if (len == 0)
8287                   return tsubst (TREE_CHAIN (t), args, complain, 
8288                                  TREE_CHAIN (t));
8289               }
8290             else
8291               {
8292                 /* All we did was update the type. Make a note of that.  */
8293                 type = expanded_types;
8294                 expanded_types = NULL_TREE;
8295               }
8296           }
8297
8298         /* Loop through all of the parameter's we'll build. When T is
8299            a function parameter pack, LEN is the number of expanded
8300            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8301         r = NULL_TREE;
8302         for (i = 0; i < len; ++i)
8303           {
8304             prev_r = r;
8305             r = copy_node (t);
8306             if (DECL_TEMPLATE_PARM_P (t))
8307               SET_DECL_TEMPLATE_PARM_P (r);
8308
8309             if (expanded_types)
8310               /* We're on the Ith parameter of the function parameter
8311                  pack.  */
8312               {
8313                 /* Get the Ith type.  */
8314                 type = TREE_VEC_ELT (expanded_types, i);
8315
8316                 if (DECL_NAME (r))
8317                   /* Rename the parameter to include the index.  */
8318                   DECL_NAME (r) =
8319                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8320               }
8321             else if (!type)
8322               /* We're dealing with a normal parameter.  */
8323               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8324
8325             type = type_decays_to (type);
8326             TREE_TYPE (r) = type;
8327             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8328
8329             if (DECL_INITIAL (r))
8330               {
8331                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8332                   DECL_INITIAL (r) = TREE_TYPE (r);
8333                 else
8334                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8335                                              complain, in_decl);
8336               }
8337
8338             DECL_CONTEXT (r) = NULL_TREE;
8339
8340             if (!DECL_TEMPLATE_PARM_P (r))
8341               DECL_ARG_TYPE (r) = type_passed_as (type);
8342
8343             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8344                                             args, complain, in_decl);
8345
8346             /* Keep track of the first new parameter we
8347                generate. That's what will be returned to the
8348                caller.  */
8349             if (!first_r)
8350               first_r = r;
8351
8352             /* Build a proper chain of parameters when substituting
8353                into a function parameter pack.  */
8354             if (prev_r)
8355               TREE_CHAIN (prev_r) = r;
8356           }
8357
8358         if (TREE_CHAIN (t))
8359           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8360                                    complain, TREE_CHAIN (t));
8361
8362         /* FIRST_R contains the start of the chain we've built.  */
8363         r = first_r;
8364       }
8365       break;
8366
8367     case FIELD_DECL:
8368       {
8369         tree type;
8370
8371         r = copy_decl (t);
8372         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8373         if (type == error_mark_node)
8374           return error_mark_node;
8375         TREE_TYPE (r) = type;
8376         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8377
8378         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8379         DECL_INITIAL (r)
8380           = tsubst_expr (DECL_INITIAL (t), args,
8381                          complain, in_decl,
8382                          /*integral_constant_expression_p=*/true);
8383         /* We don't have to set DECL_CONTEXT here; it is set by
8384            finish_member_declaration.  */
8385         TREE_CHAIN (r) = NULL_TREE;
8386         if (VOID_TYPE_P (type))
8387           error ("instantiation of %q+D as type %qT", r, type);
8388
8389         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8390                                         args, complain, in_decl);
8391       }
8392       break;
8393
8394     case USING_DECL:
8395       /* We reach here only for member using decls.  */
8396       if (DECL_DEPENDENT_P (t))
8397         {
8398           r = do_class_using_decl
8399             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8400              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8401           if (!r)
8402             r = error_mark_node;
8403         }
8404       else
8405         {
8406           r = copy_node (t);
8407           TREE_CHAIN (r) = NULL_TREE;
8408         }
8409       break;
8410
8411     case TYPE_DECL:
8412     case VAR_DECL:
8413       {
8414         tree argvec = NULL_TREE;
8415         tree gen_tmpl = NULL_TREE;
8416         tree spec;
8417         tree tmpl = NULL_TREE;
8418         tree ctx;
8419         tree type = NULL_TREE;
8420         bool local_p;
8421
8422         if (TREE_CODE (t) == TYPE_DECL
8423             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8424           {
8425             /* If this is the canonical decl, we don't have to
8426                mess with instantiations, and often we can't (for
8427                typename, template type parms and such).  Note that
8428                TYPE_NAME is not correct for the above test if
8429                we've copied the type for a typedef.  */
8430             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8431             if (type == error_mark_node)
8432               return error_mark_node;
8433             r = TYPE_NAME (type);
8434             break;
8435           }
8436
8437         /* Check to see if we already have the specialization we
8438            need.  */
8439         spec = NULL_TREE;
8440         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8441           {
8442             /* T is a static data member or namespace-scope entity.
8443                We have to substitute into namespace-scope variables
8444                (even though such entities are never templates) because
8445                of cases like:
8446                
8447                  template <class T> void f() { extern T t; }
8448
8449                where the entity referenced is not known until
8450                instantiation time.  */
8451             local_p = false;
8452             ctx = DECL_CONTEXT (t);
8453             if (DECL_CLASS_SCOPE_P (t))
8454               {
8455                 ctx = tsubst_aggr_type (ctx, args,
8456                                         complain,
8457                                         in_decl, /*entering_scope=*/1);
8458                 /* If CTX is unchanged, then T is in fact the
8459                    specialization we want.  That situation occurs when
8460                    referencing a static data member within in its own
8461                    class.  We can use pointer equality, rather than
8462                    same_type_p, because DECL_CONTEXT is always
8463                    canonical.  */
8464                 if (ctx == DECL_CONTEXT (t))
8465                   spec = t;
8466               }
8467
8468             if (!spec)
8469               {
8470                 tmpl = DECL_TI_TEMPLATE (t);
8471                 gen_tmpl = most_general_template (tmpl);
8472                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8473                 spec = (retrieve_specialization 
8474                         (gen_tmpl, argvec,
8475                          /*class_specializations_p=*/false));
8476               }
8477           }
8478         else
8479           {
8480             /* A local variable.  */
8481             local_p = true;
8482             /* Subsequent calls to pushdecl will fill this in.  */
8483             ctx = NULL_TREE;
8484             spec = retrieve_local_specialization (t);
8485           }
8486         /* If we already have the specialization we need, there is
8487            nothing more to do.  */ 
8488         if (spec)
8489           {
8490             r = spec;
8491             break;
8492           }
8493
8494         /* Create a new node for the specialization we need.  */
8495         r = copy_decl (t);
8496         if (type == NULL_TREE)
8497           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8498         if (TREE_CODE (r) == VAR_DECL)
8499           {
8500             /* Even if the original location is out of scope, the
8501                newly substituted one is not.  */
8502             DECL_DEAD_FOR_LOCAL (r) = 0;
8503             DECL_INITIALIZED_P (r) = 0;
8504             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8505             if (type == error_mark_node)
8506               return error_mark_node;
8507             if (TREE_CODE (type) == FUNCTION_TYPE)
8508               {
8509                 /* It may seem that this case cannot occur, since:
8510
8511                      typedef void f();
8512                      void g() { f x; }
8513
8514                    declares a function, not a variable.  However:
8515       
8516                      typedef void f();
8517                      template <typename T> void g() { T t; }
8518                      template void g<f>();
8519
8520                    is an attempt to declare a variable with function
8521                    type.  */
8522                 error ("variable %qD has function type",
8523                        /* R is not yet sufficiently initialized, so we
8524                           just use its name.  */
8525                        DECL_NAME (r));
8526                 return error_mark_node;
8527               }
8528             type = complete_type (type);
8529             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8530               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8531             type = check_var_type (DECL_NAME (r), type);
8532
8533             if (DECL_HAS_VALUE_EXPR_P (t))
8534               {
8535                 tree ve = DECL_VALUE_EXPR (t);
8536                 ve = tsubst_expr (ve, args, complain, in_decl,
8537                                   /*constant_expression_p=*/false);
8538                 SET_DECL_VALUE_EXPR (r, ve);
8539               }
8540           }
8541         else if (DECL_SELF_REFERENCE_P (t))
8542           SET_DECL_SELF_REFERENCE_P (r);
8543         TREE_TYPE (r) = type;
8544         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8545         DECL_CONTEXT (r) = ctx;
8546         /* Clear out the mangled name and RTL for the instantiation.  */
8547         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8548         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8549           SET_DECL_RTL (r, NULL_RTX);
8550         /* The initializer must not be expanded until it is required;
8551            see [temp.inst].  */
8552         DECL_INITIAL (r) = NULL_TREE;
8553         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8554           SET_DECL_RTL (r, NULL_RTX);
8555         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8556         if (TREE_CODE (r) == VAR_DECL)
8557           {
8558             /* Possibly limit visibility based on template args.  */
8559             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8560             if (DECL_VISIBILITY_SPECIFIED (t))
8561               {
8562                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8563                 DECL_ATTRIBUTES (r)
8564                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8565               }
8566             determine_visibility (r);
8567           }
8568         /* Preserve a typedef that names a type.  */
8569         else if (TREE_CODE (r) == TYPE_DECL
8570                  && DECL_ORIGINAL_TYPE (t)
8571                  && type != error_mark_node)
8572           {
8573             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8574                                              args, complain, in_decl);
8575             TREE_TYPE (r) = type = build_variant_type_copy (type);
8576             TYPE_NAME (type) = r;
8577           }
8578
8579         if (!local_p)
8580           {
8581             /* A static data member declaration is always marked
8582                external when it is declared in-class, even if an
8583                initializer is present.  We mimic the non-template
8584                processing here.  */
8585             DECL_EXTERNAL (r) = 1;
8586
8587             register_specialization (r, gen_tmpl, argvec, false);
8588             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8589             SET_DECL_IMPLICIT_INSTANTIATION (r);
8590           }
8591         else
8592           register_local_specialization (r, t);
8593
8594         TREE_CHAIN (r) = NULL_TREE;
8595
8596         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
8597                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
8598                                         args, complain, in_decl);
8599         layout_decl (r, 0);
8600       }
8601       break;
8602
8603     default:
8604       gcc_unreachable ();
8605     }
8606
8607   /* Restore the file and line information.  */
8608   input_location = saved_loc;
8609
8610   return r;
8611 }
8612
8613 /* Substitute into the ARG_TYPES of a function type.  */
8614
8615 static tree
8616 tsubst_arg_types (tree arg_types,
8617                   tree args,
8618                   tsubst_flags_t complain,
8619                   tree in_decl)
8620 {
8621   tree remaining_arg_types;
8622   tree type = NULL_TREE;
8623   int i = 1;
8624   tree expanded_args = NULL_TREE;
8625   tree default_arg;
8626
8627   if (!arg_types || arg_types == void_list_node)
8628     return arg_types;
8629
8630   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8631                                           args, complain, in_decl);
8632   if (remaining_arg_types == error_mark_node)
8633     return error_mark_node;
8634
8635   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8636     {
8637       /* For a pack expansion, perform substitution on the
8638          entire expression. Later on, we'll handle the arguments
8639          one-by-one.  */
8640       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8641                                             args, complain, in_decl);
8642
8643       if (TREE_CODE (expanded_args) == TREE_VEC)
8644         /* So that we'll spin through the parameters, one by one.  */
8645         i = TREE_VEC_LENGTH (expanded_args);
8646       else
8647         {
8648           /* We only partially substituted into the parameter
8649              pack. Our type is TYPE_PACK_EXPANSION.  */
8650           type = expanded_args;
8651           expanded_args = NULL_TREE;
8652         }
8653     }
8654
8655   while (i > 0) {
8656     --i;
8657     
8658     if (expanded_args)
8659       type = TREE_VEC_ELT (expanded_args, i);
8660     else if (!type)
8661       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8662
8663     if (type == error_mark_node)
8664       return error_mark_node;
8665     if (VOID_TYPE_P (type))
8666       {
8667         if (complain & tf_error)
8668           {
8669             error ("invalid parameter type %qT", type);
8670             if (in_decl)
8671               error ("in declaration %q+D", in_decl);
8672           }
8673         return error_mark_node;
8674     }
8675     
8676     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8677        top-level qualifiers as required.  */
8678     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8679
8680     /* We do not substitute into default arguments here.  The standard
8681        mandates that they be instantiated only when needed, which is
8682        done in build_over_call.  */
8683     default_arg = TREE_PURPOSE (arg_types);
8684
8685     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8686       {
8687         /* We've instantiated a template before its default arguments
8688            have been parsed.  This can happen for a nested template
8689            class, and is not an error unless we require the default
8690            argument in a call of this function.  */
8691         remaining_arg_types = 
8692           tree_cons (default_arg, type, remaining_arg_types);
8693         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8694                        remaining_arg_types);
8695       }
8696     else
8697       remaining_arg_types = 
8698         hash_tree_cons (default_arg, type, remaining_arg_types);
8699   }
8700         
8701   return remaining_arg_types;
8702 }
8703
8704 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8705    *not* handle the exception-specification for FNTYPE, because the
8706    initial substitution of explicitly provided template parameters
8707    during argument deduction forbids substitution into the
8708    exception-specification:
8709
8710      [temp.deduct]
8711
8712      All references in the function type of the function template to  the
8713      corresponding template parameters are replaced by the specified tem-
8714      plate argument values.  If a substitution in a template parameter or
8715      in  the function type of the function template results in an invalid
8716      type, type deduction fails.  [Note: The equivalent  substitution  in
8717      exception specifications is done only when the function is instanti-
8718      ated, at which point a program is  ill-formed  if  the  substitution
8719      results in an invalid type.]  */
8720
8721 static tree
8722 tsubst_function_type (tree t,
8723                       tree args,
8724                       tsubst_flags_t complain,
8725                       tree in_decl)
8726 {
8727   tree return_type;
8728   tree arg_types;
8729   tree fntype;
8730
8731   /* The TYPE_CONTEXT is not used for function/method types.  */
8732   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8733
8734   /* Substitute the return type.  */
8735   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8736   if (return_type == error_mark_node)
8737     return error_mark_node;
8738   /* The standard does not presently indicate that creation of a
8739      function type with an invalid return type is a deduction failure.
8740      However, that is clearly analogous to creating an array of "void"
8741      or a reference to a reference.  This is core issue #486.  */
8742   if (TREE_CODE (return_type) == ARRAY_TYPE
8743       || TREE_CODE (return_type) == FUNCTION_TYPE)
8744     {
8745       if (complain & tf_error)
8746         {
8747           if (TREE_CODE (return_type) == ARRAY_TYPE)
8748             error ("function returning an array");
8749           else
8750             error ("function returning a function");
8751         }
8752       return error_mark_node;
8753     }
8754
8755   /* Substitute the argument types.  */
8756   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8757                                 complain, in_decl);
8758   if (arg_types == error_mark_node)
8759     return error_mark_node;
8760
8761   if (TYPE_QUALS (return_type) != TYPE_UNQUALIFIED
8762       && in_decl != NULL_TREE
8763       && !TREE_NO_WARNING (in_decl)
8764       && (SCALAR_TYPE_P (return_type) || VOID_TYPE_P (return_type)))
8765     warning (OPT_Wignored_qualifiers,
8766             "type qualifiers ignored on function return type");
8767
8768   /* Construct a new type node and return it.  */
8769   if (TREE_CODE (t) == FUNCTION_TYPE)
8770     fntype = build_function_type (return_type, arg_types);
8771   else
8772     {
8773       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8774       if (! MAYBE_CLASS_TYPE_P (r))
8775         {
8776           /* [temp.deduct]
8777
8778              Type deduction may fail for any of the following
8779              reasons:
8780
8781              -- Attempting to create "pointer to member of T" when T
8782              is not a class type.  */
8783           if (complain & tf_error)
8784             error ("creating pointer to member function of non-class type %qT",
8785                       r);
8786           return error_mark_node;
8787         }
8788
8789       fntype = build_method_type_directly (r, return_type,
8790                                            TREE_CHAIN (arg_types));
8791     }
8792   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
8793   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
8794
8795   return fntype;
8796 }
8797
8798 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
8799    ARGS into that specification, and return the substituted
8800    specification.  If there is no specification, return NULL_TREE.  */
8801
8802 static tree
8803 tsubst_exception_specification (tree fntype,
8804                                 tree args,
8805                                 tsubst_flags_t complain,
8806                                 tree in_decl)
8807 {
8808   tree specs;
8809   tree new_specs;
8810
8811   specs = TYPE_RAISES_EXCEPTIONS (fntype);
8812   new_specs = NULL_TREE;
8813   if (specs)
8814     {
8815       if (! TREE_VALUE (specs))
8816         new_specs = specs;
8817       else
8818         while (specs)
8819           {
8820             tree spec;
8821             int i, len = 1;
8822             tree expanded_specs = NULL_TREE;
8823
8824             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
8825               {
8826                 /* Expand the pack expansion type.  */
8827                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
8828                                                        args, complain,
8829                                                        in_decl);
8830
8831                 if (expanded_specs == error_mark_node)
8832                   return error_mark_node;
8833                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
8834                   len = TREE_VEC_LENGTH (expanded_specs);
8835                 else
8836                   {
8837                     /* We're substituting into a member template, so
8838                        we got a TYPE_PACK_EXPANSION back.  Add that
8839                        expansion and move on.  */
8840                     gcc_assert (TREE_CODE (expanded_specs) 
8841                                 == TYPE_PACK_EXPANSION);
8842                     new_specs = add_exception_specifier (new_specs,
8843                                                          expanded_specs,
8844                                                          complain);
8845                     specs = TREE_CHAIN (specs);
8846                     continue;
8847                   }
8848               }
8849
8850             for (i = 0; i < len; ++i)
8851               {
8852                 if (expanded_specs)
8853                   spec = TREE_VEC_ELT (expanded_specs, i);
8854                 else
8855                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
8856                 if (spec == error_mark_node)
8857                   return spec;
8858                 new_specs = add_exception_specifier (new_specs, spec, 
8859                                                      complain);
8860               }
8861
8862             specs = TREE_CHAIN (specs);
8863           }
8864     }
8865   return new_specs;
8866 }
8867
8868 /* Take the tree structure T and replace template parameters used
8869    therein with the argument vector ARGS.  IN_DECL is an associated
8870    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
8871    Issue error and warning messages under control of COMPLAIN.  Note
8872    that we must be relatively non-tolerant of extensions here, in
8873    order to preserve conformance; if we allow substitutions that
8874    should not be allowed, we may allow argument deductions that should
8875    not succeed, and therefore report ambiguous overload situations
8876    where there are none.  In theory, we could allow the substitution,
8877    but indicate that it should have failed, and allow our caller to
8878    make sure that the right thing happens, but we don't try to do this
8879    yet.
8880
8881    This function is used for dealing with types, decls and the like;
8882    for expressions, use tsubst_expr or tsubst_copy.  */
8883
8884 static tree
8885 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8886 {
8887   tree type, r;
8888
8889   if (t == NULL_TREE || t == error_mark_node
8890       || t == integer_type_node
8891       || t == void_type_node
8892       || t == char_type_node
8893       || t == unknown_type_node
8894       || TREE_CODE (t) == NAMESPACE_DECL)
8895     return t;
8896
8897   if (DECL_P (t))
8898     return tsubst_decl (t, args, complain);
8899
8900   if (TREE_CODE (t) == IDENTIFIER_NODE)
8901     type = IDENTIFIER_TYPE_VALUE (t);
8902   else
8903     type = TREE_TYPE (t);
8904
8905   gcc_assert (type != unknown_type_node);
8906
8907   /* Reuse typedefs.  We need to do this to handle dependent attributes,
8908      such as attribute aligned.  */
8909   if (TYPE_P (t)
8910       && TYPE_NAME (t)
8911       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
8912     {
8913       tree decl = TYPE_NAME (t);
8914       
8915       if (DECL_CLASS_SCOPE_P (decl)
8916           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
8917           && uses_template_parms (DECL_CONTEXT (decl)))
8918         {
8919           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
8920           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
8921           r = retrieve_specialization (tmpl, gen_args, false);
8922         }
8923       else if (DECL_FUNCTION_SCOPE_P (decl)
8924                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
8925                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
8926         r = retrieve_local_specialization (decl);
8927       else
8928         /* The typedef is from a non-template context.  */
8929         return t;
8930
8931       if (r)
8932         {
8933           r = TREE_TYPE (r);
8934           r = cp_build_qualified_type_real
8935             (r, cp_type_quals (t) | cp_type_quals (r),
8936              complain | tf_ignore_bad_quals);
8937           return r;
8938         }
8939       /* Else we must be instantiating the typedef, so fall through.  */
8940     }
8941
8942   if (type
8943       && TREE_CODE (t) != TYPENAME_TYPE
8944       && TREE_CODE (t) != IDENTIFIER_NODE
8945       && TREE_CODE (t) != FUNCTION_TYPE
8946       && TREE_CODE (t) != METHOD_TYPE)
8947     type = tsubst (type, args, complain, in_decl);
8948   if (type == error_mark_node)
8949     return error_mark_node;
8950
8951   switch (TREE_CODE (t))
8952     {
8953     case RECORD_TYPE:
8954     case UNION_TYPE:
8955     case ENUMERAL_TYPE:
8956       return tsubst_aggr_type (t, args, complain, in_decl,
8957                                /*entering_scope=*/0);
8958
8959     case ERROR_MARK:
8960     case IDENTIFIER_NODE:
8961     case VOID_TYPE:
8962     case REAL_TYPE:
8963     case COMPLEX_TYPE:
8964     case VECTOR_TYPE:
8965     case BOOLEAN_TYPE:
8966     case INTEGER_CST:
8967     case REAL_CST:
8968     case STRING_CST:
8969       return t;
8970
8971     case INTEGER_TYPE:
8972       if (t == integer_type_node)
8973         return t;
8974
8975       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
8976           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
8977         return t;
8978
8979       {
8980         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
8981
8982         max = tsubst_expr (omax, args, complain, in_decl,
8983                            /*integral_constant_expression_p=*/false);
8984         max = fold_decl_constant_value (max);
8985
8986         if (TREE_CODE (max) != INTEGER_CST
8987             && !at_function_scope_p ()
8988             && !value_dependent_expression_p (max))
8989           {
8990             if (complain & tf_error)
8991               error ("array bound is not an integer constant");
8992             return error_mark_node;
8993           }
8994
8995         /* [temp.deduct]
8996
8997            Type deduction may fail for any of the following
8998            reasons:
8999
9000              Attempting to create an array with a size that is
9001              zero or negative.  */
9002         if (integer_zerop (max) && !(complain & tf_error))
9003           /* We must fail if performing argument deduction (as
9004              indicated by the state of complain), so that
9005              another substitution can be found.  */
9006           return error_mark_node;
9007         else if (TREE_CODE (max) == INTEGER_CST
9008                  && INT_CST_LT (max, integer_zero_node))
9009           {
9010             if (complain & tf_error)
9011               error ("creating array with negative size (%qE)", max);
9012
9013             return error_mark_node;
9014           }
9015
9016         return compute_array_index_type (NULL_TREE, max);
9017       }
9018
9019     case TEMPLATE_TYPE_PARM:
9020     case TEMPLATE_TEMPLATE_PARM:
9021     case BOUND_TEMPLATE_TEMPLATE_PARM:
9022     case TEMPLATE_PARM_INDEX:
9023       {
9024         int idx;
9025         int level;
9026         int levels;
9027         tree arg = NULL_TREE;
9028
9029         r = NULL_TREE;
9030
9031         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9032         template_parm_level_and_index (t, &level, &idx); 
9033
9034         levels = TMPL_ARGS_DEPTH (args);
9035         if (level <= levels)
9036           {
9037             arg = TMPL_ARG (args, level, idx);
9038
9039             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9040               /* See through ARGUMENT_PACK_SELECT arguments. */
9041               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9042           }
9043
9044         if (arg == error_mark_node)
9045           return error_mark_node;
9046         else if (arg != NULL_TREE)
9047           {
9048             if (ARGUMENT_PACK_P (arg))
9049               /* If ARG is an argument pack, we don't actually want to
9050                  perform a substitution here, because substitutions
9051                  for argument packs are only done
9052                  element-by-element. We can get to this point when
9053                  substituting the type of a non-type template
9054                  parameter pack, when that type actually contains
9055                  template parameter packs from an outer template, e.g.,
9056
9057                  template<typename... Types> struct A {
9058                    template<Types... Values> struct B { };
9059                  };  */
9060               return t;
9061
9062             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9063               {
9064                 int quals;
9065                 gcc_assert (TYPE_P (arg));
9066
9067                 /* cv-quals from the template are discarded when
9068                    substituting in a function or reference type.  */
9069                 if (TREE_CODE (arg) == FUNCTION_TYPE
9070                     || TREE_CODE (arg) == METHOD_TYPE
9071                     || TREE_CODE (arg) == REFERENCE_TYPE)
9072                   quals = cp_type_quals (arg);
9073                 else
9074                   quals = cp_type_quals (arg) | cp_type_quals (t);
9075                   
9076                 return cp_build_qualified_type_real
9077                   (arg, quals, complain | tf_ignore_bad_quals);
9078               }
9079             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9080               {
9081                 /* We are processing a type constructed from a
9082                    template template parameter.  */
9083                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9084                                       args, complain, in_decl);
9085                 if (argvec == error_mark_node)
9086                   return error_mark_node;
9087
9088                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9089                    are resolving nested-types in the signature of a
9090                    member function templates.  Otherwise ARG is a
9091                    TEMPLATE_DECL and is the real template to be
9092                    instantiated.  */
9093                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9094                   arg = TYPE_NAME (arg);
9095
9096                 r = lookup_template_class (arg,
9097                                            argvec, in_decl,
9098                                            DECL_CONTEXT (arg),
9099                                             /*entering_scope=*/0,
9100                                            complain);
9101                 return cp_build_qualified_type_real
9102                   (r, TYPE_QUALS (t), complain);
9103               }
9104             else
9105               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9106               return arg;
9107           }
9108
9109         if (level == 1)
9110           /* This can happen during the attempted tsubst'ing in
9111              unify.  This means that we don't yet have any information
9112              about the template parameter in question.  */
9113           return t;
9114
9115         /* If we get here, we must have been looking at a parm for a
9116            more deeply nested template.  Make a new version of this
9117            template parameter, but with a lower level.  */
9118         switch (TREE_CODE (t))
9119           {
9120           case TEMPLATE_TYPE_PARM:
9121           case TEMPLATE_TEMPLATE_PARM:
9122           case BOUND_TEMPLATE_TEMPLATE_PARM:
9123             if (cp_type_quals (t))
9124               {
9125                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9126                 r = cp_build_qualified_type_real
9127                   (r, cp_type_quals (t),
9128                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9129                                ? tf_ignore_bad_quals : 0));
9130               }
9131             else
9132               {
9133                 r = copy_type (t);
9134                 TEMPLATE_TYPE_PARM_INDEX (r)
9135                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9136                                                 r, levels, args, complain);
9137                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9138                 TYPE_MAIN_VARIANT (r) = r;
9139                 TYPE_POINTER_TO (r) = NULL_TREE;
9140                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9141
9142                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9143                   /* We have reduced the level of the template
9144                      template parameter, but not the levels of its
9145                      template parameters, so canonical_type_parameter
9146                      will not be able to find the canonical template
9147                      template parameter for this level. Thus, we
9148                      require structural equality checking to compare
9149                      TEMPLATE_TEMPLATE_PARMs. */
9150                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9151                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9152                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9153                 else
9154                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9155
9156                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9157                   {
9158                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9159                                           complain, in_decl);
9160                     if (argvec == error_mark_node)
9161                       return error_mark_node;
9162
9163                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9164                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9165                   }
9166               }
9167             break;
9168
9169           case TEMPLATE_PARM_INDEX:
9170             r = reduce_template_parm_level (t, type, levels, args, complain);
9171             break;
9172
9173           default:
9174             gcc_unreachable ();
9175           }
9176
9177         return r;
9178       }
9179
9180     case TREE_LIST:
9181       {
9182         tree purpose, value, chain;
9183
9184         if (t == void_list_node)
9185           return t;
9186
9187         purpose = TREE_PURPOSE (t);
9188         if (purpose)
9189           {
9190             purpose = tsubst (purpose, args, complain, in_decl);
9191             if (purpose == error_mark_node)
9192               return error_mark_node;
9193           }
9194         value = TREE_VALUE (t);
9195         if (value)
9196           {
9197             value = tsubst (value, args, complain, in_decl);
9198             if (value == error_mark_node)
9199               return error_mark_node;
9200           }
9201         chain = TREE_CHAIN (t);
9202         if (chain && chain != void_type_node)
9203           {
9204             chain = tsubst (chain, args, complain, in_decl);
9205             if (chain == error_mark_node)
9206               return error_mark_node;
9207           }
9208         if (purpose == TREE_PURPOSE (t)
9209             && value == TREE_VALUE (t)
9210             && chain == TREE_CHAIN (t))
9211           return t;
9212         return hash_tree_cons (purpose, value, chain);
9213       }
9214
9215     case TREE_BINFO:
9216       /* We should never be tsubsting a binfo.  */
9217       gcc_unreachable ();
9218
9219     case TREE_VEC:
9220       /* A vector of template arguments.  */
9221       gcc_assert (!type);
9222       return tsubst_template_args (t, args, complain, in_decl);
9223
9224     case POINTER_TYPE:
9225     case REFERENCE_TYPE:
9226       {
9227         enum tree_code code;
9228
9229         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9230           return t;
9231
9232         code = TREE_CODE (t);
9233
9234
9235         /* [temp.deduct]
9236
9237            Type deduction may fail for any of the following
9238            reasons:
9239
9240            -- Attempting to create a pointer to reference type.
9241            -- Attempting to create a reference to a reference type or
9242               a reference to void.
9243
9244           Core issue 106 says that creating a reference to a reference
9245           during instantiation is no longer a cause for failure. We
9246           only enforce this check in strict C++98 mode.  */
9247         if ((TREE_CODE (type) == REFERENCE_TYPE
9248              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9249             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9250           {
9251             static location_t last_loc;
9252
9253             /* We keep track of the last time we issued this error
9254                message to avoid spewing a ton of messages during a
9255                single bad template instantiation.  */
9256             if (complain & tf_error
9257                 && last_loc != input_location)
9258               {
9259                 if (TREE_CODE (type) == VOID_TYPE)
9260                   error ("forming reference to void");
9261                 else
9262                   error ("forming %s to reference type %qT",
9263                          (code == POINTER_TYPE) ? "pointer" : "reference",
9264                          type);
9265                 last_loc = input_location;
9266               }
9267
9268             return error_mark_node;
9269           }
9270         else if (code == POINTER_TYPE)
9271           {
9272             r = build_pointer_type (type);
9273             if (TREE_CODE (type) == METHOD_TYPE)
9274               r = build_ptrmemfunc_type (r);
9275           }
9276         else if (TREE_CODE (type) == REFERENCE_TYPE)
9277           /* In C++0x, during template argument substitution, when there is an
9278              attempt to create a reference to a reference type, reference
9279              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9280
9281              "If a template-argument for a template-parameter T names a type
9282              that is a reference to a type A, an attempt to create the type
9283              'lvalue reference to cv T' creates the type 'lvalue reference to
9284              A,' while an attempt to create the type type rvalue reference to
9285              cv T' creates the type T"
9286           */
9287           r = cp_build_reference_type
9288               (TREE_TYPE (type),
9289                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9290         else
9291           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9292         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9293
9294         if (r != error_mark_node)
9295           /* Will this ever be needed for TYPE_..._TO values?  */
9296           layout_type (r);
9297
9298         return r;
9299       }
9300     case OFFSET_TYPE:
9301       {
9302         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9303         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9304           {
9305             /* [temp.deduct]
9306
9307                Type deduction may fail for any of the following
9308                reasons:
9309
9310                -- Attempting to create "pointer to member of T" when T
9311                   is not a class type.  */
9312             if (complain & tf_error)
9313               error ("creating pointer to member of non-class type %qT", r);
9314             return error_mark_node;
9315           }
9316         if (TREE_CODE (type) == REFERENCE_TYPE)
9317           {
9318             if (complain & tf_error)
9319               error ("creating pointer to member reference type %qT", type);
9320             return error_mark_node;
9321           }
9322         if (TREE_CODE (type) == VOID_TYPE)
9323           {
9324             if (complain & tf_error)
9325               error ("creating pointer to member of type void");
9326             return error_mark_node;
9327           }
9328         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9329         if (TREE_CODE (type) == FUNCTION_TYPE)
9330           {
9331             /* The type of the implicit object parameter gets its
9332                cv-qualifiers from the FUNCTION_TYPE. */
9333             tree method_type;
9334             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9335                                                       cp_type_quals (type));
9336             tree memptr;
9337             method_type = build_method_type_directly (this_type,
9338                                                       TREE_TYPE (type),
9339                                                       TYPE_ARG_TYPES (type));
9340             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9341             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9342                                                  complain);
9343           }
9344         else
9345           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9346                                                TYPE_QUALS (t),
9347                                                complain);
9348       }
9349     case FUNCTION_TYPE:
9350     case METHOD_TYPE:
9351       {
9352         tree fntype;
9353         tree specs;
9354         fntype = tsubst_function_type (t, args, complain, in_decl);
9355         if (fntype == error_mark_node)
9356           return error_mark_node;
9357
9358         /* Substitute the exception specification.  */
9359         specs = tsubst_exception_specification (t, args, complain,
9360                                                 in_decl);
9361         if (specs == error_mark_node)
9362           return error_mark_node;
9363         if (specs)
9364           fntype = build_exception_variant (fntype, specs);
9365         return fntype;
9366       }
9367     case ARRAY_TYPE:
9368       {
9369         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9370         if (domain == error_mark_node)
9371           return error_mark_node;
9372
9373         /* As an optimization, we avoid regenerating the array type if
9374            it will obviously be the same as T.  */
9375         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9376           return t;
9377
9378         /* These checks should match the ones in grokdeclarator.
9379
9380            [temp.deduct]
9381
9382            The deduction may fail for any of the following reasons:
9383
9384            -- Attempting to create an array with an element type that
9385               is void, a function type, or a reference type, or [DR337]
9386               an abstract class type.  */
9387         if (TREE_CODE (type) == VOID_TYPE
9388             || TREE_CODE (type) == FUNCTION_TYPE
9389             || TREE_CODE (type) == REFERENCE_TYPE)
9390           {
9391             if (complain & tf_error)
9392               error ("creating array of %qT", type);
9393             return error_mark_node;
9394           }
9395         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9396           {
9397             if (complain & tf_error)
9398               error ("creating array of %qT, which is an abstract class type",
9399                      type);
9400             return error_mark_node;
9401           }
9402
9403         r = build_cplus_array_type (type, domain);
9404
9405         if (TYPE_USER_ALIGN (t))
9406           {
9407             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9408             TYPE_USER_ALIGN (r) = 1;
9409           }
9410
9411         return r;
9412       }
9413
9414     case PLUS_EXPR:
9415     case MINUS_EXPR:
9416       {
9417         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9418         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9419
9420         if (e1 == error_mark_node || e2 == error_mark_node)
9421           return error_mark_node;
9422
9423         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9424       }
9425
9426     case NEGATE_EXPR:
9427     case NOP_EXPR:
9428       {
9429         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9430         if (e == error_mark_node)
9431           return error_mark_node;
9432
9433         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9434       }
9435
9436     case TYPENAME_TYPE:
9437       {
9438         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9439                                      in_decl, /*entering_scope=*/1);
9440         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9441                               complain, in_decl);
9442
9443         if (ctx == error_mark_node || f == error_mark_node)
9444           return error_mark_node;
9445
9446         if (!MAYBE_CLASS_TYPE_P (ctx))
9447           {
9448             if (complain & tf_error)
9449               error ("%qT is not a class, struct, or union type", ctx);
9450             return error_mark_node;
9451           }
9452         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9453           {
9454             /* Normally, make_typename_type does not require that the CTX
9455                have complete type in order to allow things like:
9456
9457                  template <class T> struct S { typename S<T>::X Y; };
9458
9459                But, such constructs have already been resolved by this
9460                point, so here CTX really should have complete type, unless
9461                it's a partial instantiation.  */
9462             ctx = complete_type (ctx);
9463             if (!COMPLETE_TYPE_P (ctx))
9464               {
9465                 if (complain & tf_error)
9466                   cxx_incomplete_type_error (NULL_TREE, ctx);
9467                 return error_mark_node;
9468               }
9469           }
9470
9471         f = make_typename_type (ctx, f, typename_type,
9472                                 (complain & tf_error) | tf_keep_type_decl);
9473         if (f == error_mark_node)
9474           return f;
9475         if (TREE_CODE (f) == TYPE_DECL)
9476           {
9477             complain |= tf_ignore_bad_quals;
9478             f = TREE_TYPE (f);
9479           }
9480
9481         if (TREE_CODE (f) != TYPENAME_TYPE)
9482           {
9483             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9484               error ("%qT resolves to %qT, which is not an enumeration type",
9485                      t, f);
9486             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9487               error ("%qT resolves to %qT, which is is not a class type",
9488                      t, f);
9489           }
9490
9491         return cp_build_qualified_type_real
9492           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9493       }
9494
9495     case UNBOUND_CLASS_TEMPLATE:
9496       {
9497         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9498                                      in_decl, /*entering_scope=*/1);
9499         tree name = TYPE_IDENTIFIER (t);
9500         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9501
9502         if (ctx == error_mark_node || name == error_mark_node)
9503           return error_mark_node;
9504
9505         if (parm_list)
9506           parm_list = tsubst_template_parms (parm_list, args, complain);
9507         return make_unbound_class_template (ctx, name, parm_list, complain);
9508       }
9509
9510     case INDIRECT_REF:
9511     case ADDR_EXPR:
9512     case CALL_EXPR:
9513       gcc_unreachable ();
9514
9515     case ARRAY_REF:
9516       {
9517         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9518         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9519                                /*integral_constant_expression_p=*/false);
9520         if (e1 == error_mark_node || e2 == error_mark_node)
9521           return error_mark_node;
9522
9523         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9524       }
9525
9526     case SCOPE_REF:
9527       {
9528         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9529         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9530         if (e1 == error_mark_node || e2 == error_mark_node)
9531           return error_mark_node;
9532
9533         return build_qualified_name (/*type=*/NULL_TREE,
9534                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9535       }
9536
9537     case TYPEOF_TYPE:
9538       {
9539         tree type;
9540
9541         type = finish_typeof (tsubst_expr 
9542                               (TYPEOF_TYPE_EXPR (t), args,
9543                                complain, in_decl,
9544                                /*integral_constant_expression_p=*/false));
9545         return cp_build_qualified_type_real (type,
9546                                              cp_type_quals (t)
9547                                              | cp_type_quals (type),
9548                                              complain);
9549       }
9550
9551     case DECLTYPE_TYPE:
9552       {
9553         tree type;
9554
9555         type = 
9556           finish_decltype_type (tsubst_expr 
9557                                 (DECLTYPE_TYPE_EXPR (t), args,
9558                                  complain, in_decl,
9559                                  /*integral_constant_expression_p=*/false),
9560                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9561         return cp_build_qualified_type_real (type,
9562                                              cp_type_quals (t)
9563                                              | cp_type_quals (type),
9564                                              complain);
9565       }
9566
9567     case TYPE_ARGUMENT_PACK:
9568     case NONTYPE_ARGUMENT_PACK:
9569       {
9570         tree r = make_node (TREE_CODE (t));
9571         tree packed_out = 
9572           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9573                                 args,
9574                                 complain,
9575                                 in_decl);
9576         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9577
9578         /* For template nontype argument packs, also substitute into
9579            the type.  */
9580         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9581           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9582
9583         return r;
9584       }
9585       break;
9586
9587     default:
9588       sorry ("use of %qs in template",
9589              tree_code_name [(int) TREE_CODE (t)]);
9590       return error_mark_node;
9591     }
9592 }
9593
9594 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9595    type of the expression on the left-hand side of the "." or "->"
9596    operator.  */
9597
9598 static tree
9599 tsubst_baselink (tree baselink, tree object_type,
9600                  tree args, tsubst_flags_t complain, tree in_decl)
9601 {
9602     tree name;
9603     tree qualifying_scope;
9604     tree fns;
9605     tree optype;
9606     tree template_args = 0;
9607     bool template_id_p = false;
9608
9609     /* A baselink indicates a function from a base class.  Both the
9610        BASELINK_ACCESS_BINFO and the base class referenced may
9611        indicate bases of the template class, rather than the
9612        instantiated class.  In addition, lookups that were not
9613        ambiguous before may be ambiguous now.  Therefore, we perform
9614        the lookup again.  */
9615     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9616     qualifying_scope = tsubst (qualifying_scope, args,
9617                                complain, in_decl);
9618     fns = BASELINK_FUNCTIONS (baselink);
9619     optype = BASELINK_OPTYPE (baselink);
9620     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9621       {
9622         template_id_p = true;
9623         template_args = TREE_OPERAND (fns, 1);
9624         fns = TREE_OPERAND (fns, 0);
9625         if (template_args)
9626           template_args = tsubst_template_args (template_args, args,
9627                                                 complain, in_decl);
9628       }
9629     name = DECL_NAME (get_first_fn (fns));
9630     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9631
9632     /* If lookup found a single function, mark it as used at this
9633        point.  (If it lookup found multiple functions the one selected
9634        later by overload resolution will be marked as used at that
9635        point.)  */
9636     if (BASELINK_P (baselink))
9637       fns = BASELINK_FUNCTIONS (baselink);
9638     if (!template_id_p && !really_overloaded_fn (fns))
9639       mark_used (OVL_CURRENT (fns));
9640
9641     /* Add back the template arguments, if present.  */
9642     if (BASELINK_P (baselink) && template_id_p)
9643       BASELINK_FUNCTIONS (baselink)
9644         = build_nt (TEMPLATE_ID_EXPR,
9645                     BASELINK_FUNCTIONS (baselink),
9646                     template_args);
9647     /* Update the conversion operator type.  */
9648     BASELINK_OPTYPE (baselink) 
9649       = tsubst (optype, args, complain, in_decl);
9650
9651     if (!object_type)
9652       object_type = current_class_type;
9653     return adjust_result_of_qualified_name_lookup (baselink,
9654                                                    qualifying_scope,
9655                                                    object_type);
9656 }
9657
9658 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9659    true if the qualified-id will be a postfix-expression in-and-of
9660    itself; false if more of the postfix-expression follows the
9661    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9662    of "&".  */
9663
9664 static tree
9665 tsubst_qualified_id (tree qualified_id, tree args,
9666                      tsubst_flags_t complain, tree in_decl,
9667                      bool done, bool address_p)
9668 {
9669   tree expr;
9670   tree scope;
9671   tree name;
9672   bool is_template;
9673   tree template_args;
9674
9675   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9676
9677   /* Figure out what name to look up.  */
9678   name = TREE_OPERAND (qualified_id, 1);
9679   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9680     {
9681       is_template = true;
9682       template_args = TREE_OPERAND (name, 1);
9683       if (template_args)
9684         template_args = tsubst_template_args (template_args, args,
9685                                               complain, in_decl);
9686       name = TREE_OPERAND (name, 0);
9687     }
9688   else
9689     {
9690       is_template = false;
9691       template_args = NULL_TREE;
9692     }
9693
9694   /* Substitute into the qualifying scope.  When there are no ARGS, we
9695      are just trying to simplify a non-dependent expression.  In that
9696      case the qualifying scope may be dependent, and, in any case,
9697      substituting will not help.  */
9698   scope = TREE_OPERAND (qualified_id, 0);
9699   if (args)
9700     {
9701       scope = tsubst (scope, args, complain, in_decl);
9702       expr = tsubst_copy (name, args, complain, in_decl);
9703     }
9704   else
9705     expr = name;
9706
9707   if (dependent_type_p (scope))
9708     return build_qualified_name (/*type=*/NULL_TREE,
9709                                  scope, expr,
9710                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9711
9712   if (!BASELINK_P (name) && !DECL_P (expr))
9713     {
9714       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9715         /* If this were actually a destructor call, it would have been
9716            parsed as such by the parser.  */
9717         expr = error_mark_node;
9718       else
9719         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9720       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9721                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9722         {
9723           if (complain & tf_error)
9724             {
9725               error ("dependent-name %qE is parsed as a non-type, but "
9726                      "instantiation yields a type", qualified_id);
9727               inform ("say %<typename %E%> if a type is meant", qualified_id);
9728             }
9729           return error_mark_node;
9730         }
9731     }
9732
9733   if (DECL_P (expr))
9734     {
9735       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9736                                            scope);
9737       /* Remember that there was a reference to this entity.  */
9738       mark_used (expr);
9739     }
9740
9741   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9742     {
9743       if (complain & tf_error)
9744         qualified_name_lookup_error (scope,
9745                                      TREE_OPERAND (qualified_id, 1),
9746                                      expr);
9747       return error_mark_node;
9748     }
9749
9750   if (is_template)
9751     expr = lookup_template_function (expr, template_args);
9752
9753   if (expr == error_mark_node && complain & tf_error)
9754     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
9755                                  expr);
9756   else if (TYPE_P (scope))
9757     {
9758       expr = (adjust_result_of_qualified_name_lookup
9759               (expr, scope, current_class_type));
9760       expr = (finish_qualified_id_expr
9761               (scope, expr, done, address_p,
9762                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
9763                /*template_arg_p=*/false));
9764     }
9765
9766   /* Expressions do not generally have reference type.  */
9767   if (TREE_CODE (expr) != SCOPE_REF
9768       /* However, if we're about to form a pointer-to-member, we just
9769          want the referenced member referenced.  */
9770       && TREE_CODE (expr) != OFFSET_REF)
9771     expr = convert_from_reference (expr);
9772
9773   return expr;
9774 }
9775
9776 /* Like tsubst, but deals with expressions.  This function just replaces
9777    template parms; to finish processing the resultant expression, use
9778    tsubst_expr.  */
9779
9780 static tree
9781 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9782 {
9783   enum tree_code code;
9784   tree r;
9785
9786   if (t == NULL_TREE || t == error_mark_node)
9787     return t;
9788
9789   code = TREE_CODE (t);
9790
9791   switch (code)
9792     {
9793     case PARM_DECL:
9794       r = retrieve_local_specialization (t);
9795       gcc_assert (r != NULL);
9796       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
9797         r = ARGUMENT_PACK_SELECT_ARG (r);
9798       mark_used (r);
9799       return r;
9800
9801     case CONST_DECL:
9802       {
9803         tree enum_type;
9804         tree v;
9805
9806         if (DECL_TEMPLATE_PARM_P (t))
9807           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
9808         /* There is no need to substitute into namespace-scope
9809            enumerators.  */
9810         if (DECL_NAMESPACE_SCOPE_P (t))
9811           return t;
9812         /* If ARGS is NULL, then T is known to be non-dependent.  */
9813         if (args == NULL_TREE)
9814           return integral_constant_value (t);
9815
9816         /* Unfortunately, we cannot just call lookup_name here.
9817            Consider:
9818
9819              template <int I> int f() {
9820              enum E { a = I };
9821              struct S { void g() { E e = a; } };
9822              };
9823
9824            When we instantiate f<7>::S::g(), say, lookup_name is not
9825            clever enough to find f<7>::a.  */
9826         enum_type
9827           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
9828                               /*entering_scope=*/0);
9829
9830         for (v = TYPE_VALUES (enum_type);
9831              v != NULL_TREE;
9832              v = TREE_CHAIN (v))
9833           if (TREE_PURPOSE (v) == DECL_NAME (t))
9834             return TREE_VALUE (v);
9835
9836           /* We didn't find the name.  That should never happen; if
9837              name-lookup found it during preliminary parsing, we
9838              should find it again here during instantiation.  */
9839         gcc_unreachable ();
9840       }
9841       return t;
9842
9843     case FIELD_DECL:
9844       if (DECL_CONTEXT (t))
9845         {
9846           tree ctx;
9847
9848           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
9849                                   /*entering_scope=*/1);
9850           if (ctx != DECL_CONTEXT (t))
9851             {
9852               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
9853               if (!r)
9854                 {
9855                   if (complain & tf_error)
9856                     error ("using invalid field %qD", t);
9857                   return error_mark_node;
9858                 }
9859               return r;
9860             }
9861         }
9862
9863       return t;
9864
9865     case VAR_DECL:
9866     case FUNCTION_DECL:
9867       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9868           || local_variable_p (t))
9869         t = tsubst (t, args, complain, in_decl);
9870       mark_used (t);
9871       return t;
9872
9873     case BASELINK:
9874       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
9875
9876     case TEMPLATE_DECL:
9877       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9878         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
9879                        args, complain, in_decl);
9880       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
9881         return tsubst (t, args, complain, in_decl);
9882       else if (DECL_CLASS_SCOPE_P (t)
9883                && uses_template_parms (DECL_CONTEXT (t)))
9884         {
9885           /* Template template argument like the following example need
9886              special treatment:
9887
9888                template <template <class> class TT> struct C {};
9889                template <class T> struct D {
9890                  template <class U> struct E {};
9891                  C<E> c;                                // #1
9892                };
9893                D<int> d;                                // #2
9894
9895              We are processing the template argument `E' in #1 for
9896              the template instantiation #2.  Originally, `E' is a
9897              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
9898              have to substitute this with one having context `D<int>'.  */
9899
9900           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
9901           return lookup_field (context, DECL_NAME(t), 0, false);
9902         }
9903       else
9904         /* Ordinary template template argument.  */
9905         return t;
9906
9907     case CAST_EXPR:
9908     case REINTERPRET_CAST_EXPR:
9909     case CONST_CAST_EXPR:
9910     case STATIC_CAST_EXPR:
9911     case DYNAMIC_CAST_EXPR:
9912     case NOP_EXPR:
9913       return build1
9914         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9915          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9916
9917     case SIZEOF_EXPR:
9918       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
9919         {
9920           /* We only want to compute the number of arguments.  */
9921           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
9922                                                 complain, in_decl);
9923           int len = 0;
9924
9925           if (TREE_CODE (expanded) == TREE_VEC)
9926             len = TREE_VEC_LENGTH (expanded);
9927
9928           if (expanded == error_mark_node)
9929             return error_mark_node;
9930           else if (PACK_EXPANSION_P (expanded)
9931                    || (TREE_CODE (expanded) == TREE_VEC
9932                        && len > 0
9933                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
9934             {
9935               if (TREE_CODE (expanded) == TREE_VEC)
9936                 expanded = TREE_VEC_ELT (expanded, len - 1);
9937
9938               if (TYPE_P (expanded))
9939                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
9940                                                    complain & tf_error);
9941               else
9942                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
9943                                                    complain & tf_error);
9944             }
9945           else
9946             return build_int_cst (size_type_node, len);
9947         }
9948       /* Fall through */
9949
9950     case INDIRECT_REF:
9951     case NEGATE_EXPR:
9952     case TRUTH_NOT_EXPR:
9953     case BIT_NOT_EXPR:
9954     case ADDR_EXPR:
9955     case UNARY_PLUS_EXPR:      /* Unary + */
9956     case ALIGNOF_EXPR:
9957     case ARROW_EXPR:
9958     case THROW_EXPR:
9959     case TYPEID_EXPR:
9960     case REALPART_EXPR:
9961     case IMAGPART_EXPR:
9962       return build1
9963         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9964          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9965
9966     case COMPONENT_REF:
9967       {
9968         tree object;
9969         tree name;
9970
9971         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
9972         name = TREE_OPERAND (t, 1);
9973         if (TREE_CODE (name) == BIT_NOT_EXPR)
9974           {
9975             name = tsubst_copy (TREE_OPERAND (name, 0), args,
9976                                 complain, in_decl);
9977             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
9978           }
9979         else if (TREE_CODE (name) == SCOPE_REF
9980                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
9981           {
9982             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
9983                                      complain, in_decl);
9984             name = TREE_OPERAND (name, 1);
9985             name = tsubst_copy (TREE_OPERAND (name, 0), args,
9986                                 complain, in_decl);
9987             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
9988             name = build_qualified_name (/*type=*/NULL_TREE,
9989                                          base, name,
9990                                          /*template_p=*/false);
9991           }
9992         else if (TREE_CODE (name) == BASELINK)
9993           name = tsubst_baselink (name,
9994                                   non_reference (TREE_TYPE (object)),
9995                                   args, complain,
9996                                   in_decl);
9997         else
9998           name = tsubst_copy (name, args, complain, in_decl);
9999         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10000       }
10001
10002     case PLUS_EXPR:
10003     case MINUS_EXPR:
10004     case MULT_EXPR:
10005     case TRUNC_DIV_EXPR:
10006     case CEIL_DIV_EXPR:
10007     case FLOOR_DIV_EXPR:
10008     case ROUND_DIV_EXPR:
10009     case EXACT_DIV_EXPR:
10010     case BIT_AND_EXPR:
10011     case BIT_IOR_EXPR:
10012     case BIT_XOR_EXPR:
10013     case TRUNC_MOD_EXPR:
10014     case FLOOR_MOD_EXPR:
10015     case TRUTH_ANDIF_EXPR:
10016     case TRUTH_ORIF_EXPR:
10017     case TRUTH_AND_EXPR:
10018     case TRUTH_OR_EXPR:
10019     case RSHIFT_EXPR:
10020     case LSHIFT_EXPR:
10021     case RROTATE_EXPR:
10022     case LROTATE_EXPR:
10023     case EQ_EXPR:
10024     case NE_EXPR:
10025     case MAX_EXPR:
10026     case MIN_EXPR:
10027     case LE_EXPR:
10028     case GE_EXPR:
10029     case LT_EXPR:
10030     case GT_EXPR:
10031     case COMPOUND_EXPR:
10032     case DOTSTAR_EXPR:
10033     case MEMBER_REF:
10034     case PREDECREMENT_EXPR:
10035     case PREINCREMENT_EXPR:
10036     case POSTDECREMENT_EXPR:
10037     case POSTINCREMENT_EXPR:
10038       return build_nt
10039         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10040          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10041
10042     case SCOPE_REF:
10043       return build_qualified_name (/*type=*/NULL_TREE,
10044                                    tsubst_copy (TREE_OPERAND (t, 0),
10045                                                 args, complain, in_decl),
10046                                    tsubst_copy (TREE_OPERAND (t, 1),
10047                                                 args, complain, in_decl),
10048                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10049
10050     case ARRAY_REF:
10051       return build_nt
10052         (ARRAY_REF,
10053          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10054          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10055          NULL_TREE, NULL_TREE);
10056
10057     case CALL_EXPR:
10058       {
10059         int n = VL_EXP_OPERAND_LENGTH (t);
10060         tree result = build_vl_exp (CALL_EXPR, n);
10061         int i;
10062         for (i = 0; i < n; i++)
10063           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10064                                              complain, in_decl);
10065         return result;
10066       }
10067
10068     case COND_EXPR:
10069     case MODOP_EXPR:
10070     case PSEUDO_DTOR_EXPR:
10071       {
10072         r = build_nt
10073           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10074            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10075            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10076         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10077         return r;
10078       }
10079
10080     case NEW_EXPR:
10081       {
10082         r = build_nt
10083         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10084          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10085          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10086         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10087         return r;
10088       }
10089
10090     case DELETE_EXPR:
10091       {
10092         r = build_nt
10093         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10094          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10095         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10096         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10097         return r;
10098       }
10099
10100     case TEMPLATE_ID_EXPR:
10101       {
10102         /* Substituted template arguments */
10103         tree fn = TREE_OPERAND (t, 0);
10104         tree targs = TREE_OPERAND (t, 1);
10105
10106         fn = tsubst_copy (fn, args, complain, in_decl);
10107         if (targs)
10108           targs = tsubst_template_args (targs, args, complain, in_decl);
10109
10110         return lookup_template_function (fn, targs);
10111       }
10112
10113     case TREE_LIST:
10114       {
10115         tree purpose, value, chain;
10116
10117         if (t == void_list_node)
10118           return t;
10119
10120         purpose = TREE_PURPOSE (t);
10121         if (purpose)
10122           purpose = tsubst_copy (purpose, args, complain, in_decl);
10123         value = TREE_VALUE (t);
10124         if (value)
10125           value = tsubst_copy (value, args, complain, in_decl);
10126         chain = TREE_CHAIN (t);
10127         if (chain && chain != void_type_node)
10128           chain = tsubst_copy (chain, args, complain, in_decl);
10129         if (purpose == TREE_PURPOSE (t)
10130             && value == TREE_VALUE (t)
10131             && chain == TREE_CHAIN (t))
10132           return t;
10133         return tree_cons (purpose, value, chain);
10134       }
10135
10136     case RECORD_TYPE:
10137     case UNION_TYPE:
10138     case ENUMERAL_TYPE:
10139     case INTEGER_TYPE:
10140     case TEMPLATE_TYPE_PARM:
10141     case TEMPLATE_TEMPLATE_PARM:
10142     case BOUND_TEMPLATE_TEMPLATE_PARM:
10143     case TEMPLATE_PARM_INDEX:
10144     case POINTER_TYPE:
10145     case REFERENCE_TYPE:
10146     case OFFSET_TYPE:
10147     case FUNCTION_TYPE:
10148     case METHOD_TYPE:
10149     case ARRAY_TYPE:
10150     case TYPENAME_TYPE:
10151     case UNBOUND_CLASS_TEMPLATE:
10152     case TYPEOF_TYPE:
10153     case DECLTYPE_TYPE:
10154     case TYPE_DECL:
10155       return tsubst (t, args, complain, in_decl);
10156
10157     case IDENTIFIER_NODE:
10158       if (IDENTIFIER_TYPENAME_P (t))
10159         {
10160           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10161           return mangle_conv_op_name_for_type (new_type);
10162         }
10163       else
10164         return t;
10165
10166     case CONSTRUCTOR:
10167       /* This is handled by tsubst_copy_and_build.  */
10168       gcc_unreachable ();
10169
10170     case VA_ARG_EXPR:
10171       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10172                                           in_decl),
10173                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10174
10175     case CLEANUP_POINT_EXPR:
10176       /* We shouldn't have built any of these during initial template
10177          generation.  Instead, they should be built during instantiation
10178          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10179       gcc_unreachable ();
10180
10181     case OFFSET_REF:
10182       mark_used (TREE_OPERAND (t, 1));
10183       return t;
10184
10185     case EXPR_PACK_EXPANSION:
10186       error ("invalid use of pack expansion expression");
10187       return error_mark_node;
10188
10189     case NONTYPE_ARGUMENT_PACK:
10190       error ("use %<...%> to expand argument pack");
10191       return error_mark_node;
10192
10193     default:
10194       return t;
10195     }
10196 }
10197
10198 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10199
10200 static tree
10201 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10202                     tree in_decl)
10203 {
10204   tree new_clauses = NULL, nc, oc;
10205
10206   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10207     {
10208       nc = copy_node (oc);
10209       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10210       new_clauses = nc;
10211
10212       switch (OMP_CLAUSE_CODE (nc))
10213         {
10214         case OMP_CLAUSE_PRIVATE:
10215         case OMP_CLAUSE_SHARED:
10216         case OMP_CLAUSE_FIRSTPRIVATE:
10217         case OMP_CLAUSE_LASTPRIVATE:
10218         case OMP_CLAUSE_REDUCTION:
10219         case OMP_CLAUSE_COPYIN:
10220         case OMP_CLAUSE_COPYPRIVATE:
10221         case OMP_CLAUSE_IF:
10222         case OMP_CLAUSE_NUM_THREADS:
10223         case OMP_CLAUSE_SCHEDULE:
10224           OMP_CLAUSE_OPERAND (nc, 0)
10225             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10226                            in_decl, /*integral_constant_expression_p=*/false);
10227           break;
10228         case OMP_CLAUSE_NOWAIT:
10229         case OMP_CLAUSE_ORDERED:
10230         case OMP_CLAUSE_DEFAULT:
10231           break;
10232         default:
10233           gcc_unreachable ();
10234         }
10235     }
10236
10237   return finish_omp_clauses (nreverse (new_clauses));
10238 }
10239
10240 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10241
10242 static tree
10243 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10244                           tree in_decl)
10245 {
10246 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10247
10248   tree purpose, value, chain;
10249
10250   if (t == NULL)
10251     return t;
10252
10253   if (TREE_CODE (t) != TREE_LIST)
10254     return tsubst_copy_and_build (t, args, complain, in_decl,
10255                                   /*function_p=*/false,
10256                                   /*integral_constant_expression_p=*/false);
10257
10258   if (t == void_list_node)
10259     return t;
10260
10261   purpose = TREE_PURPOSE (t);
10262   if (purpose)
10263     purpose = RECUR (purpose);
10264   value = TREE_VALUE (t);
10265   if (value)
10266     value = RECUR (value);
10267   chain = TREE_CHAIN (t);
10268   if (chain && chain != void_type_node)
10269     chain = RECUR (chain);
10270   return tree_cons (purpose, value, chain);
10271 #undef RECUR
10272 }
10273
10274 /* Like tsubst_copy for expressions, etc. but also does semantic
10275    processing.  */
10276
10277 static tree
10278 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10279              bool integral_constant_expression_p)
10280 {
10281 #define RECUR(NODE)                             \
10282   tsubst_expr ((NODE), args, complain, in_decl, \
10283                integral_constant_expression_p)
10284
10285   tree stmt, tmp;
10286
10287   if (t == NULL_TREE || t == error_mark_node)
10288     return t;
10289
10290   if (EXPR_HAS_LOCATION (t))
10291     input_location = EXPR_LOCATION (t);
10292   if (STATEMENT_CODE_P (TREE_CODE (t)))
10293     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10294
10295   switch (TREE_CODE (t))
10296     {
10297     case STATEMENT_LIST:
10298       {
10299         tree_stmt_iterator i;
10300         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10301           RECUR (tsi_stmt (i));
10302         break;
10303       }
10304
10305     case CTOR_INITIALIZER:
10306       finish_mem_initializers (tsubst_initializer_list
10307                                (TREE_OPERAND (t, 0), args));
10308       break;
10309
10310     case RETURN_EXPR:
10311       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10312       break;
10313
10314     case EXPR_STMT:
10315       tmp = RECUR (EXPR_STMT_EXPR (t));
10316       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10317         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10318       else
10319         finish_expr_stmt (tmp);
10320       break;
10321
10322     case USING_STMT:
10323       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10324       break;
10325
10326     case DECL_EXPR:
10327       {
10328         tree decl;
10329         tree init;
10330
10331         decl = DECL_EXPR_DECL (t);
10332         if (TREE_CODE (decl) == LABEL_DECL)
10333           finish_label_decl (DECL_NAME (decl));
10334         else if (TREE_CODE (decl) == USING_DECL)
10335           {
10336             tree scope = USING_DECL_SCOPE (decl);
10337             tree name = DECL_NAME (decl);
10338             tree decl;
10339
10340             scope = RECUR (scope);
10341             decl = lookup_qualified_name (scope, name,
10342                                           /*is_type_p=*/false,
10343                                           /*complain=*/false);
10344             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10345               qualified_name_lookup_error (scope, name, decl);
10346             else
10347               do_local_using_decl (decl, scope, name);
10348           }
10349         else
10350           {
10351             init = DECL_INITIAL (decl);
10352             decl = tsubst (decl, args, complain, in_decl);
10353             if (decl != error_mark_node)
10354               {
10355                 /* By marking the declaration as instantiated, we avoid
10356                    trying to instantiate it.  Since instantiate_decl can't
10357                    handle local variables, and since we've already done
10358                    all that needs to be done, that's the right thing to
10359                    do.  */
10360                 if (TREE_CODE (decl) == VAR_DECL)
10361                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10362                 if (TREE_CODE (decl) == VAR_DECL
10363                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10364                   /* Anonymous aggregates are a special case.  */
10365                   finish_anon_union (decl);
10366                 else
10367                   {
10368                     maybe_push_decl (decl);
10369                     if (TREE_CODE (decl) == VAR_DECL
10370                         && DECL_PRETTY_FUNCTION_P (decl))
10371                       {
10372                         /* For __PRETTY_FUNCTION__ we have to adjust the
10373                            initializer.  */
10374                         const char *const name
10375                           = cxx_printable_name (current_function_decl, 2);
10376                         init = cp_fname_init (name, &TREE_TYPE (decl));
10377                       }
10378                     else
10379                       {
10380                         tree t = RECUR (init);
10381
10382                         if (init && !t)
10383                           /* If we had an initializer but it
10384                              instantiated to nothing,
10385                              value-initialize the object.  This will
10386                              only occur when the initializer was a
10387                              pack expansion where the parameter packs
10388                              used in that expansion were of length
10389                              zero.  */
10390                           init = build_default_init (TREE_TYPE (decl),
10391                                                      NULL_TREE);
10392                         else
10393                           init = t;
10394                       }
10395
10396                     finish_decl (decl, init, NULL_TREE);
10397                   }
10398               }
10399           }
10400
10401         /* A DECL_EXPR can also be used as an expression, in the condition
10402            clause of an if/for/while construct.  */
10403         return decl;
10404       }
10405
10406     case FOR_STMT:
10407       stmt = begin_for_stmt ();
10408                           RECUR (FOR_INIT_STMT (t));
10409       finish_for_init_stmt (stmt);
10410       tmp = RECUR (FOR_COND (t));
10411       finish_for_cond (tmp, stmt);
10412       tmp = RECUR (FOR_EXPR (t));
10413       finish_for_expr (tmp, stmt);
10414       RECUR (FOR_BODY (t));
10415       finish_for_stmt (stmt);
10416       break;
10417
10418     case WHILE_STMT:
10419       stmt = begin_while_stmt ();
10420       tmp = RECUR (WHILE_COND (t));
10421       finish_while_stmt_cond (tmp, stmt);
10422       RECUR (WHILE_BODY (t));
10423       finish_while_stmt (stmt);
10424       break;
10425
10426     case DO_STMT:
10427       stmt = begin_do_stmt ();
10428       RECUR (DO_BODY (t));
10429       finish_do_body (stmt);
10430       tmp = RECUR (DO_COND (t));
10431       finish_do_stmt (tmp, stmt);
10432       break;
10433
10434     case IF_STMT:
10435       stmt = begin_if_stmt ();
10436       tmp = RECUR (IF_COND (t));
10437       finish_if_stmt_cond (tmp, stmt);
10438       RECUR (THEN_CLAUSE (t));
10439       finish_then_clause (stmt);
10440
10441       if (ELSE_CLAUSE (t))
10442         {
10443           begin_else_clause (stmt);
10444           RECUR (ELSE_CLAUSE (t));
10445           finish_else_clause (stmt);
10446         }
10447
10448       finish_if_stmt (stmt);
10449       break;
10450
10451     case BIND_EXPR:
10452       if (BIND_EXPR_BODY_BLOCK (t))
10453         stmt = begin_function_body ();
10454       else
10455         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10456                                     ? BCS_TRY_BLOCK : 0);
10457
10458       RECUR (BIND_EXPR_BODY (t));
10459
10460       if (BIND_EXPR_BODY_BLOCK (t))
10461         finish_function_body (stmt);
10462       else
10463         finish_compound_stmt (stmt);
10464       break;
10465
10466     case BREAK_STMT:
10467       finish_break_stmt ();
10468       break;
10469
10470     case CONTINUE_STMT:
10471       finish_continue_stmt ();
10472       break;
10473
10474     case SWITCH_STMT:
10475       stmt = begin_switch_stmt ();
10476       tmp = RECUR (SWITCH_STMT_COND (t));
10477       finish_switch_cond (tmp, stmt);
10478       RECUR (SWITCH_STMT_BODY (t));
10479       finish_switch_stmt (stmt);
10480       break;
10481
10482     case CASE_LABEL_EXPR:
10483       finish_case_label (RECUR (CASE_LOW (t)),
10484                          RECUR (CASE_HIGH (t)));
10485       break;
10486
10487     case LABEL_EXPR:
10488       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10489       break;
10490
10491     case GOTO_EXPR:
10492       tmp = GOTO_DESTINATION (t);
10493       if (TREE_CODE (tmp) != LABEL_DECL)
10494         /* Computed goto's must be tsubst'd into.  On the other hand,
10495            non-computed gotos must not be; the identifier in question
10496            will have no binding.  */
10497         tmp = RECUR (tmp);
10498       else
10499         tmp = DECL_NAME (tmp);
10500       finish_goto_stmt (tmp);
10501       break;
10502
10503     case ASM_EXPR:
10504       tmp = finish_asm_stmt
10505         (ASM_VOLATILE_P (t),
10506          RECUR (ASM_STRING (t)),
10507          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10508          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10509          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10510       {
10511         tree asm_expr = tmp;
10512         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10513           asm_expr = TREE_OPERAND (asm_expr, 0);
10514         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10515       }
10516       break;
10517
10518     case TRY_BLOCK:
10519       if (CLEANUP_P (t))
10520         {
10521           stmt = begin_try_block ();
10522           RECUR (TRY_STMTS (t));
10523           finish_cleanup_try_block (stmt);
10524           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10525         }
10526       else
10527         {
10528           tree compound_stmt = NULL_TREE;
10529
10530           if (FN_TRY_BLOCK_P (t))
10531             stmt = begin_function_try_block (&compound_stmt);
10532           else
10533             stmt = begin_try_block ();
10534
10535           RECUR (TRY_STMTS (t));
10536
10537           if (FN_TRY_BLOCK_P (t))
10538             finish_function_try_block (stmt);
10539           else
10540             finish_try_block (stmt);
10541
10542           RECUR (TRY_HANDLERS (t));
10543           if (FN_TRY_BLOCK_P (t))
10544             finish_function_handler_sequence (stmt, compound_stmt);
10545           else
10546             finish_handler_sequence (stmt);
10547         }
10548       break;
10549
10550     case HANDLER:
10551       {
10552         tree decl = HANDLER_PARMS (t);
10553
10554         if (decl)
10555           {
10556             decl = tsubst (decl, args, complain, in_decl);
10557             /* Prevent instantiate_decl from trying to instantiate
10558                this variable.  We've already done all that needs to be
10559                done.  */
10560             if (decl != error_mark_node)
10561               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10562           }
10563         stmt = begin_handler ();
10564         finish_handler_parms (decl, stmt);
10565         RECUR (HANDLER_BODY (t));
10566         finish_handler (stmt);
10567       }
10568       break;
10569
10570     case TAG_DEFN:
10571       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10572       break;
10573
10574     case STATIC_ASSERT:
10575       {
10576         tree condition = 
10577           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10578                        args,
10579                        complain, in_decl,
10580                        /*integral_constant_expression_p=*/true);
10581         finish_static_assert (condition,
10582                               STATIC_ASSERT_MESSAGE (t),
10583                               STATIC_ASSERT_SOURCE_LOCATION (t),
10584                               /*member_p=*/false);
10585       }
10586       break;
10587
10588     case OMP_PARALLEL:
10589       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
10590                                 args, complain, in_decl);
10591       stmt = begin_omp_parallel ();
10592       RECUR (OMP_PARALLEL_BODY (t));
10593       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
10594         = OMP_PARALLEL_COMBINED (t);
10595       break;
10596
10597     case OMP_FOR:
10598       {
10599         tree clauses, decl, init, cond, incr, body, pre_body;
10600
10601         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
10602                                       args, complain, in_decl);
10603         init = OMP_FOR_INIT (t);
10604         gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10605         decl = RECUR (TREE_OPERAND (init, 0));
10606         init = RECUR (TREE_OPERAND (init, 1));
10607         cond = RECUR (OMP_FOR_COND (t));
10608         incr = RECUR (OMP_FOR_INCR (t));
10609
10610         stmt = begin_omp_structured_block ();
10611
10612         pre_body = push_stmt_list ();
10613         RECUR (OMP_FOR_PRE_BODY (t));
10614         pre_body = pop_stmt_list (pre_body);
10615
10616         body = push_stmt_list ();
10617         RECUR (OMP_FOR_BODY (t));
10618         body = pop_stmt_list (body);
10619
10620         t = finish_omp_for (EXPR_LOCATION (t), decl, init, cond, incr, body,
10621                             pre_body);
10622         if (t)
10623           OMP_FOR_CLAUSES (t) = clauses;
10624
10625         add_stmt (finish_omp_structured_block (stmt));
10626       }
10627       break;
10628
10629     case OMP_SECTIONS:
10630     case OMP_SINGLE:
10631       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
10632       stmt = push_stmt_list ();
10633       RECUR (OMP_BODY (t));
10634       stmt = pop_stmt_list (stmt);
10635
10636       t = copy_node (t);
10637       OMP_BODY (t) = stmt;
10638       OMP_CLAUSES (t) = tmp;
10639       add_stmt (t);
10640       break;
10641
10642     case OMP_SECTION:
10643     case OMP_CRITICAL:
10644     case OMP_MASTER:
10645     case OMP_ORDERED:
10646       stmt = push_stmt_list ();
10647       RECUR (OMP_BODY (t));
10648       stmt = pop_stmt_list (stmt);
10649
10650       t = copy_node (t);
10651       OMP_BODY (t) = stmt;
10652       add_stmt (t);
10653       break;
10654
10655     case OMP_ATOMIC:
10656       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
10657       {
10658         tree op1 = TREE_OPERAND (t, 1);
10659         tree lhs = RECUR (TREE_OPERAND (op1, 0));
10660         tree rhs = RECUR (TREE_OPERAND (op1, 1));
10661         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
10662       }
10663       break;
10664
10665     case EXPR_PACK_EXPANSION:
10666       error ("invalid use of pack expansion expression");
10667       return error_mark_node;
10668
10669     case NONTYPE_ARGUMENT_PACK:
10670       error ("use %<...%> to expand argument pack");
10671       return error_mark_node;
10672
10673     default:
10674       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
10675
10676       return tsubst_copy_and_build (t, args, complain, in_decl,
10677                                     /*function_p=*/false,
10678                                     integral_constant_expression_p);
10679     }
10680
10681   return NULL_TREE;
10682 #undef RECUR
10683 }
10684
10685 /* T is a postfix-expression that is not being used in a function
10686    call.  Return the substituted version of T.  */
10687
10688 static tree
10689 tsubst_non_call_postfix_expression (tree t, tree args,
10690                                     tsubst_flags_t complain,
10691                                     tree in_decl)
10692 {
10693   if (TREE_CODE (t) == SCOPE_REF)
10694     t = tsubst_qualified_id (t, args, complain, in_decl,
10695                              /*done=*/false, /*address_p=*/false);
10696   else
10697     t = tsubst_copy_and_build (t, args, complain, in_decl,
10698                                /*function_p=*/false,
10699                                /*integral_constant_expression_p=*/false);
10700
10701   return t;
10702 }
10703
10704 /* Like tsubst but deals with expressions and performs semantic
10705    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
10706
10707 tree
10708 tsubst_copy_and_build (tree t,
10709                        tree args,
10710                        tsubst_flags_t complain,
10711                        tree in_decl,
10712                        bool function_p,
10713                        bool integral_constant_expression_p)
10714 {
10715 #define RECUR(NODE)                                             \
10716   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
10717                          /*function_p=*/false,                  \
10718                          integral_constant_expression_p)
10719
10720   tree op1;
10721
10722   if (t == NULL_TREE || t == error_mark_node)
10723     return t;
10724
10725   switch (TREE_CODE (t))
10726     {
10727     case USING_DECL:
10728       t = DECL_NAME (t);
10729       /* Fall through.  */
10730     case IDENTIFIER_NODE:
10731       {
10732         tree decl;
10733         cp_id_kind idk;
10734         bool non_integral_constant_expression_p;
10735         const char *error_msg;
10736
10737         if (IDENTIFIER_TYPENAME_P (t))
10738           {
10739             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10740             t = mangle_conv_op_name_for_type (new_type);
10741           }
10742
10743         /* Look up the name.  */
10744         decl = lookup_name (t);
10745
10746         /* By convention, expressions use ERROR_MARK_NODE to indicate
10747            failure, not NULL_TREE.  */
10748         if (decl == NULL_TREE)
10749           decl = error_mark_node;
10750
10751         decl = finish_id_expression (t, decl, NULL_TREE,
10752                                      &idk,
10753                                      integral_constant_expression_p,
10754                                      /*allow_non_integral_constant_expression_p=*/false,
10755                                      &non_integral_constant_expression_p,
10756                                      /*template_p=*/false,
10757                                      /*done=*/true,
10758                                      /*address_p=*/false,
10759                                      /*template_arg_p=*/false,
10760                                      &error_msg);
10761         if (error_msg)
10762           error (error_msg);
10763         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
10764           decl = unqualified_name_lookup_error (decl);
10765         return decl;
10766       }
10767
10768     case TEMPLATE_ID_EXPR:
10769       {
10770         tree object;
10771         tree template = RECUR (TREE_OPERAND (t, 0));
10772         tree targs = TREE_OPERAND (t, 1);
10773
10774         if (targs)
10775           targs = tsubst_template_args (targs, args, complain, in_decl);
10776
10777         if (TREE_CODE (template) == COMPONENT_REF)
10778           {
10779             object = TREE_OPERAND (template, 0);
10780             template = TREE_OPERAND (template, 1);
10781           }
10782         else
10783           object = NULL_TREE;
10784         template = lookup_template_function (template, targs);
10785
10786         if (object)
10787           return build3 (COMPONENT_REF, TREE_TYPE (template),
10788                          object, template, NULL_TREE);
10789         else
10790           return baselink_for_fns (template);
10791       }
10792
10793     case INDIRECT_REF:
10794       {
10795         tree r = RECUR (TREE_OPERAND (t, 0));
10796
10797         if (REFERENCE_REF_P (t))
10798           {
10799             /* A type conversion to reference type will be enclosed in
10800                such an indirect ref, but the substitution of the cast
10801                will have also added such an indirect ref.  */
10802             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
10803               r = convert_from_reference (r);
10804           }
10805         else
10806           r = build_x_indirect_ref (r, "unary *", complain);
10807         return r;
10808       }
10809
10810     case NOP_EXPR:
10811       return build_nop
10812         (tsubst (TREE_TYPE (t), args, complain, in_decl),
10813          RECUR (TREE_OPERAND (t, 0)));
10814
10815     case CAST_EXPR:
10816     case REINTERPRET_CAST_EXPR:
10817     case CONST_CAST_EXPR:
10818     case DYNAMIC_CAST_EXPR:
10819     case STATIC_CAST_EXPR:
10820       {
10821         tree type;
10822         tree op;
10823
10824         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10825         if (integral_constant_expression_p
10826             && !cast_valid_in_integral_constant_expression_p (type))
10827           {
10828             if (complain & tf_error)
10829               error ("a cast to a type other than an integral or "
10830                      "enumeration type cannot appear in a constant-expression");
10831             return error_mark_node; 
10832           }
10833
10834         op = RECUR (TREE_OPERAND (t, 0));
10835
10836         switch (TREE_CODE (t))
10837           {
10838           case CAST_EXPR:
10839             return build_functional_cast (type, op, complain);
10840           case REINTERPRET_CAST_EXPR:
10841             return build_reinterpret_cast (type, op, complain);
10842           case CONST_CAST_EXPR:
10843             return build_const_cast (type, op, complain);
10844           case DYNAMIC_CAST_EXPR:
10845             return build_dynamic_cast (type, op, complain);
10846           case STATIC_CAST_EXPR:
10847             return build_static_cast (type, op, complain);
10848           default:
10849             gcc_unreachable ();
10850           }
10851       }
10852
10853     case POSTDECREMENT_EXPR:
10854     case POSTINCREMENT_EXPR:
10855       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10856                                                 args, complain, in_decl);
10857       return build_x_unary_op (TREE_CODE (t), op1, complain);
10858
10859     case PREDECREMENT_EXPR:
10860     case PREINCREMENT_EXPR:
10861     case NEGATE_EXPR:
10862     case BIT_NOT_EXPR:
10863     case ABS_EXPR:
10864     case TRUTH_NOT_EXPR:
10865     case UNARY_PLUS_EXPR:  /* Unary + */
10866     case REALPART_EXPR:
10867     case IMAGPART_EXPR:
10868       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
10869                                complain);
10870
10871     case ADDR_EXPR:
10872       op1 = TREE_OPERAND (t, 0);
10873       if (TREE_CODE (op1) == SCOPE_REF)
10874         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
10875                                    /*done=*/true, /*address_p=*/true);
10876       else
10877         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
10878                                                   in_decl);
10879       if (TREE_CODE (op1) == LABEL_DECL)
10880         return finish_label_address_expr (DECL_NAME (op1));
10881       return build_x_unary_op (ADDR_EXPR, op1, complain);
10882
10883     case PLUS_EXPR:
10884     case MINUS_EXPR:
10885     case MULT_EXPR:
10886     case TRUNC_DIV_EXPR:
10887     case CEIL_DIV_EXPR:
10888     case FLOOR_DIV_EXPR:
10889     case ROUND_DIV_EXPR:
10890     case EXACT_DIV_EXPR:
10891     case BIT_AND_EXPR:
10892     case BIT_IOR_EXPR:
10893     case BIT_XOR_EXPR:
10894     case TRUNC_MOD_EXPR:
10895     case FLOOR_MOD_EXPR:
10896     case TRUTH_ANDIF_EXPR:
10897     case TRUTH_ORIF_EXPR:
10898     case TRUTH_AND_EXPR:
10899     case TRUTH_OR_EXPR:
10900     case RSHIFT_EXPR:
10901     case LSHIFT_EXPR:
10902     case RROTATE_EXPR:
10903     case LROTATE_EXPR:
10904     case EQ_EXPR:
10905     case NE_EXPR:
10906     case MAX_EXPR:
10907     case MIN_EXPR:
10908     case LE_EXPR:
10909     case GE_EXPR:
10910     case LT_EXPR:
10911     case GT_EXPR:
10912     case MEMBER_REF:
10913     case DOTSTAR_EXPR:
10914       return build_x_binary_op
10915         (TREE_CODE (t),
10916          RECUR (TREE_OPERAND (t, 0)),
10917          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
10918           ? ERROR_MARK
10919           : TREE_CODE (TREE_OPERAND (t, 0))),
10920          RECUR (TREE_OPERAND (t, 1)),
10921          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
10922           ? ERROR_MARK
10923           : TREE_CODE (TREE_OPERAND (t, 1))),
10924          /*overloaded_p=*/NULL,
10925          complain);
10926
10927     case SCOPE_REF:
10928       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
10929                                   /*address_p=*/false);
10930     case ARRAY_REF:
10931       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10932                                                 args, complain, in_decl);
10933       return build_x_binary_op (ARRAY_REF, op1,
10934                                 (TREE_NO_WARNING (TREE_OPERAND (t, 0))
10935                                  ? ERROR_MARK
10936                                  : TREE_CODE (TREE_OPERAND (t, 0))),
10937                                 RECUR (TREE_OPERAND (t, 1)),
10938                                 (TREE_NO_WARNING (TREE_OPERAND (t, 1))
10939                                  ? ERROR_MARK
10940                                  : TREE_CODE (TREE_OPERAND (t, 1))),
10941                                 /*overloaded_p=*/NULL,
10942                                 complain);
10943
10944     case SIZEOF_EXPR:
10945       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10946         return tsubst_copy (t, args, complain, in_decl);
10947       /* Fall through */
10948       
10949     case ALIGNOF_EXPR:
10950       op1 = TREE_OPERAND (t, 0);
10951       if (!args)
10952         {
10953           /* When there are no ARGS, we are trying to evaluate a
10954              non-dependent expression from the parser.  Trying to do
10955              the substitutions may not work.  */
10956           if (!TYPE_P (op1))
10957             op1 = TREE_TYPE (op1);
10958         }
10959       else
10960         {
10961           ++skip_evaluation;
10962           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
10963                                        /*function_p=*/false,
10964                                        /*integral_constant_expression_p=*/false);
10965           --skip_evaluation;
10966         }
10967       if (TYPE_P (op1))
10968         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
10969                                            complain & tf_error);
10970       else
10971         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
10972                                            complain & tf_error);
10973
10974     case MODOP_EXPR:
10975       {
10976         tree r = build_x_modify_expr
10977           (RECUR (TREE_OPERAND (t, 0)),
10978            TREE_CODE (TREE_OPERAND (t, 1)),
10979            RECUR (TREE_OPERAND (t, 2)),
10980            complain);
10981         /* TREE_NO_WARNING must be set if either the expression was
10982            parenthesized or it uses an operator such as >>= rather
10983            than plain assignment.  In the former case, it was already
10984            set and must be copied.  In the latter case,
10985            build_x_modify_expr sets it and it must not be reset
10986            here.  */
10987         if (TREE_NO_WARNING (t))
10988           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10989         return r;
10990       }
10991
10992     case ARROW_EXPR:
10993       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10994                                                 args, complain, in_decl);
10995       /* Remember that there was a reference to this entity.  */
10996       if (DECL_P (op1))
10997         mark_used (op1);
10998       return build_x_arrow (op1);
10999
11000     case NEW_EXPR:
11001       {
11002         tree init = RECUR (TREE_OPERAND (t, 3));
11003
11004         if (TREE_OPERAND (t, 3) && !init)
11005           /* If there was an initializer in the the original tree, but
11006              it instantiated to an empty list, then we should pass on
11007              VOID_ZERO_NODE to tell build_new that it was an empty
11008              initializer () rather than no initializer.  This can only
11009              happen when the initializer is a pack expansion whose
11010              parameter packs are of length zero.  */
11011           init = void_zero_node;
11012
11013         return build_new
11014           (RECUR (TREE_OPERAND (t, 0)),
11015            RECUR (TREE_OPERAND (t, 1)),
11016            RECUR (TREE_OPERAND (t, 2)),
11017            init,
11018            NEW_EXPR_USE_GLOBAL (t),
11019            complain);
11020       }
11021
11022     case DELETE_EXPR:
11023      return delete_sanity
11024        (RECUR (TREE_OPERAND (t, 0)),
11025         RECUR (TREE_OPERAND (t, 1)),
11026         DELETE_EXPR_USE_VEC (t),
11027         DELETE_EXPR_USE_GLOBAL (t));
11028
11029     case COMPOUND_EXPR:
11030       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11031                                     RECUR (TREE_OPERAND (t, 1)),
11032                                     complain);
11033
11034     case CALL_EXPR:
11035       {
11036         tree function;
11037         tree call_args;
11038         bool qualified_p;
11039         bool koenig_p;
11040
11041         function = CALL_EXPR_FN (t);
11042         /* When we parsed the expression,  we determined whether or
11043            not Koenig lookup should be performed.  */
11044         koenig_p = KOENIG_LOOKUP_P (t);
11045         if (TREE_CODE (function) == SCOPE_REF)
11046           {
11047             qualified_p = true;
11048             function = tsubst_qualified_id (function, args, complain, in_decl,
11049                                             /*done=*/false,
11050                                             /*address_p=*/false);
11051           }
11052         else
11053           {
11054             if (TREE_CODE (function) == COMPONENT_REF)
11055               {
11056                 tree op = TREE_OPERAND (function, 1);
11057
11058                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11059                                || (BASELINK_P (op)
11060                                    && BASELINK_QUALIFIED_P (op)));
11061               }
11062             else
11063               qualified_p = false;
11064
11065             function = tsubst_copy_and_build (function, args, complain,
11066                                               in_decl,
11067                                               !qualified_p,
11068                                               integral_constant_expression_p);
11069
11070             if (BASELINK_P (function))
11071               qualified_p = true;
11072           }
11073
11074         /* FIXME:  Rewrite this so as not to construct an arglist.  */
11075         call_args = RECUR (CALL_EXPR_ARGS (t));
11076
11077         /* We do not perform argument-dependent lookup if normal
11078            lookup finds a non-function, in accordance with the
11079            expected resolution of DR 218.  */
11080         if (koenig_p
11081             && ((is_overloaded_fn (function)
11082                  /* If lookup found a member function, the Koenig lookup is
11083                     not appropriate, even if an unqualified-name was used
11084                     to denote the function.  */
11085                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11086                 || TREE_CODE (function) == IDENTIFIER_NODE))
11087           function = perform_koenig_lookup (function, call_args);
11088
11089         if (TREE_CODE (function) == IDENTIFIER_NODE)
11090           {
11091             unqualified_name_lookup_error (function);
11092             return error_mark_node;
11093           }
11094
11095         /* Remember that there was a reference to this entity.  */
11096         if (DECL_P (function))
11097           mark_used (function);
11098
11099         if (TREE_CODE (function) == OFFSET_REF)
11100           return build_offset_ref_call_from_tree (function, call_args);
11101         if (TREE_CODE (function) == COMPONENT_REF)
11102           {
11103             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11104               return finish_call_expr (function, call_args,
11105                                        /*disallow_virtual=*/false,
11106                                        /*koenig_p=*/false,
11107                                        complain);
11108             else
11109               return (build_new_method_call
11110                       (TREE_OPERAND (function, 0),
11111                        TREE_OPERAND (function, 1),
11112                        call_args, NULL_TREE,
11113                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11114                        /*fn_p=*/NULL,
11115                        complain));
11116           }
11117         return finish_call_expr (function, call_args,
11118                                  /*disallow_virtual=*/qualified_p,
11119                                  koenig_p,
11120                                  complain);
11121       }
11122
11123     case COND_EXPR:
11124       return build_x_conditional_expr
11125         (RECUR (TREE_OPERAND (t, 0)),
11126          RECUR (TREE_OPERAND (t, 1)),
11127          RECUR (TREE_OPERAND (t, 2)),
11128          complain);
11129
11130     case PSEUDO_DTOR_EXPR:
11131       return finish_pseudo_destructor_expr
11132         (RECUR (TREE_OPERAND (t, 0)),
11133          RECUR (TREE_OPERAND (t, 1)),
11134          RECUR (TREE_OPERAND (t, 2)));
11135
11136     case TREE_LIST:
11137       {
11138         tree purpose, value, chain;
11139
11140         if (t == void_list_node)
11141           return t;
11142
11143         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11144             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11145           {
11146             /* We have pack expansions, so expand those and
11147                create a new list out of it.  */
11148             tree purposevec = NULL_TREE;
11149             tree valuevec = NULL_TREE;
11150             tree chain;
11151             int i, len = -1;
11152
11153             /* Expand the argument expressions.  */
11154             if (TREE_PURPOSE (t))
11155               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11156                                                  complain, in_decl);
11157             if (TREE_VALUE (t))
11158               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11159                                                complain, in_decl);
11160
11161             /* Build the rest of the list.  */
11162             chain = TREE_CHAIN (t);
11163             if (chain && chain != void_type_node)
11164               chain = RECUR (chain);
11165
11166             /* Determine the number of arguments.  */
11167             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11168               {
11169                 len = TREE_VEC_LENGTH (purposevec);
11170                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11171               }
11172             else if (TREE_CODE (valuevec) == TREE_VEC)
11173               len = TREE_VEC_LENGTH (valuevec);
11174             else
11175               {
11176                 /* Since we only performed a partial substitution into
11177                    the argument pack, we only return a single list
11178                    node.  */
11179                 if (purposevec == TREE_PURPOSE (t)
11180                     && valuevec == TREE_VALUE (t)
11181                     && chain == TREE_CHAIN (t))
11182                   return t;
11183
11184                 return tree_cons (purposevec, valuevec, chain);
11185               }
11186             
11187             /* Convert the argument vectors into a TREE_LIST */
11188             i = len;
11189             while (i > 0)
11190               {
11191                 /* Grab the Ith values.  */
11192                 i--;
11193                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11194                                      : NULL_TREE;
11195                 value 
11196                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11197                              : NULL_TREE;
11198
11199                 /* Build the list (backwards).  */
11200                 chain = tree_cons (purpose, value, chain);
11201               }
11202
11203             return chain;
11204           }
11205
11206         purpose = TREE_PURPOSE (t);
11207         if (purpose)
11208           purpose = RECUR (purpose);
11209         value = TREE_VALUE (t);
11210         if (value)
11211           value = RECUR (value);
11212         chain = TREE_CHAIN (t);
11213         if (chain && chain != void_type_node)
11214           chain = RECUR (chain);
11215         if (purpose == TREE_PURPOSE (t)
11216             && value == TREE_VALUE (t)
11217             && chain == TREE_CHAIN (t))
11218           return t;
11219         return tree_cons (purpose, value, chain);
11220       }
11221
11222     case COMPONENT_REF:
11223       {
11224         tree object;
11225         tree object_type;
11226         tree member;
11227
11228         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11229                                                      args, complain, in_decl);
11230         /* Remember that there was a reference to this entity.  */
11231         if (DECL_P (object))
11232           mark_used (object);
11233         object_type = TREE_TYPE (object);
11234
11235         member = TREE_OPERAND (t, 1);
11236         if (BASELINK_P (member))
11237           member = tsubst_baselink (member,
11238                                     non_reference (TREE_TYPE (object)),
11239                                     args, complain, in_decl);
11240         else
11241           member = tsubst_copy (member, args, complain, in_decl);
11242         if (member == error_mark_node)
11243           return error_mark_node;
11244
11245         if (object_type && !CLASS_TYPE_P (object_type))
11246           {
11247             if (SCALAR_TYPE_P (object_type))
11248               {
11249                 tree s = NULL_TREE;
11250                 tree dtor = member;
11251
11252                 if (TREE_CODE (dtor) == SCOPE_REF)
11253                   {
11254                     s = TREE_OPERAND (dtor, 0);
11255                     dtor = TREE_OPERAND (dtor, 1);
11256                   }
11257                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11258                   {
11259                     dtor = TREE_OPERAND (dtor, 0);
11260                     if (TYPE_P (dtor))
11261                       return finish_pseudo_destructor_expr (object, s, dtor);
11262                   }
11263               }
11264           }
11265         else if (TREE_CODE (member) == SCOPE_REF
11266                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11267           {
11268             tree tmpl;
11269             tree args;
11270
11271             /* Lookup the template functions now that we know what the
11272                scope is.  */
11273             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11274             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11275             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11276                                             /*is_type_p=*/false,
11277                                             /*complain=*/false);
11278             if (BASELINK_P (member))
11279               {
11280                 BASELINK_FUNCTIONS (member)
11281                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11282                               args);
11283                 member = (adjust_result_of_qualified_name_lookup
11284                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11285                            object_type));
11286               }
11287             else
11288               {
11289                 qualified_name_lookup_error (object_type, tmpl, member);
11290                 return error_mark_node;
11291               }
11292           }
11293         else if (TREE_CODE (member) == SCOPE_REF
11294                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11295                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11296           {
11297             if (complain & tf_error)
11298               {
11299                 if (TYPE_P (TREE_OPERAND (member, 0)))
11300                   error ("%qT is not a class or namespace",
11301                          TREE_OPERAND (member, 0));
11302                 else
11303                   error ("%qD is not a class or namespace",
11304                          TREE_OPERAND (member, 0));
11305               }
11306             return error_mark_node;
11307           }
11308         else if (TREE_CODE (member) == FIELD_DECL)
11309           return finish_non_static_data_member (member, object, NULL_TREE);
11310
11311         return finish_class_member_access_expr (object, member,
11312                                                 /*template_p=*/false,
11313                                                 complain);
11314       }
11315
11316     case THROW_EXPR:
11317       return build_throw
11318         (RECUR (TREE_OPERAND (t, 0)));
11319
11320     case CONSTRUCTOR:
11321       {
11322         VEC(constructor_elt,gc) *n;
11323         constructor_elt *ce;
11324         unsigned HOST_WIDE_INT idx;
11325         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11326         bool process_index_p;
11327         int newlen;
11328         bool need_copy_p = false;
11329
11330         if (type == error_mark_node)
11331           return error_mark_node;
11332
11333         /* digest_init will do the wrong thing if we let it.  */
11334         if (type && TYPE_PTRMEMFUNC_P (type))
11335           return t;
11336
11337         /* We do not want to process the index of aggregate
11338            initializers as they are identifier nodes which will be
11339            looked up by digest_init.  */
11340         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
11341
11342         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11343         newlen = VEC_length (constructor_elt, n);
11344         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11345           {
11346             if (ce->index && process_index_p)
11347               ce->index = RECUR (ce->index);
11348
11349             if (PACK_EXPANSION_P (ce->value))
11350               {
11351                 /* Substitute into the pack expansion.  */
11352                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11353                                                   in_decl);
11354
11355                 if (ce->value == error_mark_node)
11356                   ;
11357                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11358                   /* Just move the argument into place.  */
11359                   ce->value = TREE_VEC_ELT (ce->value, 0);
11360                 else
11361                   {
11362                     /* Update the length of the final CONSTRUCTOR
11363                        arguments vector, and note that we will need to
11364                        copy.*/
11365                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11366                     need_copy_p = true;
11367                   }
11368               }
11369             else
11370               ce->value = RECUR (ce->value);
11371           }
11372
11373         if (need_copy_p)
11374           {
11375             VEC(constructor_elt,gc) *old_n = n;
11376
11377             n = VEC_alloc (constructor_elt, gc, newlen);
11378             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11379                  idx++)
11380               {
11381                 if (TREE_CODE (ce->value) == TREE_VEC)
11382                   {
11383                     int i, len = TREE_VEC_LENGTH (ce->value);
11384                     for (i = 0; i < len; ++i)
11385                       CONSTRUCTOR_APPEND_ELT (n, 0,
11386                                               TREE_VEC_ELT (ce->value, i));
11387                   }
11388                 else
11389                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11390               }
11391           }
11392
11393         if (TREE_HAS_CONSTRUCTOR (t))
11394           return finish_compound_literal (type, n);
11395
11396         return build_constructor (NULL_TREE, n);
11397       }
11398
11399     case TYPEID_EXPR:
11400       {
11401         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11402         if (TYPE_P (operand_0))
11403           return get_typeid (operand_0);
11404         return build_typeid (operand_0);
11405       }
11406
11407     case VAR_DECL:
11408       if (!args)
11409         return t;
11410       /* Fall through */
11411
11412     case PARM_DECL:
11413       {
11414         tree r = tsubst_copy (t, args, complain, in_decl);
11415
11416         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11417           /* If the original type was a reference, we'll be wrapped in
11418              the appropriate INDIRECT_REF.  */
11419           r = convert_from_reference (r);
11420         return r;
11421       }
11422
11423     case VA_ARG_EXPR:
11424       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11425                              tsubst_copy (TREE_TYPE (t), args, complain,
11426                                           in_decl));
11427
11428     case OFFSETOF_EXPR:
11429       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11430
11431     case TRAIT_EXPR:
11432       {
11433         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11434                                   complain, in_decl);
11435
11436         tree type2 = TRAIT_EXPR_TYPE2 (t);
11437         if (type2)
11438           type2 = tsubst_copy (type2, args, complain, in_decl);
11439         
11440         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11441       }
11442
11443     case STMT_EXPR:
11444       {
11445         tree old_stmt_expr = cur_stmt_expr;
11446         tree stmt_expr = begin_stmt_expr ();
11447
11448         cur_stmt_expr = stmt_expr;
11449         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11450                      integral_constant_expression_p);
11451         stmt_expr = finish_stmt_expr (stmt_expr, false);
11452         cur_stmt_expr = old_stmt_expr;
11453
11454         return stmt_expr;
11455       }
11456
11457     case CONST_DECL:
11458       t = tsubst_copy (t, args, complain, in_decl);
11459       /* As in finish_id_expression, we resolve enumeration constants
11460          to their underlying values.  */
11461       if (TREE_CODE (t) == CONST_DECL)
11462         {
11463           used_types_insert (TREE_TYPE (t));
11464           return DECL_INITIAL (t);
11465         }
11466       return t;
11467
11468     default:
11469       /* Handle Objective-C++ constructs, if appropriate.  */
11470       {
11471         tree subst
11472           = objcp_tsubst_copy_and_build (t, args, complain,
11473                                          in_decl, /*function_p=*/false);
11474         if (subst)
11475           return subst;
11476       }
11477       return tsubst_copy (t, args, complain, in_decl);
11478     }
11479
11480 #undef RECUR
11481 }
11482
11483 /* Verify that the instantiated ARGS are valid. For type arguments,
11484    make sure that the type's linkage is ok. For non-type arguments,
11485    make sure they are constants if they are integral or enumerations.
11486    Emit an error under control of COMPLAIN, and return TRUE on error.  */
11487
11488 static bool
11489 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
11490 {
11491   int ix, len = DECL_NTPARMS (tmpl);
11492   bool result = false;
11493
11494   for (ix = 0; ix != len; ix++)
11495     {
11496       tree t = TREE_VEC_ELT (args, ix);
11497
11498       if (TYPE_P (t))
11499         {
11500           /* [basic.link]: A name with no linkage (notably, the name
11501              of a class or enumeration declared in a local scope)
11502              shall not be used to declare an entity with linkage.
11503              This implies that names with no linkage cannot be used as
11504              template arguments.  */
11505           tree nt = no_linkage_check (t, /*relaxed_p=*/false);
11506
11507           if (nt)
11508             {
11509               /* DR 488 makes use of a type with no linkage cause
11510                  type deduction to fail.  */
11511               if (complain & tf_error)
11512                 {
11513                   if (TYPE_ANONYMOUS_P (nt))
11514                     error ("%qT is/uses anonymous type", t);
11515                   else
11516                     error ("template argument for %qD uses local type %qT",
11517                            tmpl, t);
11518                 }
11519               result = true;
11520             }
11521           /* In order to avoid all sorts of complications, we do not
11522              allow variably-modified types as template arguments.  */
11523           else if (variably_modified_type_p (t, NULL_TREE))
11524             {
11525               if (complain & tf_error)
11526                 error ("%qT is a variably modified type", t);
11527               result = true;
11528             }
11529         }
11530       /* A non-type argument of integral or enumerated type must be a
11531          constant.  */
11532       else if (TREE_TYPE (t)
11533                && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
11534                && !TREE_CONSTANT (t))
11535         {
11536           if (complain & tf_error)
11537             error ("integral expression %qE is not constant", t);
11538           result = true;
11539         }
11540     }
11541   if (result && (complain & tf_error))
11542     error ("  trying to instantiate %qD", tmpl);
11543   return result;
11544 }
11545
11546 /* Instantiate the indicated variable or function template TMPL with
11547    the template arguments in TARG_PTR.  */
11548
11549 tree
11550 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
11551 {
11552   tree fndecl;
11553   tree gen_tmpl;
11554   tree spec;
11555   HOST_WIDE_INT saved_processing_template_decl;
11556
11557   if (tmpl == error_mark_node)
11558     return error_mark_node;
11559
11560   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
11561
11562   /* If this function is a clone, handle it specially.  */
11563   if (DECL_CLONED_FUNCTION_P (tmpl))
11564     {
11565       tree spec;
11566       tree clone;
11567
11568       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
11569                                    complain);
11570       if (spec == error_mark_node)
11571         return error_mark_node;
11572
11573       /* Look for the clone.  */
11574       FOR_EACH_CLONE (clone, spec)
11575         if (DECL_NAME (clone) == DECL_NAME (tmpl))
11576           return clone;
11577       /* We should always have found the clone by now.  */
11578       gcc_unreachable ();
11579       return NULL_TREE;
11580     }
11581
11582   /* Check to see if we already have this specialization.  */
11583   spec = retrieve_specialization (tmpl, targ_ptr,
11584                                   /*class_specializations_p=*/false);
11585   if (spec != NULL_TREE)
11586     return spec;
11587
11588   gen_tmpl = most_general_template (tmpl);
11589   if (tmpl != gen_tmpl)
11590     {
11591       /* The TMPL is a partial instantiation.  To get a full set of
11592          arguments we must add the arguments used to perform the
11593          partial instantiation.  */
11594       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
11595                                               targ_ptr);
11596
11597       /* Check to see if we already have this specialization.  */
11598       spec = retrieve_specialization (gen_tmpl, targ_ptr,
11599                                       /*class_specializations_p=*/false);
11600       if (spec != NULL_TREE)
11601         return spec;
11602     }
11603
11604   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
11605                                complain))
11606     return error_mark_node;
11607
11608   /* We are building a FUNCTION_DECL, during which the access of its
11609      parameters and return types have to be checked.  However this
11610      FUNCTION_DECL which is the desired context for access checking
11611      is not built yet.  We solve this chicken-and-egg problem by
11612      deferring all checks until we have the FUNCTION_DECL.  */
11613   push_deferring_access_checks (dk_deferred);
11614
11615   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
11616      (because, for example, we have encountered a non-dependent
11617      function call in the body of a template function and must now
11618      determine which of several overloaded functions will be called),
11619      within the instantiation itself we are not processing a
11620      template.  */  
11621   saved_processing_template_decl = processing_template_decl;
11622   processing_template_decl = 0;
11623   /* Substitute template parameters to obtain the specialization.  */
11624   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
11625                    targ_ptr, complain, gen_tmpl);
11626   processing_template_decl = saved_processing_template_decl;
11627   if (fndecl == error_mark_node)
11628     return error_mark_node;
11629
11630   /* Now we know the specialization, compute access previously
11631      deferred.  */
11632   push_access_scope (fndecl);
11633   perform_deferred_access_checks ();
11634   pop_access_scope (fndecl);
11635   pop_deferring_access_checks ();
11636
11637   /* The DECL_TI_TEMPLATE should always be the immediate parent
11638      template, not the most general template.  */
11639   DECL_TI_TEMPLATE (fndecl) = tmpl;
11640
11641   /* If we've just instantiated the main entry point for a function,
11642      instantiate all the alternate entry points as well.  We do this
11643      by cloning the instantiation of the main entry point, not by
11644      instantiating the template clones.  */
11645   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
11646     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
11647
11648   return fndecl;
11649 }
11650
11651 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
11652    arguments that are being used when calling it.  TARGS is a vector
11653    into which the deduced template arguments are placed.
11654
11655    Return zero for success, 2 for an incomplete match that doesn't resolve
11656    all the types, and 1 for complete failure.  An error message will be
11657    printed only for an incomplete match.
11658
11659    If FN is a conversion operator, or we are trying to produce a specific
11660    specialization, RETURN_TYPE is the return type desired.
11661
11662    The EXPLICIT_TARGS are explicit template arguments provided via a
11663    template-id.
11664
11665    The parameter STRICT is one of:
11666
11667    DEDUCE_CALL:
11668      We are deducing arguments for a function call, as in
11669      [temp.deduct.call].
11670
11671    DEDUCE_CONV:
11672      We are deducing arguments for a conversion function, as in
11673      [temp.deduct.conv].
11674
11675    DEDUCE_EXACT:
11676      We are deducing arguments when doing an explicit instantiation
11677      as in [temp.explicit], when determining an explicit specialization
11678      as in [temp.expl.spec], or when taking the address of a function
11679      template, as in [temp.deduct.funcaddr].  */
11680
11681 int
11682 fn_type_unification (tree fn,
11683                      tree explicit_targs,
11684                      tree targs,
11685                      tree args,
11686                      tree return_type,
11687                      unification_kind_t strict,
11688                      int flags)
11689 {
11690   tree parms;
11691   tree fntype;
11692   int result;
11693   bool incomplete_argument_packs_p = false;
11694
11695   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
11696
11697   fntype = TREE_TYPE (fn);
11698   if (explicit_targs)
11699     {
11700       /* [temp.deduct]
11701
11702          The specified template arguments must match the template
11703          parameters in kind (i.e., type, nontype, template), and there
11704          must not be more arguments than there are parameters;
11705          otherwise type deduction fails.
11706
11707          Nontype arguments must match the types of the corresponding
11708          nontype template parameters, or must be convertible to the
11709          types of the corresponding nontype parameters as specified in
11710          _temp.arg.nontype_, otherwise type deduction fails.
11711
11712          All references in the function type of the function template
11713          to the corresponding template parameters are replaced by the
11714          specified template argument values.  If a substitution in a
11715          template parameter or in the function type of the function
11716          template results in an invalid type, type deduction fails.  */
11717       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
11718       int i, len = TREE_VEC_LENGTH (tparms);
11719       tree converted_args;
11720       bool incomplete = false;
11721
11722       if (explicit_targs == error_mark_node)
11723         return 1;
11724
11725       converted_args
11726         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
11727                                   /*require_all_args=*/false,
11728                                   /*use_default_args=*/false));
11729       if (converted_args == error_mark_node)
11730         return 1;
11731
11732       /* Substitute the explicit args into the function type.  This is
11733          necessary so that, for instance, explicitly declared function
11734          arguments can match null pointed constants.  If we were given
11735          an incomplete set of explicit args, we must not do semantic
11736          processing during substitution as we could create partial
11737          instantiations.  */
11738       for (i = 0; i < len; i++)
11739         {
11740           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
11741           bool parameter_pack = false;
11742
11743           /* Dig out the actual parm.  */
11744           if (TREE_CODE (parm) == TYPE_DECL
11745               || TREE_CODE (parm) == TEMPLATE_DECL)
11746             {
11747               parm = TREE_TYPE (parm);
11748               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
11749             }
11750           else if (TREE_CODE (parm) == PARM_DECL)
11751             {
11752               parm = DECL_INITIAL (parm);
11753               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
11754             }
11755
11756           if (parameter_pack)
11757             {
11758               int level, idx;
11759               tree targ;
11760               template_parm_level_and_index (parm, &level, &idx);
11761
11762               /* Mark the argument pack as "incomplete". We could
11763                  still deduce more arguments during unification.  */
11764               targ = TMPL_ARG (converted_args, level, idx);
11765               if (targ)
11766                 {
11767                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
11768                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
11769                     = ARGUMENT_PACK_ARGS (targ);
11770                 }
11771
11772               /* We have some incomplete argument packs.  */
11773               incomplete_argument_packs_p = true;
11774             }
11775         }
11776
11777       if (incomplete_argument_packs_p)
11778         /* Any substitution is guaranteed to be incomplete if there
11779            are incomplete argument packs, because we can still deduce
11780            more arguments.  */
11781         incomplete = 1;
11782       else
11783         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
11784
11785       processing_template_decl += incomplete;
11786       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
11787       processing_template_decl -= incomplete;
11788
11789       if (fntype == error_mark_node)
11790         return 1;
11791
11792       /* Place the explicitly specified arguments in TARGS.  */
11793       for (i = NUM_TMPL_ARGS (converted_args); i--;)
11794         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
11795     }
11796
11797   /* Never do unification on the 'this' parameter.  */
11798   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
11799
11800   if (return_type)
11801     {
11802       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
11803       args = tree_cons (NULL_TREE, return_type, args);
11804     }
11805
11806   /* We allow incomplete unification without an error message here
11807      because the standard doesn't seem to explicitly prohibit it.  Our
11808      callers must be ready to deal with unification failures in any
11809      event.  */
11810   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
11811                                   targs, parms, args, /*subr=*/0,
11812                                   strict, flags);
11813
11814   if (result == 0 && incomplete_argument_packs_p)
11815     {
11816       int i, len = NUM_TMPL_ARGS (targs);
11817
11818       /* Clear the "incomplete" flags on all argument packs.  */
11819       for (i = 0; i < len; i++)
11820         {
11821           tree arg = TREE_VEC_ELT (targs, i);
11822           if (ARGUMENT_PACK_P (arg))
11823             {
11824               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
11825               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
11826             }
11827         }
11828     }
11829
11830   /* Now that we have bindings for all of the template arguments,
11831      ensure that the arguments deduced for the template template
11832      parameters have compatible template parameter lists.  We cannot
11833      check this property before we have deduced all template
11834      arguments, because the template parameter types of a template
11835      template parameter might depend on prior template parameters
11836      deduced after the template template parameter.  The following
11837      ill-formed example illustrates this issue:
11838
11839        template<typename T, template<T> class C> void f(C<5>, T);
11840
11841        template<int N> struct X {};
11842
11843        void g() {
11844          f(X<5>(), 5l); // error: template argument deduction fails
11845        }
11846
11847      The template parameter list of 'C' depends on the template type
11848      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
11849      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
11850      time that we deduce 'C'.  */
11851   if (result == 0
11852       && !template_template_parm_bindings_ok_p 
11853            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
11854     return 1;
11855
11856   if (result == 0)
11857     /* All is well so far.  Now, check:
11858
11859        [temp.deduct]
11860
11861        When all template arguments have been deduced, all uses of
11862        template parameters in nondeduced contexts are replaced with
11863        the corresponding deduced argument values.  If the
11864        substitution results in an invalid type, as described above,
11865        type deduction fails.  */
11866     if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
11867         == error_mark_node)
11868       return 1;
11869
11870   return result;
11871 }
11872
11873 /* Adjust types before performing type deduction, as described in
11874    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
11875    sections are symmetric.  PARM is the type of a function parameter
11876    or the return type of the conversion function.  ARG is the type of
11877    the argument passed to the call, or the type of the value
11878    initialized with the result of the conversion function.
11879    ARG_EXPR is the original argument expression, which may be null.  */
11880
11881 static int
11882 maybe_adjust_types_for_deduction (unification_kind_t strict,
11883                                   tree* parm,
11884                                   tree* arg,
11885                                   tree arg_expr)
11886 {
11887   int result = 0;
11888
11889   switch (strict)
11890     {
11891     case DEDUCE_CALL:
11892       break;
11893
11894     case DEDUCE_CONV:
11895       {
11896         /* Swap PARM and ARG throughout the remainder of this
11897            function; the handling is precisely symmetric since PARM
11898            will initialize ARG rather than vice versa.  */
11899         tree* temp = parm;
11900         parm = arg;
11901         arg = temp;
11902         break;
11903       }
11904
11905     case DEDUCE_EXACT:
11906       /* There is nothing to do in this case.  */
11907       return 0;
11908
11909     default:
11910       gcc_unreachable ();
11911     }
11912
11913   if (TREE_CODE (*parm) != REFERENCE_TYPE)
11914     {
11915       /* [temp.deduct.call]
11916
11917          If P is not a reference type:
11918
11919          --If A is an array type, the pointer type produced by the
11920          array-to-pointer standard conversion (_conv.array_) is
11921          used in place of A for type deduction; otherwise,
11922
11923          --If A is a function type, the pointer type produced by
11924          the function-to-pointer standard conversion
11925          (_conv.func_) is used in place of A for type deduction;
11926          otherwise,
11927
11928          --If A is a cv-qualified type, the top level
11929          cv-qualifiers of A's type are ignored for type
11930          deduction.  */
11931       if (TREE_CODE (*arg) == ARRAY_TYPE)
11932         *arg = build_pointer_type (TREE_TYPE (*arg));
11933       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
11934         *arg = build_pointer_type (*arg);
11935       else
11936         *arg = TYPE_MAIN_VARIANT (*arg);
11937     }
11938
11939   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
11940      of the form T&&, where T is a template parameter, and the argument
11941      is an lvalue, T is deduced as A& */
11942   if (TREE_CODE (*parm) == REFERENCE_TYPE
11943       && TYPE_REF_IS_RVALUE (*parm)
11944       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
11945       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
11946       && arg_expr && real_lvalue_p (arg_expr))
11947     *arg = build_reference_type (*arg);
11948
11949   /* [temp.deduct.call]
11950
11951      If P is a cv-qualified type, the top level cv-qualifiers
11952      of P's type are ignored for type deduction.  If P is a
11953      reference type, the type referred to by P is used for
11954      type deduction.  */
11955   *parm = TYPE_MAIN_VARIANT (*parm);
11956   if (TREE_CODE (*parm) == REFERENCE_TYPE)
11957     {
11958       *parm = TREE_TYPE (*parm);
11959       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
11960     }
11961
11962   /* DR 322. For conversion deduction, remove a reference type on parm
11963      too (which has been swapped into ARG).  */
11964   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
11965     *arg = TREE_TYPE (*arg);
11966
11967   return result;
11968 }
11969
11970 /* Most parms like fn_type_unification.
11971
11972    If SUBR is 1, we're being called recursively (to unify the
11973    arguments of a function or method parameter of a function
11974    template). */
11975
11976 static int
11977 type_unification_real (tree tparms,
11978                        tree targs,
11979                        tree xparms,
11980                        tree xargs,
11981                        int subr,
11982                        unification_kind_t strict,
11983                        int flags)
11984 {
11985   tree parm, arg, arg_expr;
11986   int i;
11987   int ntparms = TREE_VEC_LENGTH (tparms);
11988   int sub_strict;
11989   int saw_undeduced = 0;
11990   tree parms, args;
11991
11992   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
11993   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
11994   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
11995   gcc_assert (ntparms > 0);
11996
11997   switch (strict)
11998     {
11999     case DEDUCE_CALL:
12000       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12001                     | UNIFY_ALLOW_DERIVED);
12002       break;
12003
12004     case DEDUCE_CONV:
12005       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12006       break;
12007
12008     case DEDUCE_EXACT:
12009       sub_strict = UNIFY_ALLOW_NONE;
12010       break;
12011
12012     default:
12013       gcc_unreachable ();
12014     }
12015
12016  again:
12017   parms = xparms;
12018   args = xargs;
12019
12020   while (parms && parms != void_list_node
12021          && args && args != void_list_node)
12022     {
12023       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12024         break;
12025
12026       parm = TREE_VALUE (parms);
12027       parms = TREE_CHAIN (parms);
12028       arg = TREE_VALUE (args);
12029       args = TREE_CHAIN (args);
12030       arg_expr = NULL;
12031
12032       if (arg == error_mark_node)
12033         return 1;
12034       if (arg == unknown_type_node)
12035         /* We can't deduce anything from this, but we might get all the
12036            template args from other function args.  */
12037         continue;
12038
12039       /* Conversions will be performed on a function argument that
12040          corresponds with a function parameter that contains only
12041          non-deducible template parameters and explicitly specified
12042          template parameters.  */
12043       if (!uses_template_parms (parm))
12044         {
12045           tree type;
12046
12047           if (!TYPE_P (arg))
12048             type = TREE_TYPE (arg);
12049           else
12050             type = arg;
12051
12052           if (same_type_p (parm, type))
12053             continue;
12054           if (strict != DEDUCE_EXACT
12055               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12056                                   flags))
12057             continue;
12058
12059           return 1;
12060         }
12061
12062       if (!TYPE_P (arg))
12063         {
12064           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12065           if (type_unknown_p (arg))
12066             {
12067               /* [temp.deduct.type] 
12068
12069                  A template-argument can be deduced from a pointer to
12070                  function or pointer to member function argument if
12071                  the set of overloaded functions does not contain
12072                  function templates and at most one of a set of
12073                  overloaded functions provides a unique match.  */
12074               if (resolve_overloaded_unification
12075                   (tparms, targs, parm, arg, strict, sub_strict))
12076                 continue;
12077
12078               return 1;
12079             }
12080           arg_expr = arg;
12081           arg = unlowered_expr_type (arg);
12082           if (arg == error_mark_node)
12083             return 1;
12084         }
12085
12086       {
12087         int arg_strict = sub_strict;
12088
12089         if (!subr)
12090           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12091                                                           arg_expr);
12092
12093         if (unify (tparms, targs, parm, arg, arg_strict))
12094           return 1;
12095       }
12096     }
12097
12098
12099   if (parms 
12100       && parms != void_list_node
12101       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12102     {
12103       /* Unify the remaining arguments with the pack expansion type.  */
12104       tree argvec;
12105       tree parmvec = make_tree_vec (1);
12106       int len = 0;
12107       tree t;
12108
12109       /* Count the number of arguments that remain.  */
12110       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
12111         len++;
12112         
12113       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12114       argvec = make_tree_vec (len);
12115       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
12116         {
12117           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
12118           ++i;
12119         }
12120
12121       /* Copy the parameter into parmvec.  */
12122       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12123       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12124                                 /*call_args_p=*/true, /*subr=*/subr))
12125         return 1;
12126
12127       /* Advance to the end of the list of parameters.  */
12128       parms = TREE_CHAIN (parms);
12129     }
12130
12131   /* Fail if we've reached the end of the parm list, and more args
12132      are present, and the parm list isn't variadic.  */
12133   if (args && args != void_list_node && parms == void_list_node)
12134     return 1;
12135   /* Fail if parms are left and they don't have default values.  */
12136   if (parms && parms != void_list_node
12137       && TREE_PURPOSE (parms) == NULL_TREE)
12138     return 1;
12139
12140   if (!subr)
12141     for (i = 0; i < ntparms; i++)
12142       if (!TREE_VEC_ELT (targs, i))
12143         {
12144           tree tparm;
12145
12146           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12147             continue;
12148
12149           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12150
12151           /* If this is an undeduced nontype parameter that depends on
12152              a type parameter, try another pass; its type may have been
12153              deduced from a later argument than the one from which
12154              this parameter can be deduced.  */
12155           if (TREE_CODE (tparm) == PARM_DECL
12156               && uses_template_parms (TREE_TYPE (tparm))
12157               && !saw_undeduced++)
12158             goto again;
12159
12160           /* Core issue #226 (C++0x) [temp.deduct]:
12161
12162                If a template argument has not been deduced, its
12163                default template argument, if any, is used. 
12164
12165              When we are in C++98 mode, TREE_PURPOSE will either
12166              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12167              to explicitly check cxx_dialect here.  */
12168           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12169             {
12170               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
12171                                  targs, tf_none, NULL_TREE);
12172               if (arg == error_mark_node)
12173                 return 1;
12174               else
12175                 {
12176                   TREE_VEC_ELT (targs, i) = arg;
12177                   continue;
12178                 }
12179             }
12180
12181           /* If the type parameter is a parameter pack, then it will
12182              be deduced to an empty parameter pack.  */
12183           if (template_parameter_pack_p (tparm))
12184             {
12185               tree arg;
12186
12187               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12188                 {
12189                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12190                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12191                   TREE_CONSTANT (arg) = 1;
12192                 }
12193               else
12194                 arg = make_node (TYPE_ARGUMENT_PACK);
12195
12196               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12197
12198               TREE_VEC_ELT (targs, i) = arg;
12199               continue;
12200             }
12201
12202           return 2;
12203         }
12204
12205   return 0;
12206 }
12207
12208 /* Subroutine of type_unification_real.  Args are like the variables
12209    at the call site.  ARG is an overloaded function (or template-id);
12210    we try deducing template args from each of the overloads, and if
12211    only one succeeds, we go with that.  Modifies TARGS and returns
12212    true on success.  */
12213
12214 static bool
12215 resolve_overloaded_unification (tree tparms,
12216                                 tree targs,
12217                                 tree parm,
12218                                 tree arg,
12219                                 unification_kind_t strict,
12220                                 int sub_strict)
12221 {
12222   tree tempargs = copy_node (targs);
12223   int good = 0;
12224   bool addr_p;
12225
12226   if (TREE_CODE (arg) == ADDR_EXPR)
12227     {
12228       arg = TREE_OPERAND (arg, 0);
12229       addr_p = true;
12230     }
12231   else
12232     addr_p = false;
12233
12234   if (TREE_CODE (arg) == COMPONENT_REF)
12235     /* Handle `&x' where `x' is some static or non-static member
12236        function name.  */
12237     arg = TREE_OPERAND (arg, 1);
12238
12239   if (TREE_CODE (arg) == OFFSET_REF)
12240     arg = TREE_OPERAND (arg, 1);
12241
12242   /* Strip baselink information.  */
12243   if (BASELINK_P (arg))
12244     arg = BASELINK_FUNCTIONS (arg);
12245
12246   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12247     {
12248       /* If we got some explicit template args, we need to plug them into
12249          the affected templates before we try to unify, in case the
12250          explicit args will completely resolve the templates in question.  */
12251
12252       tree expl_subargs = TREE_OPERAND (arg, 1);
12253       arg = TREE_OPERAND (arg, 0);
12254
12255       for (; arg; arg = OVL_NEXT (arg))
12256         {
12257           tree fn = OVL_CURRENT (arg);
12258           tree subargs, elem;
12259
12260           if (TREE_CODE (fn) != TEMPLATE_DECL)
12261             continue;
12262
12263           ++processing_template_decl;
12264           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12265                                   expl_subargs, /*check_ret=*/false);
12266           if (subargs)
12267             {
12268               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12269               good += try_one_overload (tparms, targs, tempargs, parm,
12270                                         elem, strict, sub_strict, addr_p);
12271             }
12272           --processing_template_decl;
12273         }
12274     }
12275   else if (TREE_CODE (arg) != OVERLOAD
12276            && TREE_CODE (arg) != FUNCTION_DECL)
12277     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12278        -- but the deduction does not succeed because the expression is
12279        not just the function on its own.  */
12280     return false;
12281   else
12282     for (; arg; arg = OVL_NEXT (arg))
12283       good += try_one_overload (tparms, targs, tempargs, parm,
12284                                 TREE_TYPE (OVL_CURRENT (arg)),
12285                                 strict, sub_strict, addr_p);
12286
12287   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12288      to function or pointer to member function argument if the set of
12289      overloaded functions does not contain function templates and at most
12290      one of a set of overloaded functions provides a unique match.
12291
12292      So if we found multiple possibilities, we return success but don't
12293      deduce anything.  */
12294
12295   if (good == 1)
12296     {
12297       int i = TREE_VEC_LENGTH (targs);
12298       for (; i--; )
12299         if (TREE_VEC_ELT (tempargs, i))
12300           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12301     }
12302   if (good)
12303     return true;
12304
12305   return false;
12306 }
12307
12308 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12309    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12310    different overloads deduce different arguments for a given parm.
12311    ADDR_P is true if the expression for which deduction is being
12312    performed was of the form "& fn" rather than simply "fn".
12313
12314    Returns 1 on success.  */
12315
12316 static int
12317 try_one_overload (tree tparms,
12318                   tree orig_targs,
12319                   tree targs,
12320                   tree parm,
12321                   tree arg,
12322                   unification_kind_t strict,
12323                   int sub_strict,
12324                   bool addr_p)
12325 {
12326   int nargs;
12327   tree tempargs;
12328   int i;
12329
12330   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12331      to function or pointer to member function argument if the set of
12332      overloaded functions does not contain function templates and at most
12333      one of a set of overloaded functions provides a unique match.
12334
12335      So if this is a template, just return success.  */
12336
12337   if (uses_template_parms (arg))
12338     return 1;
12339
12340   if (TREE_CODE (arg) == METHOD_TYPE)
12341     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12342   else if (addr_p)
12343     arg = build_pointer_type (arg);
12344
12345   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12346
12347   /* We don't copy orig_targs for this because if we have already deduced
12348      some template args from previous args, unify would complain when we
12349      try to deduce a template parameter for the same argument, even though
12350      there isn't really a conflict.  */
12351   nargs = TREE_VEC_LENGTH (targs);
12352   tempargs = make_tree_vec (nargs);
12353
12354   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12355     return 0;
12356
12357   /* First make sure we didn't deduce anything that conflicts with
12358      explicitly specified args.  */
12359   for (i = nargs; i--; )
12360     {
12361       tree elt = TREE_VEC_ELT (tempargs, i);
12362       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12363
12364       if (!elt)
12365         /*NOP*/;
12366       else if (uses_template_parms (elt))
12367         /* Since we're unifying against ourselves, we will fill in
12368            template args used in the function parm list with our own
12369            template parms.  Discard them.  */
12370         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12371       else if (oldelt && !template_args_equal (oldelt, elt))
12372         return 0;
12373     }
12374
12375   for (i = nargs; i--; )
12376     {
12377       tree elt = TREE_VEC_ELT (tempargs, i);
12378
12379       if (elt)
12380         TREE_VEC_ELT (targs, i) = elt;
12381     }
12382
12383   return 1;
12384 }
12385
12386 /* PARM is a template class (perhaps with unbound template
12387    parameters).  ARG is a fully instantiated type.  If ARG can be
12388    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12389    TARGS are as for unify.  */
12390
12391 static tree
12392 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12393 {
12394   tree copy_of_targs;
12395
12396   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12397       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12398           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12399     return NULL_TREE;
12400
12401   /* We need to make a new template argument vector for the call to
12402      unify.  If we used TARGS, we'd clutter it up with the result of
12403      the attempted unification, even if this class didn't work out.
12404      We also don't want to commit ourselves to all the unifications
12405      we've already done, since unification is supposed to be done on
12406      an argument-by-argument basis.  In other words, consider the
12407      following pathological case:
12408
12409        template <int I, int J, int K>
12410        struct S {};
12411
12412        template <int I, int J>
12413        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12414
12415        template <int I, int J, int K>
12416        void f(S<I, J, K>, S<I, I, I>);
12417
12418        void g() {
12419          S<0, 0, 0> s0;
12420          S<0, 1, 2> s2;
12421
12422          f(s0, s2);
12423        }
12424
12425      Now, by the time we consider the unification involving `s2', we
12426      already know that we must have `f<0, 0, 0>'.  But, even though
12427      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
12428      because there are two ways to unify base classes of S<0, 1, 2>
12429      with S<I, I, I>.  If we kept the already deduced knowledge, we
12430      would reject the possibility I=1.  */
12431   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
12432
12433   /* If unification failed, we're done.  */
12434   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
12435              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
12436     return NULL_TREE;
12437
12438   return arg;
12439 }
12440
12441 /* Given a template type PARM and a class type ARG, find the unique
12442    base type in ARG that is an instance of PARM.  We do not examine
12443    ARG itself; only its base-classes.  If there is not exactly one
12444    appropriate base class, return NULL_TREE.  PARM may be the type of
12445    a partial specialization, as well as a plain template type.  Used
12446    by unify.  */
12447
12448 static tree
12449 get_template_base (tree tparms, tree targs, tree parm, tree arg)
12450 {
12451   tree rval = NULL_TREE;
12452   tree binfo;
12453
12454   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
12455
12456   binfo = TYPE_BINFO (complete_type (arg));
12457   if (!binfo)
12458     /* The type could not be completed.  */
12459     return NULL_TREE;
12460
12461   /* Walk in inheritance graph order.  The search order is not
12462      important, and this avoids multiple walks of virtual bases.  */
12463   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
12464     {
12465       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
12466
12467       if (r)
12468         {
12469           /* If there is more than one satisfactory baseclass, then:
12470
12471                [temp.deduct.call]
12472
12473               If they yield more than one possible deduced A, the type
12474               deduction fails.
12475
12476              applies.  */
12477           if (rval && !same_type_p (r, rval))
12478             return NULL_TREE;
12479
12480           rval = r;
12481         }
12482     }
12483
12484   return rval;
12485 }
12486
12487 /* Returns the level of DECL, which declares a template parameter.  */
12488
12489 static int
12490 template_decl_level (tree decl)
12491 {
12492   switch (TREE_CODE (decl))
12493     {
12494     case TYPE_DECL:
12495     case TEMPLATE_DECL:
12496       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
12497
12498     case PARM_DECL:
12499       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
12500
12501     default:
12502       gcc_unreachable ();
12503     }
12504   return 0;
12505 }
12506
12507 /* Decide whether ARG can be unified with PARM, considering only the
12508    cv-qualifiers of each type, given STRICT as documented for unify.
12509    Returns nonzero iff the unification is OK on that basis.  */
12510
12511 static int
12512 check_cv_quals_for_unify (int strict, tree arg, tree parm)
12513 {
12514   int arg_quals = cp_type_quals (arg);
12515   int parm_quals = cp_type_quals (parm);
12516
12517   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12518       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12519     {
12520       /*  Although a CVR qualifier is ignored when being applied to a
12521           substituted template parameter ([8.3.2]/1 for example), that
12522           does not apply during deduction [14.8.2.4]/1, (even though
12523           that is not explicitly mentioned, [14.8.2.4]/9 indicates
12524           this).  Except when we're allowing additional CV qualifiers
12525           at the outer level [14.8.2.1]/3,1st bullet.  */
12526       if ((TREE_CODE (arg) == REFERENCE_TYPE
12527            || TREE_CODE (arg) == FUNCTION_TYPE
12528            || TREE_CODE (arg) == METHOD_TYPE)
12529           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
12530         return 0;
12531
12532       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
12533           && (parm_quals & TYPE_QUAL_RESTRICT))
12534         return 0;
12535     }
12536
12537   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12538       && (arg_quals & parm_quals) != parm_quals)
12539     return 0;
12540
12541   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
12542       && (parm_quals & arg_quals) != arg_quals)
12543     return 0;
12544
12545   return 1;
12546 }
12547
12548 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
12549 void 
12550 template_parm_level_and_index (tree parm, int* level, int* index)
12551 {
12552   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12553       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12554       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12555     {
12556       *index = TEMPLATE_TYPE_IDX (parm);
12557       *level = TEMPLATE_TYPE_LEVEL (parm);
12558     }
12559   else
12560     {
12561       *index = TEMPLATE_PARM_IDX (parm);
12562       *level = TEMPLATE_PARM_LEVEL (parm);
12563     }
12564 }
12565
12566 /* Unifies the remaining arguments in PACKED_ARGS with the pack
12567    expansion at the end of PACKED_PARMS. Returns 0 if the type
12568    deduction succeeds, 1 otherwise. STRICT is the same as in
12569    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
12570    call argument list. We'll need to adjust the arguments to make them
12571    types. SUBR tells us if this is from a recursive call to
12572    type_unification_real.  */
12573 int
12574 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
12575                       tree packed_args, int strict, bool call_args_p,
12576                       bool subr)
12577 {
12578   tree parm 
12579     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
12580   tree pattern = PACK_EXPANSION_PATTERN (parm);
12581   tree pack, packs = NULL_TREE;
12582   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
12583   int len = TREE_VEC_LENGTH (packed_args);
12584
12585   /* Determine the parameter packs we will be deducing from the
12586      pattern, and record their current deductions.  */
12587   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
12588        pack; pack = TREE_CHAIN (pack))
12589     {
12590       tree parm_pack = TREE_VALUE (pack);
12591       int idx, level;
12592
12593       /* Determine the index and level of this parameter pack.  */
12594       template_parm_level_and_index (parm_pack, &level, &idx);
12595
12596       /* Keep track of the parameter packs and their corresponding
12597          argument packs.  */
12598       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
12599       TREE_TYPE (packs) = make_tree_vec (len - start);
12600     }
12601   
12602   /* Loop through all of the arguments that have not yet been
12603      unified and unify each with the pattern.  */
12604   for (i = start; i < len; i++)
12605     {
12606       tree parm = pattern;
12607
12608       /* For each parameter pack, clear out the deduced value so that
12609          we can deduce it again.  */
12610       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12611         {
12612           int idx, level;
12613           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12614
12615           TMPL_ARG (targs, level, idx) = NULL_TREE;
12616         }
12617
12618       /* Unify the pattern with the current argument.  */
12619       {
12620         tree arg = TREE_VEC_ELT (packed_args, i);
12621         tree arg_expr = NULL_TREE;
12622         int arg_strict = strict;
12623         bool skip_arg_p = false;
12624
12625         if (call_args_p)
12626           {
12627             int sub_strict;
12628
12629             /* This mirrors what we do in type_unification_real.  */
12630             switch (strict)
12631               {
12632               case DEDUCE_CALL:
12633                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
12634                               | UNIFY_ALLOW_MORE_CV_QUAL
12635                               | UNIFY_ALLOW_DERIVED);
12636                 break;
12637                 
12638               case DEDUCE_CONV:
12639                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12640                 break;
12641                 
12642               case DEDUCE_EXACT:
12643                 sub_strict = UNIFY_ALLOW_NONE;
12644                 break;
12645                 
12646               default:
12647                 gcc_unreachable ();
12648               }
12649
12650             if (!TYPE_P (arg))
12651               {
12652                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12653                 if (type_unknown_p (arg))
12654                   {
12655                     /* [temp.deduct.type] A template-argument can be
12656                        deduced from a pointer to function or pointer
12657                        to member function argument if the set of
12658                        overloaded functions does not contain function
12659                        templates and at most one of a set of
12660                        overloaded functions provides a unique
12661                        match.  */
12662
12663                     if (resolve_overloaded_unification
12664                         (tparms, targs, parm, arg, strict, sub_strict)
12665                         != 0)
12666                       return 1;
12667                     skip_arg_p = true;
12668                   }
12669
12670                 if (!skip_arg_p)
12671                   {
12672                     arg_expr = arg;
12673                     arg = unlowered_expr_type (arg);
12674                     if (arg == error_mark_node)
12675                       return 1;
12676                   }
12677               }
12678       
12679             arg_strict = sub_strict;
12680
12681             if (!subr)
12682               arg_strict |= 
12683                 maybe_adjust_types_for_deduction (strict, &parm, &arg, 
12684                                                   arg_expr);
12685           }
12686
12687         if (!skip_arg_p)
12688           {
12689             if (unify (tparms, targs, parm, arg, arg_strict))
12690               return 1;
12691           }
12692       }
12693
12694       /* For each parameter pack, collect the deduced value.  */
12695       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12696         {
12697           int idx, level;
12698           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12699
12700           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
12701             TMPL_ARG (targs, level, idx);
12702         }
12703     }
12704
12705   /* Verify that the results of unification with the parameter packs
12706      produce results consistent with what we've seen before, and make
12707      the deduced argument packs available.  */
12708   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12709     {
12710       tree old_pack = TREE_VALUE (pack);
12711       tree new_args = TREE_TYPE (pack);
12712       int i, len = TREE_VEC_LENGTH (new_args);
12713       bool nondeduced_p = false;
12714
12715       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
12716          actually deduce anything.  */
12717       for (i = 0; i < len && !nondeduced_p; ++i)
12718         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
12719           nondeduced_p = true;
12720       if (nondeduced_p)
12721         continue;
12722
12723       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
12724         {
12725           /* Prepend the explicit arguments onto NEW_ARGS.  */
12726           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12727           tree old_args = new_args;
12728           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
12729           int len = explicit_len + TREE_VEC_LENGTH (old_args);
12730
12731           /* Copy the explicit arguments.  */
12732           new_args = make_tree_vec (len);
12733           for (i = 0; i < explicit_len; i++)
12734             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
12735
12736           /* Copy the deduced arguments.  */
12737           for (; i < len; i++)
12738             TREE_VEC_ELT (new_args, i) =
12739               TREE_VEC_ELT (old_args, i - explicit_len);
12740         }
12741
12742       if (!old_pack)
12743         {
12744           tree result;
12745           int idx, level;
12746           
12747           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12748
12749           /* Build the deduced *_ARGUMENT_PACK.  */
12750           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
12751             {
12752               result = make_node (NONTYPE_ARGUMENT_PACK);
12753               TREE_TYPE (result) = 
12754                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
12755               TREE_CONSTANT (result) = 1;
12756             }
12757           else
12758             result = make_node (TYPE_ARGUMENT_PACK);
12759
12760           SET_ARGUMENT_PACK_ARGS (result, new_args);
12761
12762           /* Note the deduced argument packs for this parameter
12763              pack.  */
12764           TMPL_ARG (targs, level, idx) = result;
12765         }
12766       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
12767                && (ARGUMENT_PACK_ARGS (old_pack) 
12768                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
12769         {
12770           /* We only had the explicitly-provided arguments before, but
12771              now we have a complete set of arguments.  */
12772           int idx, level;
12773           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12774           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12775
12776           /* Keep the original deduced argument pack.  */
12777           TMPL_ARG (targs, level, idx) = old_pack;
12778
12779           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
12780           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
12781           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
12782         }
12783       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
12784                                     new_args))
12785         /* Inconsistent unification of this parameter pack.  */
12786         return 1;
12787       else
12788         {
12789           int idx, level;
12790           
12791           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12792
12793           /* Keep the original deduced argument pack.  */
12794           TMPL_ARG (targs, level, idx) = old_pack;
12795         }
12796     }
12797
12798   return 0;
12799 }
12800
12801 /* Deduce the value of template parameters.  TPARMS is the (innermost)
12802    set of template parameters to a template.  TARGS is the bindings
12803    for those template parameters, as determined thus far; TARGS may
12804    include template arguments for outer levels of template parameters
12805    as well.  PARM is a parameter to a template function, or a
12806    subcomponent of that parameter; ARG is the corresponding argument.
12807    This function attempts to match PARM with ARG in a manner
12808    consistent with the existing assignments in TARGS.  If more values
12809    are deduced, then TARGS is updated.
12810
12811    Returns 0 if the type deduction succeeds, 1 otherwise.  The
12812    parameter STRICT is a bitwise or of the following flags:
12813
12814      UNIFY_ALLOW_NONE:
12815        Require an exact match between PARM and ARG.
12816      UNIFY_ALLOW_MORE_CV_QUAL:
12817        Allow the deduced ARG to be more cv-qualified (by qualification
12818        conversion) than ARG.
12819      UNIFY_ALLOW_LESS_CV_QUAL:
12820        Allow the deduced ARG to be less cv-qualified than ARG.
12821      UNIFY_ALLOW_DERIVED:
12822        Allow the deduced ARG to be a template base class of ARG,
12823        or a pointer to a template base class of the type pointed to by
12824        ARG.
12825      UNIFY_ALLOW_INTEGER:
12826        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
12827        case for more information.
12828      UNIFY_ALLOW_OUTER_LEVEL:
12829        This is the outermost level of a deduction. Used to determine validity
12830        of qualification conversions. A valid qualification conversion must
12831        have const qualified pointers leading up to the inner type which
12832        requires additional CV quals, except at the outer level, where const
12833        is not required [conv.qual]. It would be normal to set this flag in
12834        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
12835      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
12836        This is the outermost level of a deduction, and PARM can be more CV
12837        qualified at this point.
12838      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
12839        This is the outermost level of a deduction, and PARM can be less CV
12840        qualified at this point.  */
12841
12842 static int
12843 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
12844 {
12845   int idx;
12846   tree targ;
12847   tree tparm;
12848   int strict_in = strict;
12849
12850   /* I don't think this will do the right thing with respect to types.
12851      But the only case I've seen it in so far has been array bounds, where
12852      signedness is the only information lost, and I think that will be
12853      okay.  */
12854   while (TREE_CODE (parm) == NOP_EXPR)
12855     parm = TREE_OPERAND (parm, 0);
12856
12857   if (arg == error_mark_node)
12858     return 1;
12859   if (arg == unknown_type_node)
12860     /* We can't deduce anything from this, but we might get all the
12861        template args from other function args.  */
12862     return 0;
12863
12864   /* If PARM uses template parameters, then we can't bail out here,
12865      even if ARG == PARM, since we won't record unifications for the
12866      template parameters.  We might need them if we're trying to
12867      figure out which of two things is more specialized.  */
12868   if (arg == parm && !uses_template_parms (parm))
12869     return 0;
12870
12871   /* Immediately reject some pairs that won't unify because of
12872      cv-qualification mismatches.  */
12873   if (TREE_CODE (arg) == TREE_CODE (parm)
12874       && TYPE_P (arg)
12875       /* It is the elements of the array which hold the cv quals of an array
12876          type, and the elements might be template type parms. We'll check
12877          when we recurse.  */
12878       && TREE_CODE (arg) != ARRAY_TYPE
12879       /* We check the cv-qualifiers when unifying with template type
12880          parameters below.  We want to allow ARG `const T' to unify with
12881          PARM `T' for example, when computing which of two templates
12882          is more specialized, for example.  */
12883       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
12884       && !check_cv_quals_for_unify (strict_in, arg, parm))
12885     return 1;
12886
12887   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
12888       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
12889     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
12890   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
12891   strict &= ~UNIFY_ALLOW_DERIVED;
12892   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12893   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
12894
12895   switch (TREE_CODE (parm))
12896     {
12897     case TYPENAME_TYPE:
12898     case SCOPE_REF:
12899     case UNBOUND_CLASS_TEMPLATE:
12900       /* In a type which contains a nested-name-specifier, template
12901          argument values cannot be deduced for template parameters used
12902          within the nested-name-specifier.  */
12903       return 0;
12904
12905     case TEMPLATE_TYPE_PARM:
12906     case TEMPLATE_TEMPLATE_PARM:
12907     case BOUND_TEMPLATE_TEMPLATE_PARM:
12908       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
12909       if (tparm == error_mark_node)
12910         return 1;
12911
12912       if (TEMPLATE_TYPE_LEVEL (parm)
12913           != template_decl_level (tparm))
12914         /* The PARM is not one we're trying to unify.  Just check
12915            to see if it matches ARG.  */
12916         return (TREE_CODE (arg) == TREE_CODE (parm)
12917                 && same_type_p (parm, arg)) ? 0 : 1;
12918       idx = TEMPLATE_TYPE_IDX (parm);
12919       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
12920       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
12921
12922       /* Check for mixed types and values.  */
12923       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12924            && TREE_CODE (tparm) != TYPE_DECL)
12925           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12926               && TREE_CODE (tparm) != TEMPLATE_DECL))
12927         return 1;
12928
12929       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12930         {
12931           /* ARG must be constructed from a template class or a template
12932              template parameter.  */
12933           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
12934               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
12935             return 1;
12936
12937           {
12938             tree parmvec = TYPE_TI_ARGS (parm);
12939             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
12940             tree parm_parms 
12941               = DECL_INNERMOST_TEMPLATE_PARMS
12942                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
12943             int i, len;
12944             int parm_variadic_p = 0;
12945
12946             /* The resolution to DR150 makes clear that default
12947                arguments for an N-argument may not be used to bind T
12948                to a template template parameter with fewer than N
12949                parameters.  It is not safe to permit the binding of
12950                default arguments as an extension, as that may change
12951                the meaning of a conforming program.  Consider:
12952
12953                   struct Dense { static const unsigned int dim = 1; };
12954
12955                   template <template <typename> class View,
12956                             typename Block>
12957                   void operator+(float, View<Block> const&);
12958
12959                   template <typename Block,
12960                             unsigned int Dim = Block::dim>
12961                   struct Lvalue_proxy { operator float() const; };
12962
12963                   void
12964                   test_1d (void) {
12965                     Lvalue_proxy<Dense> p;
12966                     float b;
12967                     b + p;
12968                   }
12969
12970               Here, if Lvalue_proxy is permitted to bind to View, then
12971               the global operator+ will be used; if they are not, the
12972               Lvalue_proxy will be converted to float.  */
12973             if (coerce_template_parms (parm_parms,
12974                                        argvec,
12975                                        TYPE_TI_TEMPLATE (parm),
12976                                        tf_none,
12977                                        /*require_all_args=*/true,
12978                                        /*use_default_args=*/false)
12979                 == error_mark_node)
12980               return 1;
12981
12982             /* Deduce arguments T, i from TT<T> or TT<i>.
12983                We check each element of PARMVEC and ARGVEC individually
12984                rather than the whole TREE_VEC since they can have
12985                different number of elements.  */
12986
12987             parmvec = expand_template_argument_pack (parmvec);
12988             argvec = expand_template_argument_pack (argvec);
12989
12990             len = TREE_VEC_LENGTH (parmvec);
12991
12992             /* Check if the parameters end in a pack, making them
12993                variadic.  */
12994             if (len > 0
12995                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
12996               parm_variadic_p = 1;
12997             
12998             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
12999               return 1;
13000
13001              for (i = 0; i < len - parm_variadic_p; ++i)
13002               {
13003                 if (unify (tparms, targs,
13004                            TREE_VEC_ELT (parmvec, i),
13005                            TREE_VEC_ELT (argvec, i),
13006                            UNIFY_ALLOW_NONE))
13007                   return 1;
13008               }
13009
13010             if (parm_variadic_p
13011                 && unify_pack_expansion (tparms, targs,
13012                                          parmvec, argvec,
13013                                          UNIFY_ALLOW_NONE,
13014                                          /*call_args_p=*/false,
13015                                          /*subr=*/false))
13016               return 1;
13017           }
13018           arg = TYPE_TI_TEMPLATE (arg);
13019
13020           /* Fall through to deduce template name.  */
13021         }
13022
13023       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13024           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13025         {
13026           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13027
13028           /* Simple cases: Value already set, does match or doesn't.  */
13029           if (targ != NULL_TREE && template_args_equal (targ, arg))
13030             return 0;
13031           else if (targ)
13032             return 1;
13033         }
13034       else
13035         {
13036           /* If PARM is `const T' and ARG is only `int', we don't have
13037              a match unless we are allowing additional qualification.
13038              If ARG is `const int' and PARM is just `T' that's OK;
13039              that binds `const int' to `T'.  */
13040           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13041                                          arg, parm))
13042             return 1;
13043
13044           /* Consider the case where ARG is `const volatile int' and
13045              PARM is `const T'.  Then, T should be `volatile int'.  */
13046           arg = cp_build_qualified_type_real
13047             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13048           if (arg == error_mark_node)
13049             return 1;
13050
13051           /* Simple cases: Value already set, does match or doesn't.  */
13052           if (targ != NULL_TREE && same_type_p (targ, arg))
13053             return 0;
13054           else if (targ)
13055             return 1;
13056
13057           /* Make sure that ARG is not a variable-sized array.  (Note
13058              that were talking about variable-sized arrays (like
13059              `int[n]'), rather than arrays of unknown size (like
13060              `int[]').)  We'll get very confused by such a type since
13061              the bound of the array will not be computable in an
13062              instantiation.  Besides, such types are not allowed in
13063              ISO C++, so we can do as we please here.  */
13064           if (variably_modified_type_p (arg, NULL_TREE))
13065             return 1;
13066         }
13067
13068       /* If ARG is a parameter pack or an expansion, we cannot unify
13069          against it unless PARM is also a parameter pack.  */
13070       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13071           && !template_parameter_pack_p (parm))
13072         return 1;
13073
13074       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13075       return 0;
13076
13077     case TEMPLATE_PARM_INDEX:
13078       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13079       if (tparm == error_mark_node)
13080         return 1;
13081
13082       if (TEMPLATE_PARM_LEVEL (parm)
13083           != template_decl_level (tparm))
13084         /* The PARM is not one we're trying to unify.  Just check
13085            to see if it matches ARG.  */
13086         return !(TREE_CODE (arg) == TREE_CODE (parm)
13087                  && cp_tree_equal (parm, arg));
13088
13089       idx = TEMPLATE_PARM_IDX (parm);
13090       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13091
13092       if (targ)
13093         return !cp_tree_equal (targ, arg);
13094
13095       /* [temp.deduct.type] If, in the declaration of a function template
13096          with a non-type template-parameter, the non-type
13097          template-parameter is used in an expression in the function
13098          parameter-list and, if the corresponding template-argument is
13099          deduced, the template-argument type shall match the type of the
13100          template-parameter exactly, except that a template-argument
13101          deduced from an array bound may be of any integral type.
13102          The non-type parameter might use already deduced type parameters.  */
13103       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13104       if (!TREE_TYPE (arg))
13105         /* Template-parameter dependent expression.  Just accept it for now.
13106            It will later be processed in convert_template_argument.  */
13107         ;
13108       else if (same_type_p (TREE_TYPE (arg), tparm))
13109         /* OK */;
13110       else if ((strict & UNIFY_ALLOW_INTEGER)
13111                && (TREE_CODE (tparm) == INTEGER_TYPE
13112                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13113         /* Convert the ARG to the type of PARM; the deduced non-type
13114            template argument must exactly match the types of the
13115            corresponding parameter.  */
13116         arg = fold (build_nop (TREE_TYPE (parm), arg));
13117       else if (uses_template_parms (tparm))
13118         /* We haven't deduced the type of this parameter yet.  Try again
13119            later.  */
13120         return 0;
13121       else
13122         return 1;
13123
13124       /* If ARG is a parameter pack or an expansion, we cannot unify
13125          against it unless PARM is also a parameter pack.  */
13126       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13127           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13128         return 1;
13129
13130       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13131       return 0;
13132
13133     case PTRMEM_CST:
13134      {
13135         /* A pointer-to-member constant can be unified only with
13136          another constant.  */
13137       if (TREE_CODE (arg) != PTRMEM_CST)
13138         return 1;
13139
13140       /* Just unify the class member. It would be useless (and possibly
13141          wrong, depending on the strict flags) to unify also
13142          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13143          arg refer to the same variable, even if through different
13144          classes. For instance:
13145
13146          struct A { int x; };
13147          struct B : A { };
13148
13149          Unification of &A::x and &B::x must succeed.  */
13150       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13151                     PTRMEM_CST_MEMBER (arg), strict);
13152      }
13153
13154     case POINTER_TYPE:
13155       {
13156         if (TREE_CODE (arg) != POINTER_TYPE)
13157           return 1;
13158
13159         /* [temp.deduct.call]
13160
13161            A can be another pointer or pointer to member type that can
13162            be converted to the deduced A via a qualification
13163            conversion (_conv.qual_).
13164
13165            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13166            This will allow for additional cv-qualification of the
13167            pointed-to types if appropriate.  */
13168
13169         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13170           /* The derived-to-base conversion only persists through one
13171              level of pointers.  */
13172           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13173
13174         return unify (tparms, targs, TREE_TYPE (parm),
13175                       TREE_TYPE (arg), strict);
13176       }
13177
13178     case REFERENCE_TYPE:
13179       if (TREE_CODE (arg) != REFERENCE_TYPE)
13180         return 1;
13181       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13182                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13183
13184     case ARRAY_TYPE:
13185       if (TREE_CODE (arg) != ARRAY_TYPE)
13186         return 1;
13187       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13188           != (TYPE_DOMAIN (arg) == NULL_TREE))
13189         return 1;
13190       if (TYPE_DOMAIN (parm) != NULL_TREE)
13191         {
13192           tree parm_max;
13193           tree arg_max;
13194           bool parm_cst;
13195           bool arg_cst;
13196
13197           /* Our representation of array types uses "N - 1" as the
13198              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13199              not an integer constant.  We cannot unify arbitrarily
13200              complex expressions, so we eliminate the MINUS_EXPRs
13201              here.  */
13202           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13203           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13204           if (!parm_cst)
13205             {
13206               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13207               parm_max = TREE_OPERAND (parm_max, 0);
13208             }
13209           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13210           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13211           if (!arg_cst)
13212             {
13213               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13214                  trying to unify the type of a variable with the type
13215                  of a template parameter.  For example:
13216
13217                    template <unsigned int N>
13218                    void f (char (&) [N]);
13219                    int g(); 
13220                    void h(int i) {
13221                      char a[g(i)];
13222                      f(a); 
13223                    }
13224
13225                 Here, the type of the ARG will be "int [g(i)]", and
13226                 may be a SAVE_EXPR, etc.  */
13227               if (TREE_CODE (arg_max) != MINUS_EXPR)
13228                 return 1;
13229               arg_max = TREE_OPERAND (arg_max, 0);
13230             }
13231
13232           /* If only one of the bounds used a MINUS_EXPR, compensate
13233              by adding one to the other bound.  */
13234           if (parm_cst && !arg_cst)
13235             parm_max = fold_build2 (PLUS_EXPR,
13236                                     integer_type_node,
13237                                     parm_max,
13238                                     integer_one_node);
13239           else if (arg_cst && !parm_cst)
13240             arg_max = fold_build2 (PLUS_EXPR,
13241                                    integer_type_node,
13242                                    arg_max,
13243                                    integer_one_node);
13244
13245           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13246             return 1;
13247         }
13248       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13249                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13250
13251     case REAL_TYPE:
13252     case COMPLEX_TYPE:
13253     case VECTOR_TYPE:
13254     case INTEGER_TYPE:
13255     case BOOLEAN_TYPE:
13256     case ENUMERAL_TYPE:
13257     case VOID_TYPE:
13258       if (TREE_CODE (arg) != TREE_CODE (parm))
13259         return 1;
13260
13261       /* We have already checked cv-qualification at the top of the
13262          function.  */
13263       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13264         return 1;
13265
13266       /* As far as unification is concerned, this wins.  Later checks
13267          will invalidate it if necessary.  */
13268       return 0;
13269
13270       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13271       /* Type INTEGER_CST can come from ordinary constant template args.  */
13272     case INTEGER_CST:
13273       while (TREE_CODE (arg) == NOP_EXPR)
13274         arg = TREE_OPERAND (arg, 0);
13275
13276       if (TREE_CODE (arg) != INTEGER_CST)
13277         return 1;
13278       return !tree_int_cst_equal (parm, arg);
13279
13280     case TREE_VEC:
13281       {
13282         int i;
13283         if (TREE_CODE (arg) != TREE_VEC)
13284           return 1;
13285         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13286           return 1;
13287         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13288           if (unify (tparms, targs,
13289                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13290                      UNIFY_ALLOW_NONE))
13291             return 1;
13292         return 0;
13293       }
13294
13295     case RECORD_TYPE:
13296     case UNION_TYPE:
13297       if (TREE_CODE (arg) != TREE_CODE (parm))
13298         return 1;
13299
13300       if (TYPE_PTRMEMFUNC_P (parm))
13301         {
13302           if (!TYPE_PTRMEMFUNC_P (arg))
13303             return 1;
13304
13305           return unify (tparms, targs,
13306                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13307                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13308                         strict);
13309         }
13310
13311       if (CLASSTYPE_TEMPLATE_INFO (parm))
13312         {
13313           tree t = NULL_TREE;
13314
13315           if (strict_in & UNIFY_ALLOW_DERIVED)
13316             {
13317               /* First, we try to unify the PARM and ARG directly.  */
13318               t = try_class_unification (tparms, targs,
13319                                          parm, arg);
13320
13321               if (!t)
13322                 {
13323                   /* Fallback to the special case allowed in
13324                      [temp.deduct.call]:
13325
13326                        If P is a class, and P has the form
13327                        template-id, then A can be a derived class of
13328                        the deduced A.  Likewise, if P is a pointer to
13329                        a class of the form template-id, A can be a
13330                        pointer to a derived class pointed to by the
13331                        deduced A.  */
13332                   t = get_template_base (tparms, targs, parm, arg);
13333
13334                   if (!t)
13335                     return 1;
13336                 }
13337             }
13338           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13339                    && (CLASSTYPE_TI_TEMPLATE (parm)
13340                        == CLASSTYPE_TI_TEMPLATE (arg)))
13341             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13342                Then, we should unify `int' and `U'.  */
13343             t = arg;
13344           else
13345             /* There's no chance of unification succeeding.  */
13346             return 1;
13347
13348           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13349                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13350         }
13351       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13352         return 1;
13353       return 0;
13354
13355     case METHOD_TYPE:
13356     case FUNCTION_TYPE:
13357       if (TREE_CODE (arg) != TREE_CODE (parm))
13358         return 1;
13359
13360       /* CV qualifications for methods can never be deduced, they must
13361          match exactly.  We need to check them explicitly here,
13362          because type_unification_real treats them as any other
13363          cvqualified parameter.  */
13364       if (TREE_CODE (parm) == METHOD_TYPE
13365           && (!check_cv_quals_for_unify
13366               (UNIFY_ALLOW_NONE,
13367                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
13368                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
13369         return 1;
13370
13371       if (unify (tparms, targs, TREE_TYPE (parm),
13372                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
13373         return 1;
13374       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
13375                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
13376                                     LOOKUP_NORMAL);
13377
13378     case OFFSET_TYPE:
13379       /* Unify a pointer to member with a pointer to member function, which
13380          deduces the type of the member as a function type. */
13381       if (TYPE_PTRMEMFUNC_P (arg))
13382         {
13383           tree method_type;
13384           tree fntype;
13385           cp_cv_quals cv_quals;
13386
13387           /* Check top-level cv qualifiers */
13388           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
13389             return 1;
13390
13391           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13392                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
13393             return 1;
13394
13395           /* Determine the type of the function we are unifying against. */
13396           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
13397           fntype =
13398             build_function_type (TREE_TYPE (method_type),
13399                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
13400
13401           /* Extract the cv-qualifiers of the member function from the
13402              implicit object parameter and place them on the function
13403              type to be restored later. */
13404           cv_quals =
13405             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
13406           fntype = build_qualified_type (fntype, cv_quals);
13407           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
13408         }
13409
13410       if (TREE_CODE (arg) != OFFSET_TYPE)
13411         return 1;
13412       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13413                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
13414         return 1;
13415       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13416                     strict);
13417
13418     case CONST_DECL:
13419       if (DECL_TEMPLATE_PARM_P (parm))
13420         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
13421       if (arg != integral_constant_value (parm))
13422         return 1;
13423       return 0;
13424
13425     case FIELD_DECL:
13426     case TEMPLATE_DECL:
13427       /* Matched cases are handled by the ARG == PARM test above.  */
13428       return 1;
13429
13430     case TYPE_ARGUMENT_PACK:
13431     case NONTYPE_ARGUMENT_PACK:
13432       {
13433         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
13434         tree packed_args = ARGUMENT_PACK_ARGS (arg);
13435         int i, len = TREE_VEC_LENGTH (packed_parms);
13436         int argslen = TREE_VEC_LENGTH (packed_args);
13437         int parm_variadic_p = 0;
13438
13439         for (i = 0; i < len; ++i)
13440           {
13441             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
13442               {
13443                 if (i == len - 1)
13444                   /* We can unify against something with a trailing
13445                      parameter pack.  */
13446                   parm_variadic_p = 1;
13447                 else
13448                   /* Since there is something following the pack
13449                      expansion, we cannot unify this template argument
13450                      list.  */
13451                   return 0;
13452               }
13453           }
13454           
13455
13456         /* If we don't have enough arguments to satisfy the parameters
13457            (not counting the pack expression at the end), or we have
13458            too many arguments for a parameter list that doesn't end in
13459            a pack expression, we can't unify.  */
13460         if (argslen < (len - parm_variadic_p)
13461             || (argslen > len && !parm_variadic_p))
13462           return 1;
13463
13464         /* Unify all of the parameters that precede the (optional)
13465            pack expression.  */
13466         for (i = 0; i < len - parm_variadic_p; ++i)
13467           {
13468             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
13469                        TREE_VEC_ELT (packed_args, i), strict))
13470               return 1;
13471           }
13472
13473         if (parm_variadic_p)
13474           return unify_pack_expansion (tparms, targs, 
13475                                        packed_parms, packed_args,
13476                                        strict, /*call_args_p=*/false,
13477                                        /*subr=*/false);
13478         return 0;
13479       }
13480
13481       break;
13482
13483     case TYPEOF_TYPE:
13484     case DECLTYPE_TYPE:
13485       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
13486          nodes.  */
13487       return 0;
13488
13489     case ERROR_MARK:
13490       /* Unification fails if we hit an error node.  */
13491       return 1;
13492
13493     default:
13494       gcc_assert (EXPR_P (parm));
13495
13496       /* We must be looking at an expression.  This can happen with
13497          something like:
13498
13499            template <int I>
13500            void foo(S<I>, S<I + 2>);
13501
13502          This is a "nondeduced context":
13503
13504            [deduct.type]
13505
13506            The nondeduced contexts are:
13507
13508            --A type that is a template-id in which one or more of
13509              the template-arguments is an expression that references
13510              a template-parameter.
13511
13512          In these cases, we assume deduction succeeded, but don't
13513          actually infer any unifications.  */
13514
13515       if (!uses_template_parms (parm)
13516           && !template_args_equal (parm, arg))
13517         return 1;
13518       else
13519         return 0;
13520     }
13521 }
13522 \f
13523 /* Note that DECL can be defined in this translation unit, if
13524    required.  */
13525
13526 static void
13527 mark_definable (tree decl)
13528 {
13529   tree clone;
13530   DECL_NOT_REALLY_EXTERN (decl) = 1;
13531   FOR_EACH_CLONE (clone, decl)
13532     DECL_NOT_REALLY_EXTERN (clone) = 1;
13533 }
13534
13535 /* Called if RESULT is explicitly instantiated, or is a member of an
13536    explicitly instantiated class.  */
13537
13538 void
13539 mark_decl_instantiated (tree result, int extern_p)
13540 {
13541   SET_DECL_EXPLICIT_INSTANTIATION (result);
13542
13543   /* If this entity has already been written out, it's too late to
13544      make any modifications.  */
13545   if (TREE_ASM_WRITTEN (result))
13546     return;
13547
13548   if (TREE_CODE (result) != FUNCTION_DECL)
13549     /* The TREE_PUBLIC flag for function declarations will have been
13550        set correctly by tsubst.  */
13551     TREE_PUBLIC (result) = 1;
13552
13553   /* This might have been set by an earlier implicit instantiation.  */
13554   DECL_COMDAT (result) = 0;
13555
13556   if (extern_p)
13557     DECL_NOT_REALLY_EXTERN (result) = 0;
13558   else
13559     {
13560       mark_definable (result);
13561       /* Always make artificials weak.  */
13562       if (DECL_ARTIFICIAL (result) && flag_weak)
13563         comdat_linkage (result);
13564       /* For WIN32 we also want to put explicit instantiations in
13565          linkonce sections.  */
13566       else if (TREE_PUBLIC (result))
13567         maybe_make_one_only (result);
13568     }
13569
13570   /* If EXTERN_P, then this function will not be emitted -- unless
13571      followed by an explicit instantiation, at which point its linkage
13572      will be adjusted.  If !EXTERN_P, then this function will be
13573      emitted here.  In neither circumstance do we want
13574      import_export_decl to adjust the linkage.  */
13575   DECL_INTERFACE_KNOWN (result) = 1;
13576 }
13577
13578 /* Given two function templates PAT1 and PAT2, return:
13579
13580    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
13581    -1 if PAT2 is more specialized than PAT1.
13582    0 if neither is more specialized.
13583
13584    LEN indicates the number of parameters we should consider
13585    (defaulted parameters should not be considered).
13586
13587    The 1998 std underspecified function template partial ordering, and
13588    DR214 addresses the issue.  We take pairs of arguments, one from
13589    each of the templates, and deduce them against each other.  One of
13590    the templates will be more specialized if all the *other*
13591    template's arguments deduce against its arguments and at least one
13592    of its arguments *does* *not* deduce against the other template's
13593    corresponding argument.  Deduction is done as for class templates.
13594    The arguments used in deduction have reference and top level cv
13595    qualifiers removed.  Iff both arguments were originally reference
13596    types *and* deduction succeeds in both directions, the template
13597    with the more cv-qualified argument wins for that pairing (if
13598    neither is more cv-qualified, they both are equal).  Unlike regular
13599    deduction, after all the arguments have been deduced in this way,
13600    we do *not* verify the deduced template argument values can be
13601    substituted into non-deduced contexts, nor do we have to verify
13602    that all template arguments have been deduced.  */
13603
13604 int
13605 more_specialized_fn (tree pat1, tree pat2, int len)
13606 {
13607   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
13608   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
13609   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
13610   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
13611   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
13612   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
13613   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
13614   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
13615   int better1 = 0;
13616   int better2 = 0;
13617
13618   /* Remove the this parameter from non-static member functions.  If
13619      one is a non-static member function and the other is not a static
13620      member function, remove the first parameter from that function
13621      also.  This situation occurs for operator functions where we
13622      locate both a member function (with this pointer) and non-member
13623      operator (with explicit first operand).  */
13624   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
13625     {
13626       len--; /* LEN is the number of significant arguments for DECL1 */
13627       args1 = TREE_CHAIN (args1);
13628       if (!DECL_STATIC_FUNCTION_P (decl2))
13629         args2 = TREE_CHAIN (args2);
13630     }
13631   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
13632     {
13633       args2 = TREE_CHAIN (args2);
13634       if (!DECL_STATIC_FUNCTION_P (decl1))
13635         {
13636           len--;
13637           args1 = TREE_CHAIN (args1);
13638         }
13639     }
13640
13641   /* If only one is a conversion operator, they are unordered.  */
13642   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
13643     return 0;
13644
13645   /* Consider the return type for a conversion function */
13646   if (DECL_CONV_FN_P (decl1))
13647     {
13648       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
13649       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
13650       len++;
13651     }
13652
13653   processing_template_decl++;
13654
13655   while (len--
13656          /* Stop when an ellipsis is seen.  */
13657          && args1 != NULL_TREE && args2 != NULL_TREE)
13658     {
13659       tree arg1 = TREE_VALUE (args1);
13660       tree arg2 = TREE_VALUE (args2);
13661       int deduce1, deduce2;
13662       int quals1 = -1;
13663       int quals2 = -1;
13664
13665       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13666           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13667         {
13668           /* When both arguments are pack expansions, we need only
13669              unify the patterns themselves.  */
13670           arg1 = PACK_EXPANSION_PATTERN (arg1);
13671           arg2 = PACK_EXPANSION_PATTERN (arg2);
13672
13673           /* This is the last comparison we need to do.  */
13674           len = 0;
13675         }
13676
13677       if (TREE_CODE (arg1) == REFERENCE_TYPE)
13678         {
13679           arg1 = TREE_TYPE (arg1);
13680           quals1 = cp_type_quals (arg1);
13681         }
13682
13683       if (TREE_CODE (arg2) == REFERENCE_TYPE)
13684         {
13685           arg2 = TREE_TYPE (arg2);
13686           quals2 = cp_type_quals (arg2);
13687         }
13688
13689       if ((quals1 < 0) != (quals2 < 0))
13690         {
13691           /* Only of the args is a reference, see if we should apply
13692              array/function pointer decay to it.  This is not part of
13693              DR214, but is, IMHO, consistent with the deduction rules
13694              for the function call itself, and with our earlier
13695              implementation of the underspecified partial ordering
13696              rules.  (nathan).  */
13697           if (quals1 >= 0)
13698             {
13699               switch (TREE_CODE (arg1))
13700                 {
13701                 case ARRAY_TYPE:
13702                   arg1 = TREE_TYPE (arg1);
13703                   /* FALLTHROUGH. */
13704                 case FUNCTION_TYPE:
13705                   arg1 = build_pointer_type (arg1);
13706                   break;
13707
13708                 default:
13709                   break;
13710                 }
13711             }
13712           else
13713             {
13714               switch (TREE_CODE (arg2))
13715                 {
13716                 case ARRAY_TYPE:
13717                   arg2 = TREE_TYPE (arg2);
13718                   /* FALLTHROUGH. */
13719                 case FUNCTION_TYPE:
13720                   arg2 = build_pointer_type (arg2);
13721                   break;
13722
13723                 default:
13724                   break;
13725                 }
13726             }
13727         }
13728
13729       arg1 = TYPE_MAIN_VARIANT (arg1);
13730       arg2 = TYPE_MAIN_VARIANT (arg2);
13731
13732       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
13733         {
13734           int i, len2 = list_length (args2);
13735           tree parmvec = make_tree_vec (1);
13736           tree argvec = make_tree_vec (len2);
13737           tree ta = args2;
13738
13739           /* Setup the parameter vector, which contains only ARG1.  */
13740           TREE_VEC_ELT (parmvec, 0) = arg1;
13741
13742           /* Setup the argument vector, which contains the remaining
13743              arguments.  */
13744           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
13745             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13746
13747           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
13748                                            argvec, UNIFY_ALLOW_NONE, 
13749                                            /*call_args_p=*/false, 
13750                                            /*subr=*/0);
13751
13752           /* We cannot deduce in the other direction, because ARG1 is
13753              a pack expansion but ARG2 is not.  */
13754           deduce2 = 0;
13755         }
13756       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13757         {
13758           int i, len1 = list_length (args1);
13759           tree parmvec = make_tree_vec (1);
13760           tree argvec = make_tree_vec (len1);
13761           tree ta = args1;
13762
13763           /* Setup the parameter vector, which contains only ARG1.  */
13764           TREE_VEC_ELT (parmvec, 0) = arg2;
13765
13766           /* Setup the argument vector, which contains the remaining
13767              arguments.  */
13768           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
13769             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13770
13771           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
13772                                            argvec, UNIFY_ALLOW_NONE, 
13773                                            /*call_args_p=*/false, 
13774                                            /*subr=*/0);
13775
13776           /* We cannot deduce in the other direction, because ARG2 is
13777              a pack expansion but ARG1 is not.*/
13778           deduce1 = 0;
13779         }
13780
13781       else
13782         {
13783           /* The normal case, where neither argument is a pack
13784              expansion.  */
13785           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
13786           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
13787         }
13788
13789       if (!deduce1)
13790         better2 = -1;
13791       if (!deduce2)
13792         better1 = -1;
13793       if (better1 < 0 && better2 < 0)
13794         /* We've failed to deduce something in either direction.
13795            These must be unordered.  */
13796         break;
13797
13798       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
13799         {
13800           /* Deduces in both directions, see if quals can
13801              disambiguate.  Pretend the worse one failed to deduce. */
13802           if ((quals1 & quals2) == quals2)
13803             deduce1 = 0;
13804           if ((quals1 & quals2) == quals1)
13805             deduce2 = 0;
13806         }
13807       if (deduce1 && !deduce2 && !better2)
13808         better2 = 1;
13809       if (deduce2 && !deduce1 && !better1)
13810         better1 = 1;
13811
13812       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13813           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13814         /* We have already processed all of the arguments in our
13815            handing of the pack expansion type.  */
13816         len = 0;
13817
13818       args1 = TREE_CHAIN (args1);
13819       args2 = TREE_CHAIN (args2);
13820     }
13821
13822   processing_template_decl--;
13823
13824   /* All things being equal, if the next argument is a pack expansion
13825      for one function but not for the other, prefer the
13826      non-variadic function.  */
13827   if ((better1 > 0) - (better2 > 0) == 0
13828       && args1 && TREE_VALUE (args1)
13829       && args2 && TREE_VALUE (args2))
13830     {
13831       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
13832         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
13833       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
13834         return 1;
13835     }
13836
13837   return (better1 > 0) - (better2 > 0);
13838 }
13839
13840 /* Determine which of two partial specializations is more specialized.
13841
13842    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
13843    to the first partial specialization.  The TREE_VALUE is the
13844    innermost set of template parameters for the partial
13845    specialization.  PAT2 is similar, but for the second template.
13846
13847    Return 1 if the first partial specialization is more specialized;
13848    -1 if the second is more specialized; 0 if neither is more
13849    specialized.
13850
13851    See [temp.class.order] for information about determining which of
13852    two templates is more specialized.  */
13853
13854 static int
13855 more_specialized_class (tree pat1, tree pat2)
13856 {
13857   tree targs;
13858   tree tmpl1, tmpl2;
13859   int winner = 0;
13860   bool any_deductions = false;
13861
13862   tmpl1 = TREE_TYPE (pat1);
13863   tmpl2 = TREE_TYPE (pat2);
13864
13865   /* Just like what happens for functions, if we are ordering between
13866      different class template specializations, we may encounter dependent
13867      types in the arguments, and we need our dependency check functions
13868      to behave correctly.  */
13869   ++processing_template_decl;
13870   targs = get_class_bindings (TREE_VALUE (pat1),
13871                               CLASSTYPE_TI_ARGS (tmpl1),
13872                               CLASSTYPE_TI_ARGS (tmpl2));
13873   if (targs)
13874     {
13875       --winner;
13876       any_deductions = true;
13877     }
13878
13879   targs = get_class_bindings (TREE_VALUE (pat2),
13880                               CLASSTYPE_TI_ARGS (tmpl2),
13881                               CLASSTYPE_TI_ARGS (tmpl1));
13882   if (targs)
13883     {
13884       ++winner;
13885       any_deductions = true;
13886     }
13887   --processing_template_decl;
13888
13889   /* In the case of a tie where at least one of the class templates
13890      has a parameter pack at the end, the template with the most
13891      non-packed parameters wins.  */
13892   if (winner == 0
13893       && any_deductions
13894       && (template_args_variadic_p (TREE_PURPOSE (pat1))
13895           || template_args_variadic_p (TREE_PURPOSE (pat2))))
13896     {
13897       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
13898       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
13899       int len1 = TREE_VEC_LENGTH (args1);
13900       int len2 = TREE_VEC_LENGTH (args2);
13901
13902       /* We don't count the pack expansion at the end.  */
13903       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
13904         --len1;
13905       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
13906         --len2;
13907
13908       if (len1 > len2)
13909         return 1;
13910       else if (len1 < len2)
13911         return -1;
13912     }
13913
13914   return winner;
13915 }
13916
13917 /* Return the template arguments that will produce the function signature
13918    DECL from the function template FN, with the explicit template
13919    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
13920    also match.  Return NULL_TREE if no satisfactory arguments could be
13921    found.  */
13922
13923 static tree
13924 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
13925 {
13926   int ntparms = DECL_NTPARMS (fn);
13927   tree targs = make_tree_vec (ntparms);
13928   tree decl_type;
13929   tree decl_arg_types;
13930
13931   /* Substitute the explicit template arguments into the type of DECL.
13932      The call to fn_type_unification will handle substitution into the
13933      FN.  */
13934   decl_type = TREE_TYPE (decl);
13935   if (explicit_args && uses_template_parms (decl_type))
13936     {
13937       tree tmpl;
13938       tree converted_args;
13939
13940       if (DECL_TEMPLATE_INFO (decl))
13941         tmpl = DECL_TI_TEMPLATE (decl);
13942       else
13943         /* We can get here for some invalid specializations.  */
13944         return NULL_TREE;
13945
13946       converted_args
13947         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
13948                                  explicit_args, NULL_TREE,
13949                                  tf_none,
13950                                  /*require_all_args=*/false,
13951                                  /*use_default_args=*/false);
13952       if (converted_args == error_mark_node)
13953         return NULL_TREE;
13954
13955       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
13956       if (decl_type == error_mark_node)
13957         return NULL_TREE;
13958     }
13959
13960   /* Never do unification on the 'this' parameter.  */
13961   decl_arg_types = skip_artificial_parms_for (decl, 
13962                                               TYPE_ARG_TYPES (decl_type));
13963
13964   if (fn_type_unification (fn, explicit_args, targs,
13965                            decl_arg_types,
13966                            (check_rettype || DECL_CONV_FN_P (fn)
13967                             ? TREE_TYPE (decl_type) : NULL_TREE),
13968                            DEDUCE_EXACT, LOOKUP_NORMAL))
13969     return NULL_TREE;
13970
13971   return targs;
13972 }
13973
13974 /* Return the innermost template arguments that, when applied to a
13975    template specialization whose innermost template parameters are
13976    TPARMS, and whose specialization arguments are PARMS, yield the
13977    ARGS.
13978
13979    For example, suppose we have:
13980
13981      template <class T, class U> struct S {};
13982      template <class T> struct S<T*, int> {};
13983
13984    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
13985    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
13986    int}.  The resulting vector will be {double}, indicating that `T'
13987    is bound to `double'.  */
13988
13989 static tree
13990 get_class_bindings (tree tparms, tree spec_args, tree args)
13991 {
13992   int i, ntparms = TREE_VEC_LENGTH (tparms);
13993   tree deduced_args;
13994   tree innermost_deduced_args;
13995
13996   innermost_deduced_args = make_tree_vec (ntparms);
13997   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13998     {
13999       deduced_args = copy_node (args);
14000       SET_TMPL_ARGS_LEVEL (deduced_args,
14001                            TMPL_ARGS_DEPTH (deduced_args),
14002                            innermost_deduced_args);
14003     }
14004   else
14005     deduced_args = innermost_deduced_args;
14006
14007   if (unify (tparms, deduced_args,
14008              INNERMOST_TEMPLATE_ARGS (spec_args),
14009              INNERMOST_TEMPLATE_ARGS (args),
14010              UNIFY_ALLOW_NONE))
14011     return NULL_TREE;
14012
14013   for (i =  0; i < ntparms; ++i)
14014     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14015       return NULL_TREE;
14016
14017   /* Verify that nondeduced template arguments agree with the type
14018      obtained from argument deduction.
14019
14020      For example:
14021
14022        struct A { typedef int X; };
14023        template <class T, class U> struct C {};
14024        template <class T> struct C<T, typename T::X> {};
14025
14026      Then with the instantiation `C<A, int>', we can deduce that
14027      `T' is `A' but unify () does not check whether `typename T::X'
14028      is `int'.  */
14029   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14030   if (spec_args == error_mark_node
14031       /* We only need to check the innermost arguments; the other
14032          arguments will always agree.  */
14033       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14034                               INNERMOST_TEMPLATE_ARGS (args)))
14035     return NULL_TREE;
14036
14037   /* Now that we have bindings for all of the template arguments,
14038      ensure that the arguments deduced for the template template
14039      parameters have compatible template parameter lists.  See the use
14040      of template_template_parm_bindings_ok_p in fn_type_unification
14041      for more information.  */
14042   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14043     return NULL_TREE;
14044
14045   return deduced_args;
14046 }
14047
14048 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14049    Return the TREE_LIST node with the most specialized template, if
14050    any.  If there is no most specialized template, the error_mark_node
14051    is returned.
14052
14053    Note that this function does not look at, or modify, the
14054    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14055    returned is one of the elements of INSTANTIATIONS, callers may
14056    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14057    and retrieve it from the value returned.  */
14058
14059 tree
14060 most_specialized_instantiation (tree templates)
14061 {
14062   tree fn, champ;
14063
14064   ++processing_template_decl;
14065
14066   champ = templates;
14067   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14068     {
14069       int fate = 0;
14070
14071       if (get_bindings (TREE_VALUE (champ),
14072                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14073                         NULL_TREE, /*check_ret=*/false))
14074         fate--;
14075
14076       if (get_bindings (TREE_VALUE (fn),
14077                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14078                         NULL_TREE, /*check_ret=*/false))
14079         fate++;
14080
14081       if (fate == -1)
14082         champ = fn;
14083       else if (!fate)
14084         {
14085           /* Equally specialized, move to next function.  If there
14086              is no next function, nothing's most specialized.  */
14087           fn = TREE_CHAIN (fn);
14088           champ = fn;
14089           if (!fn)
14090             break;
14091         }
14092     }
14093
14094   if (champ)
14095     /* Now verify that champ is better than everything earlier in the
14096        instantiation list.  */
14097     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14098       if (get_bindings (TREE_VALUE (champ),
14099                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14100                         NULL_TREE, /*check_ret=*/false)
14101           || !get_bindings (TREE_VALUE (fn),
14102                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14103                             NULL_TREE, /*check_ret=*/false))
14104         {
14105           champ = NULL_TREE;
14106           break;
14107         }
14108
14109   processing_template_decl--;
14110
14111   if (!champ)
14112     return error_mark_node;
14113
14114   return champ;
14115 }
14116
14117 /* If DECL is a specialization of some template, return the most
14118    general such template.  Otherwise, returns NULL_TREE.
14119
14120    For example, given:
14121
14122      template <class T> struct S { template <class U> void f(U); };
14123
14124    if TMPL is `template <class U> void S<int>::f(U)' this will return
14125    the full template.  This function will not trace past partial
14126    specializations, however.  For example, given in addition:
14127
14128      template <class T> struct S<T*> { template <class U> void f(U); };
14129
14130    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14131    `template <class T> template <class U> S<T*>::f(U)'.  */
14132
14133 tree
14134 most_general_template (tree decl)
14135 {
14136   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14137      an immediate specialization.  */
14138   if (TREE_CODE (decl) == FUNCTION_DECL)
14139     {
14140       if (DECL_TEMPLATE_INFO (decl)) {
14141         decl = DECL_TI_TEMPLATE (decl);
14142
14143         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14144            template friend.  */
14145         if (TREE_CODE (decl) != TEMPLATE_DECL)
14146           return NULL_TREE;
14147       } else
14148         return NULL_TREE;
14149     }
14150
14151   /* Look for more and more general templates.  */
14152   while (DECL_TEMPLATE_INFO (decl))
14153     {
14154       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14155          (See cp-tree.h for details.)  */
14156       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14157         break;
14158
14159       if (CLASS_TYPE_P (TREE_TYPE (decl))
14160           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14161         break;
14162
14163       /* Stop if we run into an explicitly specialized class template.  */
14164       if (!DECL_NAMESPACE_SCOPE_P (decl)
14165           && DECL_CONTEXT (decl)
14166           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14167         break;
14168
14169       decl = DECL_TI_TEMPLATE (decl);
14170     }
14171
14172   return decl;
14173 }
14174
14175 /* Return the most specialized of the class template partial
14176    specializations of TMPL which can produce TYPE, a specialization of
14177    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14178    a _TYPE node corresponding to the partial specialization, while the
14179    TREE_PURPOSE is the set of template arguments that must be
14180    substituted into the TREE_TYPE in order to generate TYPE.
14181
14182    If the choice of partial specialization is ambiguous, a diagnostic
14183    is issued, and the error_mark_node is returned.  If there are no
14184    partial specializations of TMPL matching TYPE, then NULL_TREE is
14185    returned.  */
14186
14187 static tree
14188 most_specialized_class (tree type, tree tmpl)
14189 {
14190   tree list = NULL_TREE;
14191   tree t;
14192   tree champ;
14193   int fate;
14194   bool ambiguous_p;
14195   tree args;
14196   tree outer_args = NULL_TREE;
14197
14198   tmpl = most_general_template (tmpl);
14199   args = CLASSTYPE_TI_ARGS (type);
14200
14201   /* For determining which partial specialization to use, only the
14202      innermost args are interesting.  */
14203   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14204     {
14205       outer_args = strip_innermost_template_args (args, 1);
14206       args = INNERMOST_TEMPLATE_ARGS (args);
14207     }
14208
14209   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14210     {
14211       tree partial_spec_args;
14212       tree spec_args;
14213       tree parms = TREE_VALUE (t);
14214
14215       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14216       if (outer_args)
14217         {
14218           int i;
14219
14220           ++processing_template_decl;
14221
14222           /* Discard the outer levels of args, and then substitute in the
14223              template args from the enclosing class.  */
14224           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14225           partial_spec_args = tsubst_template_args
14226             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14227
14228           /* PARMS already refers to just the innermost parms, but the
14229              template parms in partial_spec_args had their levels lowered
14230              by tsubst, so we need to do the same for the parm list.  We
14231              can't just tsubst the TREE_VEC itself, as tsubst wants to
14232              treat a TREE_VEC as an argument vector.  */
14233           parms = copy_node (parms);
14234           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14235             TREE_VEC_ELT (parms, i) =
14236               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14237
14238           --processing_template_decl;
14239         }
14240       spec_args = get_class_bindings (parms,
14241                                       partial_spec_args,
14242                                       args);
14243       if (spec_args)
14244         {
14245           if (outer_args)
14246             spec_args = add_to_template_args (outer_args, spec_args);
14247           list = tree_cons (spec_args, TREE_VALUE (t), list);
14248           TREE_TYPE (list) = TREE_TYPE (t);
14249         }
14250     }
14251
14252   if (! list)
14253     return NULL_TREE;
14254
14255   ambiguous_p = false;
14256   t = list;
14257   champ = t;
14258   t = TREE_CHAIN (t);
14259   for (; t; t = TREE_CHAIN (t))
14260     {
14261       fate = more_specialized_class (champ, t);
14262       if (fate == 1)
14263         ;
14264       else
14265         {
14266           if (fate == 0)
14267             {
14268               t = TREE_CHAIN (t);
14269               if (! t)
14270                 {
14271                   ambiguous_p = true;
14272                   break;
14273                 }
14274             }
14275           champ = t;
14276         }
14277     }
14278
14279   if (!ambiguous_p)
14280     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14281       {
14282         fate = more_specialized_class (champ, t);
14283         if (fate != 1)
14284           {
14285             ambiguous_p = true;
14286             break;
14287           }
14288       }
14289
14290   if (ambiguous_p)
14291     {
14292       const char *str = "candidates are:";
14293       error ("ambiguous class template instantiation for %q#T", type);
14294       for (t = list; t; t = TREE_CHAIN (t))
14295         {
14296           error ("%s %+#T", str, TREE_TYPE (t));
14297           str = "               ";
14298         }
14299       return error_mark_node;
14300     }
14301
14302   return champ;
14303 }
14304
14305 /* Explicitly instantiate DECL.  */
14306
14307 void
14308 do_decl_instantiation (tree decl, tree storage)
14309 {
14310   tree result = NULL_TREE;
14311   int extern_p = 0;
14312
14313   if (!decl || decl == error_mark_node)
14314     /* An error occurred, for which grokdeclarator has already issued
14315        an appropriate message.  */
14316     return;
14317   else if (! DECL_LANG_SPECIFIC (decl))
14318     {
14319       error ("explicit instantiation of non-template %q#D", decl);
14320       return;
14321     }
14322   else if (TREE_CODE (decl) == VAR_DECL)
14323     {
14324       /* There is an asymmetry here in the way VAR_DECLs and
14325          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14326          the latter, the DECL we get back will be marked as a
14327          template instantiation, and the appropriate
14328          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14329          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14330          should handle VAR_DECLs as it currently handles
14331          FUNCTION_DECLs.  */
14332       if (!DECL_CLASS_SCOPE_P (decl))
14333         {
14334           error ("%qD is not a static data member of a class template", decl);
14335           return;
14336         }
14337       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14338       if (!result || TREE_CODE (result) != VAR_DECL)
14339         {
14340           error ("no matching template for %qD found", decl);
14341           return;
14342         }
14343       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14344         {
14345           error ("type %qT for explicit instantiation %qD does not match "
14346                  "declared type %qT", TREE_TYPE (result), decl,
14347                  TREE_TYPE (decl));
14348           return;
14349         }
14350     }
14351   else if (TREE_CODE (decl) != FUNCTION_DECL)
14352     {
14353       error ("explicit instantiation of %q#D", decl);
14354       return;
14355     }
14356   else
14357     result = decl;
14358
14359   /* Check for various error cases.  Note that if the explicit
14360      instantiation is valid the RESULT will currently be marked as an
14361      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
14362      until we get here.  */
14363
14364   if (DECL_TEMPLATE_SPECIALIZATION (result))
14365     {
14366       /* DR 259 [temp.spec].
14367
14368          Both an explicit instantiation and a declaration of an explicit
14369          specialization shall not appear in a program unless the explicit
14370          instantiation follows a declaration of the explicit specialization.
14371
14372          For a given set of template parameters, if an explicit
14373          instantiation of a template appears after a declaration of an
14374          explicit specialization for that template, the explicit
14375          instantiation has no effect.  */
14376       return;
14377     }
14378   else if (DECL_EXPLICIT_INSTANTIATION (result))
14379     {
14380       /* [temp.spec]
14381
14382          No program shall explicitly instantiate any template more
14383          than once.
14384
14385          We check DECL_NOT_REALLY_EXTERN so as not to complain when
14386          the first instantiation was `extern' and the second is not,
14387          and EXTERN_P for the opposite case.  */
14388       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
14389         pedwarn ("duplicate explicit instantiation of %q#D", result);
14390       /* If an "extern" explicit instantiation follows an ordinary
14391          explicit instantiation, the template is instantiated.  */
14392       if (extern_p)
14393         return;
14394     }
14395   else if (!DECL_IMPLICIT_INSTANTIATION (result))
14396     {
14397       error ("no matching template for %qD found", result);
14398       return;
14399     }
14400   else if (!DECL_TEMPLATE_INFO (result))
14401     {
14402       pedwarn ("explicit instantiation of non-template %q#D", result);
14403       return;
14404     }
14405
14406   if (storage == NULL_TREE)
14407     ;
14408   else if (storage == ridpointers[(int) RID_EXTERN])
14409     {
14410       if (pedantic && !in_system_header)
14411         pedwarn ("ISO C++ forbids the use of %<extern%> on explicit "
14412                  "instantiations");
14413       extern_p = 1;
14414     }
14415   else
14416     error ("storage class %qD applied to template instantiation", storage);
14417
14418   check_explicit_instantiation_namespace (result);
14419   mark_decl_instantiated (result, extern_p);
14420   if (! extern_p)
14421     instantiate_decl (result, /*defer_ok=*/1,
14422                       /*expl_inst_class_mem_p=*/false);
14423 }
14424
14425 static void
14426 mark_class_instantiated (tree t, int extern_p)
14427 {
14428   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
14429   SET_CLASSTYPE_INTERFACE_KNOWN (t);
14430   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
14431   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
14432   if (! extern_p)
14433     {
14434       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
14435       rest_of_type_compilation (t, 1);
14436     }
14437 }
14438
14439 /* Called from do_type_instantiation through binding_table_foreach to
14440    do recursive instantiation for the type bound in ENTRY.  */
14441 static void
14442 bt_instantiate_type_proc (binding_entry entry, void *data)
14443 {
14444   tree storage = *(tree *) data;
14445
14446   if (MAYBE_CLASS_TYPE_P (entry->type)
14447       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
14448     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
14449 }
14450
14451 /* Called from do_type_instantiation to instantiate a member
14452    (a member function or a static member variable) of an
14453    explicitly instantiated class template.  */
14454 static void
14455 instantiate_class_member (tree decl, int extern_p)
14456 {
14457   mark_decl_instantiated (decl, extern_p);
14458   if (! extern_p)
14459     instantiate_decl (decl, /*defer_ok=*/1,
14460                       /*expl_inst_class_mem_p=*/true);
14461 }
14462
14463 /* Perform an explicit instantiation of template class T.  STORAGE, if
14464    non-null, is the RID for extern, inline or static.  COMPLAIN is
14465    nonzero if this is called from the parser, zero if called recursively,
14466    since the standard is unclear (as detailed below).  */
14467
14468 void
14469 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
14470 {
14471   int extern_p = 0;
14472   int nomem_p = 0;
14473   int static_p = 0;
14474   int previous_instantiation_extern_p = 0;
14475
14476   if (TREE_CODE (t) == TYPE_DECL)
14477     t = TREE_TYPE (t);
14478
14479   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
14480     {
14481       error ("explicit instantiation of non-template type %qT", t);
14482       return;
14483     }
14484
14485   complete_type (t);
14486
14487   if (!COMPLETE_TYPE_P (t))
14488     {
14489       if (complain & tf_error)
14490         error ("explicit instantiation of %q#T before definition of template",
14491                t);
14492       return;
14493     }
14494
14495   if (storage != NULL_TREE)
14496     {
14497       if (pedantic && !in_system_header)
14498         pedwarn("ISO C++ forbids the use of %qE on explicit instantiations",
14499                 storage);
14500
14501       if (storage == ridpointers[(int) RID_INLINE])
14502         nomem_p = 1;
14503       else if (storage == ridpointers[(int) RID_EXTERN])
14504         extern_p = 1;
14505       else if (storage == ridpointers[(int) RID_STATIC])
14506         static_p = 1;
14507       else
14508         {
14509           error ("storage class %qD applied to template instantiation",
14510                  storage);
14511           extern_p = 0;
14512         }
14513     }
14514
14515   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
14516     {
14517       /* DR 259 [temp.spec].
14518
14519          Both an explicit instantiation and a declaration of an explicit
14520          specialization shall not appear in a program unless the explicit
14521          instantiation follows a declaration of the explicit specialization.
14522
14523          For a given set of template parameters, if an explicit
14524          instantiation of a template appears after a declaration of an
14525          explicit specialization for that template, the explicit
14526          instantiation has no effect.  */
14527       return;
14528     }
14529   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
14530     {
14531       /* [temp.spec]
14532
14533          No program shall explicitly instantiate any template more
14534          than once.
14535
14536          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
14537          instantiation was `extern'.  If EXTERN_P then the second is.
14538          These cases are OK.  */
14539       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
14540
14541       if (!previous_instantiation_extern_p && !extern_p
14542           && (complain & tf_error))
14543         pedwarn ("duplicate explicit instantiation of %q#T", t);
14544
14545       /* If we've already instantiated the template, just return now.  */
14546       if (!CLASSTYPE_INTERFACE_ONLY (t))
14547         return;
14548     }
14549
14550   check_explicit_instantiation_namespace (TYPE_NAME (t));
14551   mark_class_instantiated (t, extern_p);
14552
14553   if (nomem_p)
14554     return;
14555
14556   {
14557     tree tmp;
14558
14559     /* In contrast to implicit instantiation, where only the
14560        declarations, and not the definitions, of members are
14561        instantiated, we have here:
14562
14563          [temp.explicit]
14564
14565          The explicit instantiation of a class template specialization
14566          implies the instantiation of all of its members not
14567          previously explicitly specialized in the translation unit
14568          containing the explicit instantiation.
14569
14570        Of course, we can't instantiate member template classes, since
14571        we don't have any arguments for them.  Note that the standard
14572        is unclear on whether the instantiation of the members are
14573        *explicit* instantiations or not.  However, the most natural
14574        interpretation is that it should be an explicit instantiation.  */
14575
14576     if (! static_p)
14577       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
14578         if (TREE_CODE (tmp) == FUNCTION_DECL
14579             && DECL_TEMPLATE_INSTANTIATION (tmp))
14580           instantiate_class_member (tmp, extern_p);
14581
14582     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
14583       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
14584         instantiate_class_member (tmp, extern_p);
14585
14586     if (CLASSTYPE_NESTED_UTDS (t))
14587       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
14588                              bt_instantiate_type_proc, &storage);
14589   }
14590 }
14591
14592 /* Given a function DECL, which is a specialization of TMPL, modify
14593    DECL to be a re-instantiation of TMPL with the same template
14594    arguments.  TMPL should be the template into which tsubst'ing
14595    should occur for DECL, not the most general template.
14596
14597    One reason for doing this is a scenario like this:
14598
14599      template <class T>
14600      void f(const T&, int i);
14601
14602      void g() { f(3, 7); }
14603
14604      template <class T>
14605      void f(const T& t, const int i) { }
14606
14607    Note that when the template is first instantiated, with
14608    instantiate_template, the resulting DECL will have no name for the
14609    first parameter, and the wrong type for the second.  So, when we go
14610    to instantiate the DECL, we regenerate it.  */
14611
14612 static void
14613 regenerate_decl_from_template (tree decl, tree tmpl)
14614 {
14615   /* The arguments used to instantiate DECL, from the most general
14616      template.  */
14617   tree args;
14618   tree code_pattern;
14619
14620   args = DECL_TI_ARGS (decl);
14621   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
14622
14623   /* Make sure that we can see identifiers, and compute access
14624      correctly.  */
14625   push_access_scope (decl);
14626
14627   if (TREE_CODE (decl) == FUNCTION_DECL)
14628     {
14629       tree decl_parm;
14630       tree pattern_parm;
14631       tree specs;
14632       int args_depth;
14633       int parms_depth;
14634
14635       args_depth = TMPL_ARGS_DEPTH (args);
14636       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
14637       if (args_depth > parms_depth)
14638         args = get_innermost_template_args (args, parms_depth);
14639
14640       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
14641                                               args, tf_error, NULL_TREE);
14642       if (specs)
14643         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
14644                                                     specs);
14645
14646       /* Merge parameter declarations.  */
14647       decl_parm = skip_artificial_parms_for (decl,
14648                                              DECL_ARGUMENTS (decl));
14649       pattern_parm
14650         = skip_artificial_parms_for (code_pattern,
14651                                      DECL_ARGUMENTS (code_pattern));
14652       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
14653         {
14654           tree parm_type;
14655           tree attributes;
14656           
14657           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14658             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
14659           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
14660                               NULL_TREE);
14661           parm_type = type_decays_to (parm_type);
14662           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14663             TREE_TYPE (decl_parm) = parm_type;
14664           attributes = DECL_ATTRIBUTES (pattern_parm);
14665           if (DECL_ATTRIBUTES (decl_parm) != attributes)
14666             {
14667               DECL_ATTRIBUTES (decl_parm) = attributes;
14668               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14669             }
14670           decl_parm = TREE_CHAIN (decl_parm);
14671           pattern_parm = TREE_CHAIN (pattern_parm);
14672         }
14673       /* Merge any parameters that match with the function parameter
14674          pack.  */
14675       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
14676         {
14677           int i, len;
14678           tree expanded_types;
14679           /* Expand the TYPE_PACK_EXPANSION that provides the types for
14680              the parameters in this function parameter pack.  */
14681           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
14682                                                  args, tf_error, NULL_TREE);
14683           len = TREE_VEC_LENGTH (expanded_types);
14684           for (i = 0; i < len; i++)
14685             {
14686               tree parm_type;
14687               tree attributes;
14688           
14689               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14690                 /* Rename the parameter to include the index.  */
14691                 DECL_NAME (decl_parm) = 
14692                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
14693               parm_type = TREE_VEC_ELT (expanded_types, i);
14694               parm_type = type_decays_to (parm_type);
14695               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14696                 TREE_TYPE (decl_parm) = parm_type;
14697               attributes = DECL_ATTRIBUTES (pattern_parm);
14698               if (DECL_ATTRIBUTES (decl_parm) != attributes)
14699                 {
14700                   DECL_ATTRIBUTES (decl_parm) = attributes;
14701                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14702                 }
14703               decl_parm = TREE_CHAIN (decl_parm);
14704             }
14705         }
14706       /* Merge additional specifiers from the CODE_PATTERN.  */
14707       if (DECL_DECLARED_INLINE_P (code_pattern)
14708           && !DECL_DECLARED_INLINE_P (decl))
14709         DECL_DECLARED_INLINE_P (decl) = 1;
14710       if (DECL_INLINE (code_pattern) && !DECL_INLINE (decl))
14711         DECL_INLINE (decl) = 1;
14712     }
14713   else if (TREE_CODE (decl) == VAR_DECL)
14714     DECL_INITIAL (decl) =
14715       tsubst_expr (DECL_INITIAL (code_pattern), args,
14716                    tf_error, DECL_TI_TEMPLATE (decl),
14717                    /*integral_constant_expression_p=*/false);
14718   else
14719     gcc_unreachable ();
14720
14721   pop_access_scope (decl);
14722 }
14723
14724 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
14725    substituted to get DECL.  */
14726
14727 tree
14728 template_for_substitution (tree decl)
14729 {
14730   tree tmpl = DECL_TI_TEMPLATE (decl);
14731
14732   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
14733      for the instantiation.  This is not always the most general
14734      template.  Consider, for example:
14735
14736         template <class T>
14737         struct S { template <class U> void f();
14738                    template <> void f<int>(); };
14739
14740      and an instantiation of S<double>::f<int>.  We want TD to be the
14741      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
14742   while (/* An instantiation cannot have a definition, so we need a
14743             more general template.  */
14744          DECL_TEMPLATE_INSTANTIATION (tmpl)
14745            /* We must also deal with friend templates.  Given:
14746
14747                 template <class T> struct S {
14748                   template <class U> friend void f() {};
14749                 };
14750
14751               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
14752               so far as the language is concerned, but that's still
14753               where we get the pattern for the instantiation from.  On
14754               other hand, if the definition comes outside the class, say:
14755
14756                 template <class T> struct S {
14757                   template <class U> friend void f();
14758                 };
14759                 template <class U> friend void f() {}
14760
14761               we don't need to look any further.  That's what the check for
14762               DECL_INITIAL is for.  */
14763           || (TREE_CODE (decl) == FUNCTION_DECL
14764               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
14765               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
14766     {
14767       /* The present template, TD, should not be a definition.  If it
14768          were a definition, we should be using it!  Note that we
14769          cannot restructure the loop to just keep going until we find
14770          a template with a definition, since that might go too far if
14771          a specialization was declared, but not defined.  */
14772       gcc_assert (TREE_CODE (decl) != VAR_DECL
14773                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
14774
14775       /* Fetch the more general template.  */
14776       tmpl = DECL_TI_TEMPLATE (tmpl);
14777     }
14778
14779   return tmpl;
14780 }
14781
14782 /* Produce the definition of D, a _DECL generated from a template.  If
14783    DEFER_OK is nonzero, then we don't have to actually do the
14784    instantiation now; we just have to do it sometime.  Normally it is
14785    an error if this is an explicit instantiation but D is undefined.
14786    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
14787    explicitly instantiated class template.  */
14788
14789 tree
14790 instantiate_decl (tree d, int defer_ok,
14791                   bool expl_inst_class_mem_p)
14792 {
14793   tree tmpl = DECL_TI_TEMPLATE (d);
14794   tree gen_args;
14795   tree args;
14796   tree td;
14797   tree code_pattern;
14798   tree spec;
14799   tree gen_tmpl;
14800   bool pattern_defined;
14801   int need_push;
14802   location_t saved_loc = input_location;
14803   int saved_in_system_header = in_system_header;
14804   bool external_p;
14805
14806   /* This function should only be used to instantiate templates for
14807      functions and static member variables.  */
14808   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
14809               || TREE_CODE (d) == VAR_DECL);
14810
14811   /* Variables are never deferred; if instantiation is required, they
14812      are instantiated right away.  That allows for better code in the
14813      case that an expression refers to the value of the variable --
14814      if the variable has a constant value the referring expression can
14815      take advantage of that fact.  */
14816   if (TREE_CODE (d) == VAR_DECL)
14817     defer_ok = 0;
14818
14819   /* Don't instantiate cloned functions.  Instead, instantiate the
14820      functions they cloned.  */
14821   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
14822     d = DECL_CLONED_FUNCTION (d);
14823
14824   if (DECL_TEMPLATE_INSTANTIATED (d))
14825     /* D has already been instantiated.  It might seem reasonable to
14826        check whether or not D is an explicit instantiation, and, if so,
14827        stop here.  But when an explicit instantiation is deferred
14828        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
14829        is set, even though we still need to do the instantiation.  */
14830     return d;
14831
14832   /* If we already have a specialization of this declaration, then
14833      there's no reason to instantiate it.  Note that
14834      retrieve_specialization gives us both instantiations and
14835      specializations, so we must explicitly check
14836      DECL_TEMPLATE_SPECIALIZATION.  */
14837   gen_tmpl = most_general_template (tmpl);
14838   gen_args = DECL_TI_ARGS (d);
14839   spec = retrieve_specialization (gen_tmpl, gen_args,
14840                                   /*class_specializations_p=*/false);
14841   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
14842     return spec;
14843
14844   /* This needs to happen before any tsubsting.  */
14845   if (! push_tinst_level (d))
14846     return d;
14847
14848   timevar_push (TV_PARSE);
14849
14850   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
14851      for the instantiation.  */
14852   td = template_for_substitution (d);
14853   code_pattern = DECL_TEMPLATE_RESULT (td);
14854
14855   /* We should never be trying to instantiate a member of a class
14856      template or partial specialization.  */
14857   gcc_assert (d != code_pattern);
14858
14859   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
14860       || DECL_TEMPLATE_SPECIALIZATION (td))
14861     /* In the case of a friend template whose definition is provided
14862        outside the class, we may have too many arguments.  Drop the
14863        ones we don't need.  The same is true for specializations.  */
14864     args = get_innermost_template_args
14865       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
14866   else
14867     args = gen_args;
14868
14869   if (TREE_CODE (d) == FUNCTION_DECL)
14870     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
14871   else
14872     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
14873
14874   /* We may be in the middle of deferred access check.  Disable it now.  */
14875   push_deferring_access_checks (dk_no_deferred);
14876
14877   /* Unless an explicit instantiation directive has already determined
14878      the linkage of D, remember that a definition is available for
14879      this entity.  */
14880   if (pattern_defined
14881       && !DECL_INTERFACE_KNOWN (d)
14882       && !DECL_NOT_REALLY_EXTERN (d))
14883     mark_definable (d);
14884
14885   input_location = DECL_SOURCE_LOCATION (d);
14886   in_system_header = DECL_IN_SYSTEM_HEADER (d);
14887
14888   /* If D is a member of an explicitly instantiated class template,
14889      and no definition is available, treat it like an implicit
14890      instantiation.  */
14891   if (!pattern_defined && expl_inst_class_mem_p
14892       && DECL_EXPLICIT_INSTANTIATION (d))
14893     {
14894       DECL_NOT_REALLY_EXTERN (d) = 0;
14895       DECL_INTERFACE_KNOWN (d) = 0;
14896       SET_DECL_IMPLICIT_INSTANTIATION (d);
14897     }
14898
14899   if (!defer_ok)
14900     {
14901       /* Recheck the substitutions to obtain any warning messages
14902          about ignoring cv qualifiers.  */
14903       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
14904       tree type = TREE_TYPE (gen);
14905
14906       /* Make sure that we can see identifiers, and compute access
14907          correctly.  D is already the target FUNCTION_DECL with the
14908          right context.  */
14909       push_access_scope (d);
14910
14911       if (TREE_CODE (gen) == FUNCTION_DECL)
14912         {
14913           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
14914           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
14915                                           d);
14916           /* Don't simply tsubst the function type, as that will give
14917              duplicate warnings about poor parameter qualifications.
14918              The function arguments are the same as the decl_arguments
14919              without the top level cv qualifiers.  */
14920           type = TREE_TYPE (type);
14921         }
14922       tsubst (type, gen_args, tf_warning_or_error, d);
14923
14924       pop_access_scope (d);
14925     }
14926
14927   /* Check to see whether we know that this template will be
14928      instantiated in some other file, as with "extern template"
14929      extension.  */
14930   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
14931   /* In general, we do not instantiate such templates...  */
14932   if (external_p
14933       /* ... but we instantiate inline functions so that we can inline
14934          them and ... */
14935       && ! (TREE_CODE (d) == FUNCTION_DECL && DECL_INLINE (d))
14936       /* ... we instantiate static data members whose values are
14937          needed in integral constant expressions.  */
14938       && ! (TREE_CODE (d) == VAR_DECL
14939             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
14940     goto out;
14941   /* Defer all other templates, unless we have been explicitly
14942      forbidden from doing so.  */
14943   if (/* If there is no definition, we cannot instantiate the
14944          template.  */
14945       ! pattern_defined
14946       /* If it's OK to postpone instantiation, do so.  */
14947       || defer_ok
14948       /* If this is a static data member that will be defined
14949          elsewhere, we don't want to instantiate the entire data
14950          member, but we do want to instantiate the initializer so that
14951          we can substitute that elsewhere.  */
14952       || (external_p && TREE_CODE (d) == VAR_DECL))
14953     {
14954       /* The definition of the static data member is now required so
14955          we must substitute the initializer.  */
14956       if (TREE_CODE (d) == VAR_DECL
14957           && !DECL_INITIAL (d)
14958           && DECL_INITIAL (code_pattern))
14959         {
14960           tree ns;
14961           tree init;
14962
14963           ns = decl_namespace_context (d);
14964           push_nested_namespace (ns);
14965           push_nested_class (DECL_CONTEXT (d));
14966           init = tsubst_expr (DECL_INITIAL (code_pattern),
14967                               args,
14968                               tf_warning_or_error, NULL_TREE,
14969                               /*integral_constant_expression_p=*/false);
14970           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
14971                           /*asmspec_tree=*/NULL_TREE,
14972                           LOOKUP_ONLYCONVERTING);
14973           pop_nested_class ();
14974           pop_nested_namespace (ns);
14975         }
14976
14977       /* We restore the source position here because it's used by
14978          add_pending_template.  */
14979       input_location = saved_loc;
14980
14981       if (at_eof && !pattern_defined
14982           && DECL_EXPLICIT_INSTANTIATION (d))
14983         /* [temp.explicit]
14984
14985            The definition of a non-exported function template, a
14986            non-exported member function template, or a non-exported
14987            member function or static data member of a class template
14988            shall be present in every translation unit in which it is
14989            explicitly instantiated.  */
14990         pedwarn
14991           ("explicit instantiation of %qD but no definition available", d);
14992
14993       /* ??? Historically, we have instantiated inline functions, even
14994          when marked as "extern template".  */
14995       if (!(external_p && TREE_CODE (d) == VAR_DECL))
14996         add_pending_template (d);
14997       goto out;
14998     }
14999   /* Tell the repository that D is available in this translation unit
15000      -- and see if it is supposed to be instantiated here.  */
15001   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15002     {
15003       /* In a PCH file, despite the fact that the repository hasn't
15004          requested instantiation in the PCH it is still possible that
15005          an instantiation will be required in a file that includes the
15006          PCH.  */
15007       if (pch_file)
15008         add_pending_template (d);
15009       /* Instantiate inline functions so that the inliner can do its
15010          job, even though we'll not be emitting a copy of this
15011          function.  */
15012       if (!(TREE_CODE (d) == FUNCTION_DECL
15013             && flag_inline_trees
15014             && DECL_DECLARED_INLINE_P (d)))
15015         goto out;
15016     }
15017
15018   need_push = !cfun || !global_bindings_p ();
15019   if (need_push)
15020     push_to_top_level ();
15021
15022   /* Mark D as instantiated so that recursive calls to
15023      instantiate_decl do not try to instantiate it again.  */
15024   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15025
15026   /* Regenerate the declaration in case the template has been modified
15027      by a subsequent redeclaration.  */
15028   regenerate_decl_from_template (d, td);
15029
15030   /* We already set the file and line above.  Reset them now in case
15031      they changed as a result of calling regenerate_decl_from_template.  */
15032   input_location = DECL_SOURCE_LOCATION (d);
15033
15034   if (TREE_CODE (d) == VAR_DECL)
15035     {
15036       tree init;
15037
15038       /* Clear out DECL_RTL; whatever was there before may not be right
15039          since we've reset the type of the declaration.  */
15040       SET_DECL_RTL (d, NULL_RTX);
15041       DECL_IN_AGGR_P (d) = 0;
15042
15043       /* The initializer is placed in DECL_INITIAL by
15044          regenerate_decl_from_template.  Pull it out so that
15045          finish_decl can process it.  */
15046       init = DECL_INITIAL (d);
15047       DECL_INITIAL (d) = NULL_TREE;
15048       DECL_INITIALIZED_P (d) = 0;
15049
15050       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15051          initializer.  That function will defer actual emission until
15052          we have a chance to determine linkage.  */
15053       DECL_EXTERNAL (d) = 0;
15054
15055       /* Enter the scope of D so that access-checking works correctly.  */
15056       push_nested_class (DECL_CONTEXT (d));
15057       finish_decl (d, init, NULL_TREE);
15058       pop_nested_class ();
15059     }
15060   else if (TREE_CODE (d) == FUNCTION_DECL)
15061     {
15062       htab_t saved_local_specializations;
15063       tree subst_decl;
15064       tree tmpl_parm;
15065       tree spec_parm;
15066
15067       /* Save away the current list, in case we are instantiating one
15068          template from within the body of another.  */
15069       saved_local_specializations = local_specializations;
15070
15071       /* Set up the list of local specializations.  */
15072       local_specializations = htab_create (37,
15073                                            hash_local_specialization,
15074                                            eq_local_specializations,
15075                                            NULL);
15076
15077       /* Set up context.  */
15078       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15079
15080       /* Create substitution entries for the parameters.  */
15081       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15082       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15083       spec_parm = DECL_ARGUMENTS (d);
15084       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15085         {
15086           register_local_specialization (spec_parm, tmpl_parm);
15087           spec_parm = skip_artificial_parms_for (d, spec_parm);
15088           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15089         }
15090       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15091         {
15092           register_local_specialization (spec_parm, tmpl_parm);
15093           tmpl_parm = TREE_CHAIN (tmpl_parm);
15094           spec_parm = TREE_CHAIN (spec_parm);
15095         }
15096       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15097         {
15098           /* Collect all of the extra "packed" parameters into an
15099              argument pack.  */
15100           tree parmvec;
15101           tree parmtypevec;
15102           tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
15103           tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
15104           int i, len = 0;
15105           tree t;
15106           
15107           /* Count how many parameters remain.  */
15108           for (t = spec_parm; t; t = TREE_CHAIN (t))
15109             len++;
15110
15111           /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
15112           parmvec = make_tree_vec (len);
15113           parmtypevec = make_tree_vec (len);
15114           for(i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
15115             {
15116               TREE_VEC_ELT (parmvec, i) = spec_parm;
15117               TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
15118             }
15119
15120           /* Build the argument packs.  */
15121           SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
15122           SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
15123           TREE_TYPE (argpack) = argtypepack;
15124           
15125           /* Register the (value) argument pack as a specialization of
15126              TMPL_PARM, then move on.  */
15127           register_local_specialization (argpack, tmpl_parm);
15128           tmpl_parm = TREE_CHAIN (tmpl_parm);
15129         }
15130       gcc_assert (!spec_parm);
15131
15132       /* Substitute into the body of the function.  */
15133       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15134                    tf_warning_or_error, tmpl,
15135                    /*integral_constant_expression_p=*/false);
15136
15137       /* Set the current input_location to the end of the function
15138          so that finish_function knows where we are.  */
15139       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15140
15141       /* We don't need the local specializations any more.  */
15142       htab_delete (local_specializations);
15143       local_specializations = saved_local_specializations;
15144
15145       /* Finish the function.  */
15146       d = finish_function (0);
15147       expand_or_defer_fn (d);
15148     }
15149
15150   /* We're not deferring instantiation any more.  */
15151   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15152
15153   if (need_push)
15154     pop_from_top_level ();
15155
15156 out:
15157   input_location = saved_loc;
15158   in_system_header = saved_in_system_header;
15159   pop_deferring_access_checks ();
15160   pop_tinst_level ();
15161
15162   timevar_pop (TV_PARSE);
15163
15164   return d;
15165 }
15166
15167 /* Run through the list of templates that we wish we could
15168    instantiate, and instantiate any we can.  RETRIES is the
15169    number of times we retry pending template instantiation.  */
15170
15171 void
15172 instantiate_pending_templates (int retries)
15173 {
15174   int reconsider;
15175   location_t saved_loc = input_location;
15176   int saved_in_system_header = in_system_header;
15177
15178   /* Instantiating templates may trigger vtable generation.  This in turn
15179      may require further template instantiations.  We place a limit here
15180      to avoid infinite loop.  */
15181   if (pending_templates && retries >= max_tinst_depth)
15182     {
15183       tree decl = pending_templates->tinst->decl;
15184
15185       error ("template instantiation depth exceeds maximum of %d"
15186              " instantiating %q+D, possibly from virtual table generation"
15187              " (use -ftemplate-depth-NN to increase the maximum)",
15188              max_tinst_depth, decl);
15189       if (TREE_CODE (decl) == FUNCTION_DECL)
15190         /* Pretend that we defined it.  */
15191         DECL_INITIAL (decl) = error_mark_node;
15192       return;
15193     }
15194
15195   do
15196     {
15197       struct pending_template **t = &pending_templates;
15198       struct pending_template *last = NULL;
15199       reconsider = 0;
15200       while (*t)
15201         {
15202           tree instantiation = reopen_tinst_level ((*t)->tinst);
15203           bool complete = false;
15204
15205           if (TYPE_P (instantiation))
15206             {
15207               tree fn;
15208
15209               if (!COMPLETE_TYPE_P (instantiation))
15210                 {
15211                   instantiate_class_template (instantiation);
15212                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15213                     for (fn = TYPE_METHODS (instantiation);
15214                          fn;
15215                          fn = TREE_CHAIN (fn))
15216                       if (! DECL_ARTIFICIAL (fn))
15217                         instantiate_decl (fn,
15218                                           /*defer_ok=*/0,
15219                                           /*expl_inst_class_mem_p=*/false);
15220                   if (COMPLETE_TYPE_P (instantiation))
15221                     reconsider = 1;
15222                 }
15223
15224               complete = COMPLETE_TYPE_P (instantiation);
15225             }
15226           else
15227             {
15228               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15229                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15230                 {
15231                   instantiation
15232                     = instantiate_decl (instantiation,
15233                                         /*defer_ok=*/0,
15234                                         /*expl_inst_class_mem_p=*/false);
15235                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15236                     reconsider = 1;
15237                 }
15238
15239               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15240                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15241             }
15242
15243           if (complete)
15244             /* If INSTANTIATION has been instantiated, then we don't
15245                need to consider it again in the future.  */
15246             *t = (*t)->next;
15247           else
15248             {
15249               last = *t;
15250               t = &(*t)->next;
15251             }
15252           tinst_depth = 0;
15253           current_tinst_level = NULL;
15254         }
15255       last_pending_template = last;
15256     }
15257   while (reconsider);
15258
15259   input_location = saved_loc;
15260   in_system_header = saved_in_system_header;
15261 }
15262
15263 /* Substitute ARGVEC into T, which is a list of initializers for
15264    either base class or a non-static data member.  The TREE_PURPOSEs
15265    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15266    instantiate_decl.  */
15267
15268 static tree
15269 tsubst_initializer_list (tree t, tree argvec)
15270 {
15271   tree inits = NULL_TREE;
15272
15273   for (; t; t = TREE_CHAIN (t))
15274     {
15275       tree decl;
15276       tree init;
15277       tree expanded_bases = NULL_TREE;
15278       tree expanded_arguments = NULL_TREE;
15279       int i, len = 1;
15280
15281       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15282         {
15283           tree expr;
15284           tree arg;
15285
15286           /* Expand the base class expansion type into separate base
15287              classes.  */
15288           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15289                                                  tf_warning_or_error,
15290                                                  NULL_TREE);
15291           if (expanded_bases == error_mark_node)
15292             continue;
15293           
15294           /* We'll be building separate TREE_LISTs of arguments for
15295              each base.  */
15296           len = TREE_VEC_LENGTH (expanded_bases);
15297           expanded_arguments = make_tree_vec (len);
15298           for (i = 0; i < len; i++)
15299             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15300
15301           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15302              expand each argument in the TREE_VALUE of t.  */
15303           expr = make_node (EXPR_PACK_EXPANSION);
15304           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15305             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15306
15307           if (TREE_VALUE (t) == void_type_node)
15308             /* VOID_TYPE_NODE is used to indicate
15309                value-initialization.  */
15310             {
15311               for (i = 0; i < len; i++)
15312                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
15313             }
15314           else
15315             {
15316               /* Substitute parameter packs into each argument in the
15317                  TREE_LIST.  */
15318               in_base_initializer = 1;
15319               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15320                 {
15321                   tree expanded_exprs;
15322
15323                   /* Expand the argument.  */
15324                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15325                   expanded_exprs 
15326                     = tsubst_pack_expansion (expr, argvec,
15327                                              tf_warning_or_error,
15328                                              NULL_TREE);
15329
15330                   /* Prepend each of the expanded expressions to the
15331                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15332                   for (i = 0; i < len; i++)
15333                     {
15334                       TREE_VEC_ELT (expanded_arguments, i) = 
15335                         tree_cons (NULL_TREE, 
15336                                    TREE_VEC_ELT (expanded_exprs, i),
15337                                    TREE_VEC_ELT (expanded_arguments, i));
15338                     }
15339                 }
15340               in_base_initializer = 0;
15341
15342               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15343                  since we built them backwards.  */
15344               for (i = 0; i < len; i++)
15345                 {
15346                   TREE_VEC_ELT (expanded_arguments, i) = 
15347                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
15348                 }
15349             }
15350         }
15351
15352       for (i = 0; i < len; ++i)
15353         {
15354           if (expanded_bases)
15355             {
15356               decl = TREE_VEC_ELT (expanded_bases, i);
15357               decl = expand_member_init (decl);
15358               init = TREE_VEC_ELT (expanded_arguments, i);
15359             }
15360           else
15361             {
15362               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15363                                   tf_warning_or_error, NULL_TREE);
15364
15365               decl = expand_member_init (decl);
15366               if (decl && !DECL_P (decl))
15367                 in_base_initializer = 1;
15368
15369               init = tsubst_expr (TREE_VALUE (t), argvec, 
15370                                   tf_warning_or_error, NULL_TREE,
15371                                   /*integral_constant_expression_p=*/false);
15372               in_base_initializer = 0;
15373             }
15374
15375           if (decl)
15376             {
15377               init = build_tree_list (decl, init);
15378               TREE_CHAIN (init) = inits;
15379               inits = init;
15380             }
15381         }
15382     }
15383   return inits;
15384 }
15385
15386 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
15387
15388 static void
15389 set_current_access_from_decl (tree decl)
15390 {
15391   if (TREE_PRIVATE (decl))
15392     current_access_specifier = access_private_node;
15393   else if (TREE_PROTECTED (decl))
15394     current_access_specifier = access_protected_node;
15395   else
15396     current_access_specifier = access_public_node;
15397 }
15398
15399 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
15400    is the instantiation (which should have been created with
15401    start_enum) and ARGS are the template arguments to use.  */
15402
15403 static void
15404 tsubst_enum (tree tag, tree newtag, tree args)
15405 {
15406   tree e;
15407
15408   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
15409     {
15410       tree value;
15411       tree decl;
15412
15413       decl = TREE_VALUE (e);
15414       /* Note that in a template enum, the TREE_VALUE is the
15415          CONST_DECL, not the corresponding INTEGER_CST.  */
15416       value = tsubst_expr (DECL_INITIAL (decl),
15417                            args, tf_warning_or_error, NULL_TREE,
15418                            /*integral_constant_expression_p=*/true);
15419
15420       /* Give this enumeration constant the correct access.  */
15421       set_current_access_from_decl (decl);
15422
15423       /* Actually build the enumerator itself.  */
15424       build_enumerator (DECL_NAME (decl), value, newtag);
15425     }
15426
15427   finish_enum (newtag);
15428   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
15429     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
15430 }
15431
15432 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
15433    its type -- but without substituting the innermost set of template
15434    arguments.  So, innermost set of template parameters will appear in
15435    the type.  */
15436
15437 tree
15438 get_mostly_instantiated_function_type (tree decl)
15439 {
15440   tree fn_type;
15441   tree tmpl;
15442   tree targs;
15443   tree tparms;
15444   int parm_depth;
15445
15446   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15447   targs = DECL_TI_ARGS (decl);
15448   tparms = DECL_TEMPLATE_PARMS (tmpl);
15449   parm_depth = TMPL_PARMS_DEPTH (tparms);
15450
15451   /* There should be as many levels of arguments as there are levels
15452      of parameters.  */
15453   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
15454
15455   fn_type = TREE_TYPE (tmpl);
15456
15457   if (parm_depth == 1)
15458     /* No substitution is necessary.  */
15459     ;
15460   else
15461     {
15462       int i, save_access_control;
15463       tree partial_args;
15464
15465       /* Replace the innermost level of the TARGS with NULL_TREEs to
15466          let tsubst know not to substitute for those parameters.  */
15467       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
15468       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
15469         SET_TMPL_ARGS_LEVEL (partial_args, i,
15470                              TMPL_ARGS_LEVEL (targs, i));
15471       SET_TMPL_ARGS_LEVEL (partial_args,
15472                            TMPL_ARGS_DEPTH (targs),
15473                            make_tree_vec (DECL_NTPARMS (tmpl)));
15474
15475       /* Disable access control as this function is used only during
15476          name-mangling.  */
15477       save_access_control = flag_access_control;
15478       flag_access_control = 0;
15479
15480       ++processing_template_decl;
15481       /* Now, do the (partial) substitution to figure out the
15482          appropriate function type.  */
15483       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
15484       --processing_template_decl;
15485
15486       /* Substitute into the template parameters to obtain the real
15487          innermost set of parameters.  This step is important if the
15488          innermost set of template parameters contains value
15489          parameters whose types depend on outer template parameters.  */
15490       TREE_VEC_LENGTH (partial_args)--;
15491       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
15492
15493       flag_access_control = save_access_control;
15494     }
15495
15496   return fn_type;
15497 }
15498
15499 /* Return truthvalue if we're processing a template different from
15500    the last one involved in diagnostics.  */
15501 int
15502 problematic_instantiation_changed (void)
15503 {
15504   return last_template_error_tick != tinst_level_tick;
15505 }
15506
15507 /* Remember current template involved in diagnostics.  */
15508 void
15509 record_last_problematic_instantiation (void)
15510 {
15511   last_template_error_tick = tinst_level_tick;
15512 }
15513
15514 struct tinst_level *
15515 current_instantiation (void)
15516 {
15517   return current_tinst_level;
15518 }
15519
15520 /* [temp.param] Check that template non-type parm TYPE is of an allowable
15521    type. Return zero for ok, nonzero for disallowed. Issue error and
15522    warning messages under control of COMPLAIN.  */
15523
15524 static int
15525 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
15526 {
15527   if (INTEGRAL_TYPE_P (type))
15528     return 0;
15529   else if (POINTER_TYPE_P (type))
15530     return 0;
15531   else if (TYPE_PTR_TO_MEMBER_P (type))
15532     return 0;
15533   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15534     return 0;
15535   else if (TREE_CODE (type) == TYPENAME_TYPE)
15536     return 0;
15537
15538   if (complain & tf_error)
15539     error ("%q#T is not a valid type for a template constant parameter", type);
15540   return 1;
15541 }
15542
15543 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
15544    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
15545
15546 static bool
15547 dependent_type_p_r (tree type)
15548 {
15549   tree scope;
15550
15551   /* [temp.dep.type]
15552
15553      A type is dependent if it is:
15554
15555      -- a template parameter. Template template parameters are types
15556         for us (since TYPE_P holds true for them) so we handle
15557         them here.  */
15558   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
15559       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
15560     return true;
15561   /* -- a qualified-id with a nested-name-specifier which contains a
15562         class-name that names a dependent type or whose unqualified-id
15563         names a dependent type.  */
15564   if (TREE_CODE (type) == TYPENAME_TYPE)
15565     return true;
15566   /* -- a cv-qualified type where the cv-unqualified type is
15567         dependent.  */
15568   type = TYPE_MAIN_VARIANT (type);
15569   /* -- a compound type constructed from any dependent type.  */
15570   if (TYPE_PTR_TO_MEMBER_P (type))
15571     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
15572             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
15573                                            (type)));
15574   else if (TREE_CODE (type) == POINTER_TYPE
15575            || TREE_CODE (type) == REFERENCE_TYPE)
15576     return dependent_type_p (TREE_TYPE (type));
15577   else if (TREE_CODE (type) == FUNCTION_TYPE
15578            || TREE_CODE (type) == METHOD_TYPE)
15579     {
15580       tree arg_type;
15581
15582       if (dependent_type_p (TREE_TYPE (type)))
15583         return true;
15584       for (arg_type = TYPE_ARG_TYPES (type);
15585            arg_type;
15586            arg_type = TREE_CHAIN (arg_type))
15587         if (dependent_type_p (TREE_VALUE (arg_type)))
15588           return true;
15589       return false;
15590     }
15591   /* -- an array type constructed from any dependent type or whose
15592         size is specified by a constant expression that is
15593         value-dependent.  */
15594   if (TREE_CODE (type) == ARRAY_TYPE)
15595     {
15596       if (TYPE_DOMAIN (type)
15597           && dependent_type_p (TYPE_DOMAIN (type)))
15598         return true;
15599       return dependent_type_p (TREE_TYPE (type));
15600     }
15601   else if (TREE_CODE (type) == INTEGER_TYPE
15602            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
15603     {
15604       /* If this is the TYPE_DOMAIN of an array type, consider it
15605          dependent.  */
15606       return (value_dependent_expression_p (TYPE_MAX_VALUE (type))
15607               || type_dependent_expression_p (TYPE_MAX_VALUE (type)));
15608     }
15609
15610   /* -- a template-id in which either the template name is a template
15611      parameter ...  */
15612   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
15613     return true;
15614   /* ... or any of the template arguments is a dependent type or
15615         an expression that is type-dependent or value-dependent.  */
15616   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
15617            && (any_dependent_template_arguments_p
15618                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
15619     return true;
15620
15621   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
15622      argument of the `typeof' expression is not type-dependent, then
15623      it should already been have resolved.  */
15624   if (TREE_CODE (type) == TYPEOF_TYPE
15625       || TREE_CODE (type) == DECLTYPE_TYPE)
15626     return true;
15627
15628   /* A template argument pack is dependent if any of its packed
15629      arguments are.  */
15630   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
15631     {
15632       tree args = ARGUMENT_PACK_ARGS (type);
15633       int i, len = TREE_VEC_LENGTH (args);
15634       for (i = 0; i < len; ++i)
15635         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
15636           return true;
15637     }
15638
15639   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
15640      be template parameters.  */
15641   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
15642     return true;
15643
15644   /* The standard does not specifically mention types that are local
15645      to template functions or local classes, but they should be
15646      considered dependent too.  For example:
15647
15648        template <int I> void f() {
15649          enum E { a = I };
15650          S<sizeof (E)> s;
15651        }
15652
15653      The size of `E' cannot be known until the value of `I' has been
15654      determined.  Therefore, `E' must be considered dependent.  */
15655   scope = TYPE_CONTEXT (type);
15656   if (scope && TYPE_P (scope))
15657     return dependent_type_p (scope);
15658   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
15659     return type_dependent_expression_p (scope);
15660
15661   /* Other types are non-dependent.  */
15662   return false;
15663 }
15664
15665 /* Returns TRUE if TYPE is dependent, in the sense of
15666    [temp.dep.type].  */
15667
15668 bool
15669 dependent_type_p (tree type)
15670 {
15671   /* If there are no template parameters in scope, then there can't be
15672      any dependent types.  */
15673   if (!processing_template_decl)
15674     {
15675       /* If we are not processing a template, then nobody should be
15676          providing us with a dependent type.  */
15677       gcc_assert (type);
15678       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM);
15679       return false;
15680     }
15681
15682   /* If the type is NULL, we have not computed a type for the entity
15683      in question; in that case, the type is dependent.  */
15684   if (!type)
15685     return true;
15686
15687   /* Erroneous types can be considered non-dependent.  */
15688   if (type == error_mark_node)
15689     return false;
15690
15691   /* If we have not already computed the appropriate value for TYPE,
15692      do so now.  */
15693   if (!TYPE_DEPENDENT_P_VALID (type))
15694     {
15695       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
15696       TYPE_DEPENDENT_P_VALID (type) = 1;
15697     }
15698
15699   return TYPE_DEPENDENT_P (type);
15700 }
15701
15702 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
15703
15704 static bool
15705 dependent_scope_ref_p (tree expression, bool criterion (tree))
15706 {
15707   tree scope;
15708   tree name;
15709
15710   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
15711
15712   if (!TYPE_P (TREE_OPERAND (expression, 0)))
15713     return true;
15714
15715   scope = TREE_OPERAND (expression, 0);
15716   name = TREE_OPERAND (expression, 1);
15717
15718   /* [temp.dep.expr]
15719
15720      An id-expression is type-dependent if it contains a
15721      nested-name-specifier that contains a class-name that names a
15722      dependent type.  */
15723   /* The suggested resolution to Core Issue 2 implies that if the
15724      qualifying type is the current class, then we must peek
15725      inside it.  */
15726   if (DECL_P (name)
15727       && currently_open_class (scope)
15728       && !criterion (name))
15729     return false;
15730   if (dependent_type_p (scope))
15731     return true;
15732
15733   return false;
15734 }
15735
15736 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
15737    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
15738    expression.  */
15739
15740 bool
15741 value_dependent_expression_p (tree expression)
15742 {
15743   if (!processing_template_decl)
15744     return false;
15745
15746   /* A name declared with a dependent type.  */
15747   if (DECL_P (expression) && type_dependent_expression_p (expression))
15748     return true;
15749
15750   switch (TREE_CODE (expression))
15751     {
15752     case IDENTIFIER_NODE:
15753       /* A name that has not been looked up -- must be dependent.  */
15754       return true;
15755
15756     case TEMPLATE_PARM_INDEX:
15757       /* A non-type template parm.  */
15758       return true;
15759
15760     case CONST_DECL:
15761       /* A non-type template parm.  */
15762       if (DECL_TEMPLATE_PARM_P (expression))
15763         return true;
15764       return value_dependent_expression_p (DECL_INITIAL (expression));
15765
15766     case VAR_DECL:
15767        /* A constant with integral or enumeration type and is initialized
15768           with an expression that is value-dependent.  */
15769       if (DECL_INITIAL (expression)
15770           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
15771           && value_dependent_expression_p (DECL_INITIAL (expression)))
15772         return true;
15773       return false;
15774
15775     case DYNAMIC_CAST_EXPR:
15776     case STATIC_CAST_EXPR:
15777     case CONST_CAST_EXPR:
15778     case REINTERPRET_CAST_EXPR:
15779     case CAST_EXPR:
15780       /* These expressions are value-dependent if the type to which
15781          the cast occurs is dependent or the expression being casted
15782          is value-dependent.  */
15783       {
15784         tree type = TREE_TYPE (expression);
15785
15786         if (dependent_type_p (type))
15787           return true;
15788
15789         /* A functional cast has a list of operands.  */
15790         expression = TREE_OPERAND (expression, 0);
15791         if (!expression)
15792           {
15793             /* If there are no operands, it must be an expression such
15794                as "int()". This should not happen for aggregate types
15795                because it would form non-constant expressions.  */
15796             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
15797
15798             return false;
15799           }
15800
15801         if (TREE_CODE (expression) == TREE_LIST)
15802           return any_value_dependent_elements_p (expression);
15803
15804         return value_dependent_expression_p (expression);
15805       }
15806
15807     case SIZEOF_EXPR:
15808     case ALIGNOF_EXPR:
15809       /* A `sizeof' expression is value-dependent if the operand is
15810          type-dependent or is a pack expansion.  */
15811       expression = TREE_OPERAND (expression, 0);
15812       if (PACK_EXPANSION_P (expression))
15813         return true;
15814       else if (TYPE_P (expression))
15815         return dependent_type_p (expression);
15816       return type_dependent_expression_p (expression);
15817
15818     case SCOPE_REF:
15819       return dependent_scope_ref_p (expression, value_dependent_expression_p);
15820
15821     case COMPONENT_REF:
15822       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
15823               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
15824
15825     case CALL_EXPR:
15826       /* A CALL_EXPR may appear in a constant expression if it is a
15827          call to a builtin function, e.g., __builtin_constant_p.  All
15828          such calls are value-dependent.  */
15829       return true;
15830
15831     case NONTYPE_ARGUMENT_PACK:
15832       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
15833          is value-dependent.  */
15834       {
15835         tree values = ARGUMENT_PACK_ARGS (expression);
15836         int i, len = TREE_VEC_LENGTH (values);
15837         
15838         for (i = 0; i < len; ++i)
15839           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
15840             return true;
15841         
15842         return false;
15843       }
15844
15845     case TRAIT_EXPR:
15846       {
15847         tree type2 = TRAIT_EXPR_TYPE2 (expression);
15848         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
15849                 || (type2 ? dependent_type_p (type2) : false));
15850       }
15851
15852     case MODOP_EXPR:
15853       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
15854               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
15855
15856     default:
15857       /* A constant expression is value-dependent if any subexpression is
15858          value-dependent.  */
15859       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
15860         {
15861         case tcc_reference:
15862         case tcc_unary:
15863           return (value_dependent_expression_p
15864                   (TREE_OPERAND (expression, 0)));
15865
15866         case tcc_comparison:
15867         case tcc_binary:
15868           return ((value_dependent_expression_p
15869                    (TREE_OPERAND (expression, 0)))
15870                   || (value_dependent_expression_p
15871                       (TREE_OPERAND (expression, 1))));
15872
15873         case tcc_expression:
15874         case tcc_vl_exp:
15875           {
15876             int i;
15877             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
15878               /* In some cases, some of the operands may be missing.
15879                  (For example, in the case of PREDECREMENT_EXPR, the
15880                  amount to increment by may be missing.)  That doesn't
15881                  make the expression dependent.  */
15882               if (TREE_OPERAND (expression, i)
15883                   && (value_dependent_expression_p
15884                       (TREE_OPERAND (expression, i))))
15885                 return true;
15886             return false;
15887           }
15888
15889         default:
15890           break;
15891         }
15892     }
15893
15894   /* The expression is not value-dependent.  */
15895   return false;
15896 }
15897
15898 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
15899    [temp.dep.expr].  */
15900
15901 bool
15902 type_dependent_expression_p (tree expression)
15903 {
15904   if (!processing_template_decl)
15905     return false;
15906
15907   if (expression == error_mark_node)
15908     return false;
15909
15910   /* An unresolved name is always dependent.  */
15911   if (TREE_CODE (expression) == IDENTIFIER_NODE
15912       || TREE_CODE (expression) == USING_DECL)
15913     return true;
15914
15915   /* Some expression forms are never type-dependent.  */
15916   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
15917       || TREE_CODE (expression) == SIZEOF_EXPR
15918       || TREE_CODE (expression) == ALIGNOF_EXPR
15919       || TREE_CODE (expression) == TRAIT_EXPR
15920       || TREE_CODE (expression) == TYPEID_EXPR
15921       || TREE_CODE (expression) == DELETE_EXPR
15922       || TREE_CODE (expression) == VEC_DELETE_EXPR
15923       || TREE_CODE (expression) == THROW_EXPR)
15924     return false;
15925
15926   /* The types of these expressions depends only on the type to which
15927      the cast occurs.  */
15928   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
15929       || TREE_CODE (expression) == STATIC_CAST_EXPR
15930       || TREE_CODE (expression) == CONST_CAST_EXPR
15931       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
15932       || TREE_CODE (expression) == CAST_EXPR)
15933     return dependent_type_p (TREE_TYPE (expression));
15934
15935   /* The types of these expressions depends only on the type created
15936      by the expression.  */
15937   if (TREE_CODE (expression) == NEW_EXPR
15938       || TREE_CODE (expression) == VEC_NEW_EXPR)
15939     {
15940       /* For NEW_EXPR tree nodes created inside a template, either
15941          the object type itself or a TREE_LIST may appear as the
15942          operand 1.  */
15943       tree type = TREE_OPERAND (expression, 1);
15944       if (TREE_CODE (type) == TREE_LIST)
15945         /* This is an array type.  We need to check array dimensions
15946            as well.  */
15947         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
15948                || value_dependent_expression_p
15949                     (TREE_OPERAND (TREE_VALUE (type), 1));
15950       else
15951         return dependent_type_p (type);
15952     }
15953
15954   if (TREE_CODE (expression) == SCOPE_REF
15955       && dependent_scope_ref_p (expression,
15956                                 type_dependent_expression_p))
15957     return true;
15958
15959   if (TREE_CODE (expression) == FUNCTION_DECL
15960       && DECL_LANG_SPECIFIC (expression)
15961       && DECL_TEMPLATE_INFO (expression)
15962       && (any_dependent_template_arguments_p
15963           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
15964     return true;
15965
15966   if (TREE_CODE (expression) == TEMPLATE_DECL
15967       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
15968     return false;
15969
15970   if (TREE_CODE (expression) == STMT_EXPR)
15971     expression = stmt_expr_value_expr (expression);
15972
15973   if (TREE_TYPE (expression) == unknown_type_node)
15974     {
15975       if (TREE_CODE (expression) == ADDR_EXPR)
15976         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
15977       if (TREE_CODE (expression) == COMPONENT_REF
15978           || TREE_CODE (expression) == OFFSET_REF)
15979         {
15980           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
15981             return true;
15982           expression = TREE_OPERAND (expression, 1);
15983           if (TREE_CODE (expression) == IDENTIFIER_NODE)
15984             return false;
15985         }
15986       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
15987       if (TREE_CODE (expression) == SCOPE_REF)
15988         return false;
15989
15990       if (TREE_CODE (expression) == BASELINK)
15991         expression = BASELINK_FUNCTIONS (expression);
15992
15993       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
15994         {
15995           if (any_dependent_template_arguments_p
15996               (TREE_OPERAND (expression, 1)))
15997             return true;
15998           expression = TREE_OPERAND (expression, 0);
15999         }
16000       gcc_assert (TREE_CODE (expression) == OVERLOAD
16001                   || TREE_CODE (expression) == FUNCTION_DECL);
16002
16003       while (expression)
16004         {
16005           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16006             return true;
16007           expression = OVL_NEXT (expression);
16008         }
16009       return false;
16010     }
16011
16012   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16013
16014   return (dependent_type_p (TREE_TYPE (expression)));
16015 }
16016
16017 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
16018    contains a type-dependent expression.  */
16019
16020 bool
16021 any_type_dependent_arguments_p (const_tree args)
16022 {
16023   while (args)
16024     {
16025       tree arg = TREE_VALUE (args);
16026
16027       if (type_dependent_expression_p (arg))
16028         return true;
16029       args = TREE_CHAIN (args);
16030     }
16031   return false;
16032 }
16033
16034 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16035    expressions) contains any value-dependent expressions.  */
16036
16037 bool
16038 any_value_dependent_elements_p (const_tree list)
16039 {
16040   for (; list; list = TREE_CHAIN (list))
16041     if (value_dependent_expression_p (TREE_VALUE (list)))
16042       return true;
16043
16044   return false;
16045 }
16046
16047 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16048
16049 bool
16050 dependent_template_arg_p (tree arg)
16051 {
16052   if (!processing_template_decl)
16053     return false;
16054
16055   if (TREE_CODE (arg) == TEMPLATE_DECL
16056       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16057     return dependent_template_p (arg);
16058   else if (ARGUMENT_PACK_P (arg))
16059     {
16060       tree args = ARGUMENT_PACK_ARGS (arg);
16061       int i, len = TREE_VEC_LENGTH (args);
16062       for (i = 0; i < len; ++i)
16063         {
16064           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16065             return true;
16066         }
16067
16068       return false;
16069     }
16070   else if (TYPE_P (arg))
16071     return dependent_type_p (arg);
16072   else
16073     return (type_dependent_expression_p (arg)
16074             || value_dependent_expression_p (arg));
16075 }
16076
16077 /* Returns true if ARGS (a collection of template arguments) contains
16078    any types that require structural equality testing.  */
16079
16080 bool
16081 any_template_arguments_need_structural_equality_p (tree args)
16082 {
16083   int i;
16084   int j;
16085
16086   if (!args)
16087     return false;
16088   if (args == error_mark_node)
16089     return true;
16090
16091   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16092     {
16093       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16094       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16095         {
16096           tree arg = TREE_VEC_ELT (level, j);
16097           tree packed_args = NULL_TREE;
16098           int k, len = 1;
16099
16100           if (ARGUMENT_PACK_P (arg))
16101             {
16102               /* Look inside the argument pack.  */
16103               packed_args = ARGUMENT_PACK_ARGS (arg);
16104               len = TREE_VEC_LENGTH (packed_args);
16105             }
16106
16107           for (k = 0; k < len; ++k)
16108             {
16109               if (packed_args)
16110                 arg = TREE_VEC_ELT (packed_args, k);
16111
16112               if (error_operand_p (arg))
16113                 return true;
16114               else if (TREE_CODE (arg) == TEMPLATE_DECL
16115                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16116                 continue;
16117               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
16118                 return true;
16119               else if (!TYPE_P (arg) && TREE_TYPE (arg)
16120                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
16121                 return true;
16122             }
16123         }
16124     }
16125
16126   return false;
16127 }
16128
16129 /* Returns true if ARGS (a collection of template arguments) contains
16130    any dependent arguments.  */
16131
16132 bool
16133 any_dependent_template_arguments_p (const_tree args)
16134 {
16135   int i;
16136   int j;
16137
16138   if (!args)
16139     return false;
16140   if (args == error_mark_node)
16141     return true;
16142
16143   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16144     {
16145       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16146       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16147         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16148           return true;
16149     }
16150
16151   return false;
16152 }
16153
16154 /* Returns TRUE if the template TMPL is dependent.  */
16155
16156 bool
16157 dependent_template_p (tree tmpl)
16158 {
16159   if (TREE_CODE (tmpl) == OVERLOAD)
16160     {
16161       while (tmpl)
16162         {
16163           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16164             return true;
16165           tmpl = OVL_CHAIN (tmpl);
16166         }
16167       return false;
16168     }
16169
16170   /* Template template parameters are dependent.  */
16171   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16172       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16173     return true;
16174   /* So are names that have not been looked up.  */
16175   if (TREE_CODE (tmpl) == SCOPE_REF
16176       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16177     return true;
16178   /* So are member templates of dependent classes.  */
16179   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16180     return dependent_type_p (DECL_CONTEXT (tmpl));
16181   return false;
16182 }
16183
16184 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16185
16186 bool
16187 dependent_template_id_p (tree tmpl, tree args)
16188 {
16189   return (dependent_template_p (tmpl)
16190           || any_dependent_template_arguments_p (args));
16191 }
16192
16193 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16194    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16195    no such TYPE can be found.  Note that this function peers inside
16196    uninstantiated templates and therefore should be used only in
16197    extremely limited situations.  ONLY_CURRENT_P restricts this
16198    peering to the currently open classes hierarchy (which is required
16199    when comparing types).  */
16200
16201 tree
16202 resolve_typename_type (tree type, bool only_current_p)
16203 {
16204   tree scope;
16205   tree name;
16206   tree decl;
16207   int quals;
16208   tree pushed_scope;
16209   tree result;
16210
16211   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16212
16213   scope = TYPE_CONTEXT (type);
16214   name = TYPE_IDENTIFIER (type);
16215
16216   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16217      it first before we can figure out what NAME refers to.  */
16218   if (TREE_CODE (scope) == TYPENAME_TYPE)
16219     scope = resolve_typename_type (scope, only_current_p);
16220   /* If we don't know what SCOPE refers to, then we cannot resolve the
16221      TYPENAME_TYPE.  */
16222   if (TREE_CODE (scope) == TYPENAME_TYPE)
16223     return type;
16224   /* If the SCOPE is a template type parameter, we have no way of
16225      resolving the name.  */
16226   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16227     return type;
16228   /* If the SCOPE is not the current instantiation, there's no reason
16229      to look inside it.  */
16230   if (only_current_p && !currently_open_class (scope))
16231     return type;
16232   /* If SCOPE isn't the template itself, it will not have a valid
16233      TYPE_FIELDS list.  */
16234   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16235     /* scope is either the template itself or a compatible instantiation
16236        like X<T>, so look up the name in the original template.  */
16237     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16238   else
16239     /* scope is a partial instantiation, so we can't do the lookup or we
16240        will lose the template arguments.  */
16241     return type;
16242   /* Enter the SCOPE so that name lookup will be resolved as if we
16243      were in the class definition.  In particular, SCOPE will no
16244      longer be considered a dependent type.  */
16245   pushed_scope = push_scope (scope);
16246   /* Look up the declaration.  */
16247   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16248
16249   result = NULL_TREE;
16250   
16251   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
16252      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
16253   if (!decl)
16254     /*nop*/;
16255   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
16256            && TREE_CODE (decl) == TYPE_DECL)
16257     {
16258       result = TREE_TYPE (decl);
16259       if (result == error_mark_node)
16260         result = NULL_TREE;
16261     }
16262   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
16263            && DECL_CLASS_TEMPLATE_P (decl))
16264     {
16265       tree tmpl;
16266       tree args;
16267       /* Obtain the template and the arguments.  */
16268       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
16269       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
16270       /* Instantiate the template.  */
16271       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
16272                                       /*entering_scope=*/0,
16273                                       tf_error | tf_user);
16274       if (result == error_mark_node)
16275         result = NULL_TREE;
16276     }
16277   
16278   /* Leave the SCOPE.  */
16279   if (pushed_scope)
16280     pop_scope (pushed_scope);
16281
16282   /* If we failed to resolve it, return the original typename.  */
16283   if (!result)
16284     return type;
16285   
16286   /* If lookup found a typename type, resolve that too.  */
16287   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
16288     {
16289       /* Ill-formed programs can cause infinite recursion here, so we
16290          must catch that.  */
16291       TYPENAME_IS_RESOLVING_P (type) = 1;
16292       result = resolve_typename_type (result, only_current_p);
16293       TYPENAME_IS_RESOLVING_P (type) = 0;
16294     }
16295   
16296   /* Qualify the resulting type.  */
16297   quals = cp_type_quals (type);
16298   if (quals)
16299     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
16300
16301   return result;
16302 }
16303
16304 /* EXPR is an expression which is not type-dependent.  Return a proxy
16305    for EXPR that can be used to compute the types of larger
16306    expressions containing EXPR.  */
16307
16308 tree
16309 build_non_dependent_expr (tree expr)
16310 {
16311   tree inner_expr;
16312
16313   /* Preserve null pointer constants so that the type of things like
16314      "p == 0" where "p" is a pointer can be determined.  */
16315   if (null_ptr_cst_p (expr))
16316     return expr;
16317   /* Preserve OVERLOADs; the functions must be available to resolve
16318      types.  */
16319   inner_expr = expr;
16320   if (TREE_CODE (inner_expr) == STMT_EXPR)
16321     inner_expr = stmt_expr_value_expr (inner_expr);
16322   if (TREE_CODE (inner_expr) == ADDR_EXPR)
16323     inner_expr = TREE_OPERAND (inner_expr, 0);
16324   if (TREE_CODE (inner_expr) == COMPONENT_REF)
16325     inner_expr = TREE_OPERAND (inner_expr, 1);
16326   if (is_overloaded_fn (inner_expr)
16327       || TREE_CODE (inner_expr) == OFFSET_REF)
16328     return expr;
16329   /* There is no need to return a proxy for a variable.  */
16330   if (TREE_CODE (expr) == VAR_DECL)
16331     return expr;
16332   /* Preserve string constants; conversions from string constants to
16333      "char *" are allowed, even though normally a "const char *"
16334      cannot be used to initialize a "char *".  */
16335   if (TREE_CODE (expr) == STRING_CST)
16336     return expr;
16337   /* Preserve arithmetic constants, as an optimization -- there is no
16338      reason to create a new node.  */
16339   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
16340     return expr;
16341   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
16342      There is at least one place where we want to know that a
16343      particular expression is a throw-expression: when checking a ?:
16344      expression, there are special rules if the second or third
16345      argument is a throw-expression.  */
16346   if (TREE_CODE (expr) == THROW_EXPR)
16347     return expr;
16348
16349   if (TREE_CODE (expr) == COND_EXPR)
16350     return build3 (COND_EXPR,
16351                    TREE_TYPE (expr),
16352                    TREE_OPERAND (expr, 0),
16353                    (TREE_OPERAND (expr, 1)
16354                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
16355                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
16356                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
16357   if (TREE_CODE (expr) == COMPOUND_EXPR
16358       && !COMPOUND_EXPR_OVERLOADED (expr))
16359     return build2 (COMPOUND_EXPR,
16360                    TREE_TYPE (expr),
16361                    TREE_OPERAND (expr, 0),
16362                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
16363
16364   /* If the type is unknown, it can't really be non-dependent */
16365   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
16366
16367   /* Otherwise, build a NON_DEPENDENT_EXPR.
16368
16369      REFERENCE_TYPEs are not stripped for expressions in templates
16370      because doing so would play havoc with mangling.  Consider, for
16371      example:
16372
16373        template <typename T> void f<T& g>() { g(); }
16374
16375      In the body of "f", the expression for "g" will have
16376      REFERENCE_TYPE, even though the standard says that it should
16377      not.  The reason is that we must preserve the syntactic form of
16378      the expression so that mangling (say) "f<g>" inside the body of
16379      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
16380      stripped here.  */
16381   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
16382 }
16383
16384 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
16385    Return a new TREE_LIST with the various arguments replaced with
16386    equivalent non-dependent expressions.  */
16387
16388 tree
16389 build_non_dependent_args (tree args)
16390 {
16391   tree a;
16392   tree new_args;
16393
16394   new_args = NULL_TREE;
16395   for (a = args; a; a = TREE_CHAIN (a))
16396     new_args = tree_cons (NULL_TREE,
16397                           build_non_dependent_expr (TREE_VALUE (a)),
16398                           new_args);
16399   return nreverse (new_args);
16400 }
16401
16402 #include "gt-cp-pt.h"