OSDN Git Service

PR c++/33959
[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  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 (IS_AGGR_TYPE (type)
240           && CLASSTYPE_TEMPLATE_INFO (type)
241           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
242         {
243           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
244           check_member_template (tmpl);
245           return tmpl;
246         }
247       return NULL_TREE;
248     }
249   else if (TREE_CODE (decl) == FIELD_DECL)
250     error ("data member %qD cannot be a member template", decl);
251   else if (DECL_TEMPLATE_INFO (decl))
252     {
253       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
254         {
255           check_member_template (DECL_TI_TEMPLATE (decl));
256           return DECL_TI_TEMPLATE (decl);
257         }
258       else
259         return decl;
260     }
261   else
262     error ("invalid member template declaration %qD", decl);
263
264   return error_mark_node;
265 }
266
267 /* Return the template info node corresponding to T, whatever T is.  */
268
269 tree
270 get_template_info (tree t)
271 {
272   tree tinfo = NULL_TREE;
273
274   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
275     tinfo = DECL_TEMPLATE_INFO (t);
276
277   if (!tinfo && TREE_CODE (t) == TYPE_DECL)
278     t = TREE_TYPE (t);
279
280   if (TAGGED_TYPE_P (t))
281     tinfo = TYPE_TEMPLATE_INFO (t);
282
283   return tinfo;
284 }
285
286 /* Returns the template nesting level of the indicated class TYPE.
287
288    For example, in:
289      template <class T>
290      struct A
291      {
292        template <class U>
293        struct B {};
294      };
295
296    A<T>::B<U> has depth two, while A<T> has depth one.
297    Both A<T>::B<int> and A<int>::B<U> have depth one, if
298    they are instantiations, not specializations.
299
300    This function is guaranteed to return 0 if passed NULL_TREE so
301    that, for example, `template_class_depth (current_class_type)' is
302    always safe.  */
303
304 int
305 template_class_depth (tree type)
306 {
307   int depth;
308
309   for (depth = 0;
310        type && TREE_CODE (type) != NAMESPACE_DECL;
311        type = (TREE_CODE (type) == FUNCTION_DECL)
312          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
313     {
314       tree tinfo = get_template_info (type);
315
316       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
317           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
318         ++depth;
319     }
320
321   return depth;
322 }
323
324 /* Subroutine of maybe_begin_member_template_processing.
325    Returns true if processing DECL needs us to push template parms.  */
326
327 static bool
328 inline_needs_template_parms (tree decl)
329 {
330   if (! DECL_TEMPLATE_INFO (decl))
331     return false;
332
333   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
334           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
335 }
336
337 /* Subroutine of maybe_begin_member_template_processing.
338    Push the template parms in PARMS, starting from LEVELS steps into the
339    chain, and ending at the beginning, since template parms are listed
340    innermost first.  */
341
342 static void
343 push_inline_template_parms_recursive (tree parmlist, int levels)
344 {
345   tree parms = TREE_VALUE (parmlist);
346   int i;
347
348   if (levels > 1)
349     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
350
351   ++processing_template_decl;
352   current_template_parms
353     = tree_cons (size_int (processing_template_decl),
354                  parms, current_template_parms);
355   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
356
357   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
358                NULL);
359   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
360     {
361       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
362
363       if (parm == error_mark_node)
364         continue;
365
366       gcc_assert (DECL_P (parm));
367
368       switch (TREE_CODE (parm))
369         {
370         case TYPE_DECL:
371         case TEMPLATE_DECL:
372           pushdecl (parm);
373           break;
374
375         case PARM_DECL:
376           {
377             /* Make a CONST_DECL as is done in process_template_parm.
378                It is ugly that we recreate this here; the original
379                version built in process_template_parm is no longer
380                available.  */
381             tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
382                                     TREE_TYPE (parm));
383             DECL_ARTIFICIAL (decl) = 1;
384             TREE_CONSTANT (decl) = 1;
385             TREE_INVARIANT (decl) = 1;
386             TREE_READONLY (decl) = 1;
387             DECL_INITIAL (decl) = DECL_INITIAL (parm);
388             SET_DECL_TEMPLATE_PARM_P (decl);
389             pushdecl (decl);
390           }
391           break;
392
393         default:
394           gcc_unreachable ();
395         }
396     }
397 }
398
399 /* Restore the template parameter context for a member template or
400    a friend template defined in a class definition.  */
401
402 void
403 maybe_begin_member_template_processing (tree decl)
404 {
405   tree parms;
406   int levels = 0;
407
408   if (inline_needs_template_parms (decl))
409     {
410       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
411       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
412
413       if (DECL_TEMPLATE_SPECIALIZATION (decl))
414         {
415           --levels;
416           parms = TREE_CHAIN (parms);
417         }
418
419       push_inline_template_parms_recursive (parms, levels);
420     }
421
422   /* Remember how many levels of template parameters we pushed so that
423      we can pop them later.  */
424   VEC_safe_push (int, heap, inline_parm_levels, levels);
425 }
426
427 /* Undo the effects of maybe_begin_member_template_processing.  */
428
429 void
430 maybe_end_member_template_processing (void)
431 {
432   int i;
433   int last;
434
435   if (VEC_length (int, inline_parm_levels) == 0)
436     return;
437
438   last = VEC_pop (int, inline_parm_levels);
439   for (i = 0; i < last; ++i)
440     {
441       --processing_template_decl;
442       current_template_parms = TREE_CHAIN (current_template_parms);
443       poplevel (0, 0, 0);
444     }
445 }
446
447 /* Return a new template argument vector which contains all of ARGS,
448    but has as its innermost set of arguments the EXTRA_ARGS.  */
449
450 static tree
451 add_to_template_args (tree args, tree extra_args)
452 {
453   tree new_args;
454   int extra_depth;
455   int i;
456   int j;
457
458   extra_depth = TMPL_ARGS_DEPTH (extra_args);
459   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
460
461   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
462     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
463
464   for (j = 1; j <= extra_depth; ++j, ++i)
465     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
466
467   return new_args;
468 }
469
470 /* Like add_to_template_args, but only the outermost ARGS are added to
471    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
472    (EXTRA_ARGS) levels are added.  This function is used to combine
473    the template arguments from a partial instantiation with the
474    template arguments used to attain the full instantiation from the
475    partial instantiation.  */
476
477 static tree
478 add_outermost_template_args (tree args, tree extra_args)
479 {
480   tree new_args;
481
482   /* If there are more levels of EXTRA_ARGS than there are ARGS,
483      something very fishy is going on.  */
484   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
485
486   /* If *all* the new arguments will be the EXTRA_ARGS, just return
487      them.  */
488   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
489     return extra_args;
490
491   /* For the moment, we make ARGS look like it contains fewer levels.  */
492   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
493
494   new_args = add_to_template_args (args, extra_args);
495
496   /* Now, we restore ARGS to its full dimensions.  */
497   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
498
499   return new_args;
500 }
501
502 /* Return the N levels of innermost template arguments from the ARGS.  */
503
504 tree
505 get_innermost_template_args (tree args, int n)
506 {
507   tree new_args;
508   int extra_levels;
509   int i;
510
511   gcc_assert (n >= 0);
512
513   /* If N is 1, just return the innermost set of template arguments.  */
514   if (n == 1)
515     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
516
517   /* If we're not removing anything, just return the arguments we were
518      given.  */
519   extra_levels = TMPL_ARGS_DEPTH (args) - n;
520   gcc_assert (extra_levels >= 0);
521   if (extra_levels == 0)
522     return args;
523
524   /* Make a new set of arguments, not containing the outer arguments.  */
525   new_args = make_tree_vec (n);
526   for (i = 1; i <= n; ++i)
527     SET_TMPL_ARGS_LEVEL (new_args, i,
528                          TMPL_ARGS_LEVEL (args, i + extra_levels));
529
530   return new_args;
531 }
532
533 /* The inverse of get_innermost_template_args: Return all but the innermost
534    EXTRA_LEVELS levels of template arguments from the ARGS.  */
535
536 static tree
537 strip_innermost_template_args (tree args, int extra_levels)
538 {
539   tree new_args;
540   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
541   int i;
542
543   gcc_assert (n >= 0);
544
545   /* If N is 1, just return the outermost set of template arguments.  */
546   if (n == 1)
547     return TMPL_ARGS_LEVEL (args, 1);
548
549   /* If we're not removing anything, just return the arguments we were
550      given.  */
551   gcc_assert (extra_levels >= 0);
552   if (extra_levels == 0)
553     return args;
554
555   /* Make a new set of arguments, not containing the inner arguments.  */
556   new_args = make_tree_vec (n);
557   for (i = 1; i <= n; ++i)
558     SET_TMPL_ARGS_LEVEL (new_args, i,
559                          TMPL_ARGS_LEVEL (args, i));
560
561   return new_args;
562 }
563
564 /* We've got a template header coming up; push to a new level for storing
565    the parms.  */
566
567 void
568 begin_template_parm_list (void)
569 {
570   /* We use a non-tag-transparent scope here, which causes pushtag to
571      put tags in this scope, rather than in the enclosing class or
572      namespace scope.  This is the right thing, since we want
573      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
574      global template class, push_template_decl handles putting the
575      TEMPLATE_DECL into top-level scope.  For a nested template class,
576      e.g.:
577
578        template <class T> struct S1 {
579          template <class T> struct S2 {};
580        };
581
582      pushtag contains special code to call pushdecl_with_scope on the
583      TEMPLATE_DECL for S2.  */
584   begin_scope (sk_template_parms, NULL);
585   ++processing_template_decl;
586   ++processing_template_parmlist;
587   note_template_header (0);
588 }
589
590 /* This routine is called when a specialization is declared.  If it is
591    invalid to declare a specialization here, an error is reported and
592    false is returned, otherwise this routine will return true.  */
593
594 static bool
595 check_specialization_scope (void)
596 {
597   tree scope = current_scope ();
598
599   /* [temp.expl.spec]
600
601      An explicit specialization shall be declared in the namespace of
602      which the template is a member, or, for member templates, in the
603      namespace of which the enclosing class or enclosing class
604      template is a member.  An explicit specialization of a member
605      function, member class or static data member of a class template
606      shall be declared in the namespace of which the class template
607      is a member.  */
608   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
609     {
610       error ("explicit specialization in non-namespace scope %qD", scope);
611       return false;
612     }
613
614   /* [temp.expl.spec]
615
616      In an explicit specialization declaration for a member of a class
617      template or a member template that appears in namespace scope,
618      the member template and some of its enclosing class templates may
619      remain unspecialized, except that the declaration shall not
620      explicitly specialize a class member template if its enclosing
621      class templates are not explicitly specialized as well.  */
622   if (current_template_parms)
623     {
624       error ("enclosing class templates are not explicitly specialized");
625       return false;
626     }
627
628   return true;
629 }
630
631 /* We've just seen template <>.  */
632
633 bool
634 begin_specialization (void)
635 {
636   begin_scope (sk_template_spec, NULL);
637   note_template_header (1);
638   return check_specialization_scope ();
639 }
640
641 /* Called at then end of processing a declaration preceded by
642    template<>.  */
643
644 void
645 end_specialization (void)
646 {
647   finish_scope ();
648   reset_specialization ();
649 }
650
651 /* Any template <>'s that we have seen thus far are not referring to a
652    function specialization.  */
653
654 void
655 reset_specialization (void)
656 {
657   processing_specialization = 0;
658   template_header_count = 0;
659 }
660
661 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
662    it was of the form template <>.  */
663
664 static void
665 note_template_header (int specialization)
666 {
667   processing_specialization = specialization;
668   template_header_count++;
669 }
670
671 /* We're beginning an explicit instantiation.  */
672
673 void
674 begin_explicit_instantiation (void)
675 {
676   gcc_assert (!processing_explicit_instantiation);
677   processing_explicit_instantiation = true;
678 }
679
680
681 void
682 end_explicit_instantiation (void)
683 {
684   gcc_assert (processing_explicit_instantiation);
685   processing_explicit_instantiation = false;
686 }
687
688 /* An explicit specialization or partial specialization TMPL is being
689    declared.  Check that the namespace in which the specialization is
690    occurring is permissible.  Returns false iff it is invalid to
691    specialize TMPL in the current namespace.  */
692
693 static bool
694 check_specialization_namespace (tree tmpl)
695 {
696   tree tpl_ns = decl_namespace_context (tmpl);
697
698   /* [tmpl.expl.spec]
699
700      An explicit specialization shall be declared in the namespace of
701      which the template is a member, or, for member templates, in the
702      namespace of which the enclosing class or enclosing class
703      template is a member.  An explicit specialization of a member
704      function, member class or static data member of a class template
705      shall be declared in the namespace of which the class template is
706      a member.  */
707   if (is_associated_namespace (current_namespace, tpl_ns))
708     /* Same or super-using namespace.  */
709     return true;
710   else
711     {
712       pedwarn ("specialization of %qD in different namespace", tmpl);
713       pedwarn ("  from definition of %q+#D", tmpl);
714       return false;
715     }
716 }
717
718 /* SPEC is an explicit instantiation.  Check that it is valid to
719    perform this explicit instantiation in the current namespace.  */
720
721 static void
722 check_explicit_instantiation_namespace (tree spec)
723 {
724   tree ns;
725
726   /* DR 275: An explicit instantiation shall appear in an enclosing
727      namespace of its template.  */
728   ns = decl_namespace_context (spec);
729   if (!is_ancestor (current_namespace, ns))
730     pedwarn ("explicit instantiation of %qD in namespace %qD "
731              "(which does not enclose namespace %qD)",
732              spec, current_namespace, ns);
733 }
734
735 /* The TYPE is being declared.  If it is a template type, that means it
736    is a partial specialization.  Do appropriate error-checking.  */
737
738 tree
739 maybe_process_partial_specialization (tree type)
740 {
741   tree context;
742
743   if (type == error_mark_node)
744     return error_mark_node;
745
746   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
747     {
748       error ("name of class shadows template template parameter %qD",
749              TYPE_NAME (type));
750       return error_mark_node;
751     }
752
753   context = TYPE_CONTEXT (type);
754
755   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
756     {
757       /* This is for ordinary explicit specialization and partial
758          specialization of a template class such as:
759
760            template <> class C<int>;
761
762          or:
763
764            template <class T> class C<T*>;
765
766          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
767
768       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
769           && !COMPLETE_TYPE_P (type))
770         {
771           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
772           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
773           if (processing_template_decl)
774             push_template_decl (TYPE_MAIN_DECL (type));
775         }
776       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
777         error ("specialization of %qT after instantiation", type);
778     }
779   else if (CLASS_TYPE_P (type)
780            && !CLASSTYPE_USE_TEMPLATE (type)
781            && CLASSTYPE_TEMPLATE_INFO (type)
782            && context && CLASS_TYPE_P (context)
783            && CLASSTYPE_TEMPLATE_INFO (context))
784     {
785       /* This is for an explicit specialization of member class
786          template according to [temp.expl.spec/18]:
787
788            template <> template <class U> class C<int>::D;
789
790          The context `C<int>' must be an implicit instantiation.
791          Otherwise this is just a member class template declared
792          earlier like:
793
794            template <> class C<int> { template <class U> class D; };
795            template <> template <class U> class C<int>::D;
796
797          In the first case, `C<int>::D' is a specialization of `C<T>::D'
798          while in the second case, `C<int>::D' is a primary template
799          and `C<T>::D' may not exist.  */
800
801       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
802           && !COMPLETE_TYPE_P (type))
803         {
804           tree t;
805
806           if (current_namespace
807               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
808             {
809               pedwarn ("specializing %q#T in different namespace", type);
810               pedwarn ("  from definition of %q+#D",
811                        CLASSTYPE_TI_TEMPLATE (type));
812             }
813
814           /* Check for invalid specialization after instantiation:
815
816                template <> template <> class C<int>::D<int>;
817                template <> template <class U> class C<int>::D;  */
818
819           for (t = DECL_TEMPLATE_INSTANTIATIONS
820                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
821                t; t = TREE_CHAIN (t))
822             if (TREE_VALUE (t) != type
823                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
824               error ("specialization %qT after instantiation %qT",
825                      type, TREE_VALUE (t));
826
827           /* Mark TYPE as a specialization.  And as a result, we only
828              have one level of template argument for the innermost
829              class template.  */
830           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
831           CLASSTYPE_TI_ARGS (type)
832             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
833         }
834     }
835   else if (processing_specialization)
836     {
837       error ("explicit specialization of non-template %qT", type);
838       return error_mark_node;
839     }
840
841   return type;
842 }
843
844 /* Returns nonzero if we can optimize the retrieval of specializations
845    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
846    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
847
848 static inline bool
849 optimize_specialization_lookup_p (tree tmpl)
850 {
851   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
852           && DECL_CLASS_SCOPE_P (tmpl)
853           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
854              parameter.  */
855           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
856           /* The optimized lookup depends on the fact that the
857              template arguments for the member function template apply
858              purely to the containing class, which is not true if the
859              containing class is an explicit or partial
860              specialization.  */
861           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
862           && !DECL_MEMBER_TEMPLATE_P (tmpl)
863           && !DECL_CONV_FN_P (tmpl)
864           /* It is possible to have a template that is not a member
865              template and is not a member of a template class:
866
867              template <typename T>
868              struct S { friend A::f(); };
869
870              Here, the friend function is a template, but the context does
871              not have template information.  The optimized lookup relies
872              on having ARGS be the template arguments for both the class
873              and the function template.  */
874           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
875 }
876
877 /* Retrieve the specialization (in the sense of [temp.spec] - a
878    specialization is either an instantiation or an explicit
879    specialization) of TMPL for the given template ARGS.  If there is
880    no such specialization, return NULL_TREE.  The ARGS are a vector of
881    arguments, or a vector of vectors of arguments, in the case of
882    templates with more than one level of parameters.
883
884    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
885    then we search for a partial specialization matching ARGS.  This
886    parameter is ignored if TMPL is not a class template.  */
887
888 static tree
889 retrieve_specialization (tree tmpl, tree args,
890                          bool class_specializations_p)
891 {
892   if (args == error_mark_node)
893     return NULL_TREE;
894
895   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
896
897   /* There should be as many levels of arguments as there are
898      levels of parameters.  */
899   gcc_assert (TMPL_ARGS_DEPTH (args)
900               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
901
902   if (optimize_specialization_lookup_p (tmpl))
903     {
904       tree class_template;
905       tree class_specialization;
906       VEC(tree,gc) *methods;
907       tree fns;
908       int idx;
909
910       /* The template arguments actually apply to the containing
911          class.  Find the class specialization with those
912          arguments.  */
913       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
914       class_specialization
915         = retrieve_specialization (class_template, args,
916                                    /*class_specializations_p=*/false);
917       if (!class_specialization)
918         return NULL_TREE;
919       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
920          for the specialization.  */
921       idx = class_method_index_for_fn (class_specialization, tmpl);
922       if (idx == -1)
923         return NULL_TREE;
924       /* Iterate through the methods with the indicated name, looking
925          for the one that has an instance of TMPL.  */
926       methods = CLASSTYPE_METHOD_VEC (class_specialization);
927       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
928         {
929           tree fn = OVL_CURRENT (fns);
930           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
931             return fn;
932         }
933       return NULL_TREE;
934     }
935   else
936     {
937       tree *sp;
938       tree *head;
939
940       /* Class templates store their instantiations on the
941          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
942          DECL_TEMPLATE_SPECIALIZATIONS list.  */
943       if (!class_specializations_p
944           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL
945           && TAGGED_TYPE_P (TREE_TYPE (tmpl)))
946         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
947       else
948         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
949       head = sp;
950       /* Iterate through the list until we find a matching template.  */
951       while (*sp != NULL_TREE)
952         {
953           tree spec = *sp;
954
955           if (comp_template_args (TREE_PURPOSE (spec), args))
956             {
957               /* Use the move-to-front heuristic to speed up future
958                  searches.  */
959               if (spec != *head)
960                 {
961                   *sp = TREE_CHAIN (*sp);
962                   TREE_CHAIN (spec) = *head;
963                   *head = spec;
964                 }
965               return TREE_VALUE (spec);
966             }
967           sp = &TREE_CHAIN (spec);
968         }
969     }
970
971   return NULL_TREE;
972 }
973
974 /* Like retrieve_specialization, but for local declarations.  */
975
976 static tree
977 retrieve_local_specialization (tree tmpl)
978 {
979   tree spec;
980
981   if (local_specializations == NULL)
982     return NULL_TREE;
983
984   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
985                                      htab_hash_pointer (tmpl));
986   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
987 }
988
989 /* Returns nonzero iff DECL is a specialization of TMPL.  */
990
991 int
992 is_specialization_of (tree decl, tree tmpl)
993 {
994   tree t;
995
996   if (TREE_CODE (decl) == FUNCTION_DECL)
997     {
998       for (t = decl;
999            t != NULL_TREE;
1000            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1001         if (t == tmpl)
1002           return 1;
1003     }
1004   else
1005     {
1006       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1007
1008       for (t = TREE_TYPE (decl);
1009            t != NULL_TREE;
1010            t = CLASSTYPE_USE_TEMPLATE (t)
1011              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1012         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1013           return 1;
1014     }
1015
1016   return 0;
1017 }
1018
1019 /* Returns nonzero iff DECL is a specialization of friend declaration
1020    FRIEND according to [temp.friend].  */
1021
1022 bool
1023 is_specialization_of_friend (tree decl, tree friend)
1024 {
1025   bool need_template = true;
1026   int template_depth;
1027
1028   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1029               || TREE_CODE (decl) == TYPE_DECL);
1030
1031   /* For [temp.friend/6] when FRIEND is an ordinary member function
1032      of a template class, we want to check if DECL is a specialization
1033      if this.  */
1034   if (TREE_CODE (friend) == FUNCTION_DECL
1035       && DECL_TEMPLATE_INFO (friend)
1036       && !DECL_USE_TEMPLATE (friend))
1037     {
1038       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1039       friend = DECL_TI_TEMPLATE (friend);
1040       need_template = false;
1041     }
1042   else if (TREE_CODE (friend) == TEMPLATE_DECL
1043            && !PRIMARY_TEMPLATE_P (friend))
1044     need_template = false;
1045
1046   /* There is nothing to do if this is not a template friend.  */
1047   if (TREE_CODE (friend) != TEMPLATE_DECL)
1048     return false;
1049
1050   if (is_specialization_of (decl, friend))
1051     return true;
1052
1053   /* [temp.friend/6]
1054      A member of a class template may be declared to be a friend of a
1055      non-template class.  In this case, the corresponding member of
1056      every specialization of the class template is a friend of the
1057      class granting friendship.
1058
1059      For example, given a template friend declaration
1060
1061        template <class T> friend void A<T>::f();
1062
1063      the member function below is considered a friend
1064
1065        template <> struct A<int> {
1066          void f();
1067        };
1068
1069      For this type of template friend, TEMPLATE_DEPTH below will be
1070      nonzero.  To determine if DECL is a friend of FRIEND, we first
1071      check if the enclosing class is a specialization of another.  */
1072
1073   template_depth = template_class_depth (DECL_CONTEXT (friend));
1074   if (template_depth
1075       && DECL_CLASS_SCOPE_P (decl)
1076       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1077                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend))))
1078     {
1079       /* Next, we check the members themselves.  In order to handle
1080          a few tricky cases, such as when FRIEND's are
1081
1082            template <class T> friend void A<T>::g(T t);
1083            template <class T> template <T t> friend void A<T>::h();
1084
1085          and DECL's are
1086
1087            void A<int>::g(int);
1088            template <int> void A<int>::h();
1089
1090          we need to figure out ARGS, the template arguments from
1091          the context of DECL.  This is required for template substitution
1092          of `T' in the function parameter of `g' and template parameter
1093          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1094
1095       tree context = DECL_CONTEXT (decl);
1096       tree args = NULL_TREE;
1097       int current_depth = 0;
1098
1099       while (current_depth < template_depth)
1100         {
1101           if (CLASSTYPE_TEMPLATE_INFO (context))
1102             {
1103               if (current_depth == 0)
1104                 args = TYPE_TI_ARGS (context);
1105               else
1106                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1107               current_depth++;
1108             }
1109           context = TYPE_CONTEXT (context);
1110         }
1111
1112       if (TREE_CODE (decl) == FUNCTION_DECL)
1113         {
1114           bool is_template;
1115           tree friend_type;
1116           tree decl_type;
1117           tree friend_args_type;
1118           tree decl_args_type;
1119
1120           /* Make sure that both DECL and FRIEND are templates or
1121              non-templates.  */
1122           is_template = DECL_TEMPLATE_INFO (decl)
1123                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1124           if (need_template ^ is_template)
1125             return false;
1126           else if (is_template)
1127             {
1128               /* If both are templates, check template parameter list.  */
1129               tree friend_parms
1130                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1131                                          args, tf_none);
1132               if (!comp_template_parms
1133                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1134                       friend_parms))
1135                 return false;
1136
1137               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1138             }
1139           else
1140             decl_type = TREE_TYPE (decl);
1141
1142           friend_type = tsubst_function_type (TREE_TYPE (friend), args,
1143                                               tf_none, NULL_TREE);
1144           if (friend_type == error_mark_node)
1145             return false;
1146
1147           /* Check if return types match.  */
1148           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1149             return false;
1150
1151           /* Check if function parameter types match, ignoring the
1152              `this' parameter.  */
1153           friend_args_type = TYPE_ARG_TYPES (friend_type);
1154           decl_args_type = TYPE_ARG_TYPES (decl_type);
1155           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend))
1156             friend_args_type = TREE_CHAIN (friend_args_type);
1157           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1158             decl_args_type = TREE_CHAIN (decl_args_type);
1159
1160           return compparms (decl_args_type, friend_args_type);
1161         }
1162       else
1163         {
1164           /* DECL is a TYPE_DECL */
1165           bool is_template;
1166           tree decl_type = TREE_TYPE (decl);
1167
1168           /* Make sure that both DECL and FRIEND are templates or
1169              non-templates.  */
1170           is_template
1171             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1172               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1173
1174           if (need_template ^ is_template)
1175             return false;
1176           else if (is_template)
1177             {
1178               tree friend_parms;
1179               /* If both are templates, check the name of the two
1180                  TEMPLATE_DECL's first because is_friend didn't.  */
1181               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1182                   != DECL_NAME (friend))
1183                 return false;
1184
1185               /* Now check template parameter list.  */
1186               friend_parms
1187                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1188                                          args, tf_none);
1189               return comp_template_parms
1190                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1191                  friend_parms);
1192             }
1193           else
1194             return (DECL_NAME (decl)
1195                     == DECL_NAME (friend));
1196         }
1197     }
1198   return false;
1199 }
1200
1201 /* Register the specialization SPEC as a specialization of TMPL with
1202    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1203    is actually just a friend declaration.  Returns SPEC, or an
1204    equivalent prior declaration, if available.  */
1205
1206 static tree
1207 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1208 {
1209   tree fn;
1210
1211   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1212
1213   if (TREE_CODE (spec) == FUNCTION_DECL
1214       && uses_template_parms (DECL_TI_ARGS (spec)))
1215     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1216        register it; we want the corresponding TEMPLATE_DECL instead.
1217        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1218        the more obvious `uses_template_parms (spec)' to avoid problems
1219        with default function arguments.  In particular, given
1220        something like this:
1221
1222           template <class T> void f(T t1, T t = T())
1223
1224        the default argument expression is not substituted for in an
1225        instantiation unless and until it is actually needed.  */
1226     return spec;
1227
1228   fn = retrieve_specialization (tmpl, args,
1229                                 /*class_specializations_p=*/false);
1230   /* We can sometimes try to re-register a specialization that we've
1231      already got.  In particular, regenerate_decl_from_template calls
1232      duplicate_decls which will update the specialization list.  But,
1233      we'll still get called again here anyhow.  It's more convenient
1234      to simply allow this than to try to prevent it.  */
1235   if (fn == spec)
1236     return spec;
1237   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1238     {
1239       if (DECL_TEMPLATE_INSTANTIATION (fn))
1240         {
1241           if (TREE_USED (fn)
1242               || DECL_EXPLICIT_INSTANTIATION (fn))
1243             {
1244               error ("specialization of %qD after instantiation",
1245                      fn);
1246               return error_mark_node;
1247             }
1248           else
1249             {
1250               tree clone;
1251               /* This situation should occur only if the first
1252                  specialization is an implicit instantiation, the
1253                  second is an explicit specialization, and the
1254                  implicit instantiation has not yet been used.  That
1255                  situation can occur if we have implicitly
1256                  instantiated a member function and then specialized
1257                  it later.
1258
1259                  We can also wind up here if a friend declaration that
1260                  looked like an instantiation turns out to be a
1261                  specialization:
1262
1263                    template <class T> void foo(T);
1264                    class S { friend void foo<>(int) };
1265                    template <> void foo(int);
1266
1267                  We transform the existing DECL in place so that any
1268                  pointers to it become pointers to the updated
1269                  declaration.
1270
1271                  If there was a definition for the template, but not
1272                  for the specialization, we want this to look as if
1273                  there were no definition, and vice versa.  */
1274               DECL_INITIAL (fn) = NULL_TREE;
1275               duplicate_decls (spec, fn, is_friend);
1276               /* The call to duplicate_decls will have applied
1277                  [temp.expl.spec]:
1278
1279                    An explicit specialization of a function template
1280                    is inline only if it is explicitly declared to be,
1281                    and independently of whether its function template
1282                    is.
1283
1284                 to the primary function; now copy the inline bits to
1285                 the various clones.  */
1286               FOR_EACH_CLONE (clone, fn)
1287                 {
1288                   DECL_DECLARED_INLINE_P (clone)
1289                     = DECL_DECLARED_INLINE_P (fn);
1290                   DECL_INLINE (clone)
1291                     = DECL_INLINE (fn);
1292                 }
1293               check_specialization_namespace (fn);
1294
1295               return fn;
1296             }
1297         }
1298       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1299         {
1300           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1301             /* Dup decl failed, but this is a new definition. Set the
1302                line number so any errors match this new
1303                definition.  */
1304             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1305
1306           return fn;
1307         }
1308     }
1309
1310   /* A specialization must be declared in the same namespace as the
1311      template it is specializing.  */
1312   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1313       && !check_specialization_namespace (tmpl))
1314     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1315
1316   if (!optimize_specialization_lookup_p (tmpl))
1317     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1318       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1319
1320   return spec;
1321 }
1322
1323 /* Unregister the specialization SPEC as a specialization of TMPL.
1324    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1325    if the SPEC was listed as a specialization of TMPL.  */
1326
1327 bool
1328 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1329 {
1330   tree* s;
1331
1332   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1333        *s != NULL_TREE;
1334        s = &TREE_CHAIN (*s))
1335     if (TREE_VALUE (*s) == spec)
1336       {
1337         if (!new_spec)
1338           *s = TREE_CHAIN (*s);
1339         else
1340           TREE_VALUE (*s) = new_spec;
1341         return 1;
1342       }
1343
1344   return 0;
1345 }
1346
1347 /* Compare an entry in the local specializations hash table P1 (which
1348    is really a pointer to a TREE_LIST) with P2 (which is really a
1349    DECL).  */
1350
1351 static int
1352 eq_local_specializations (const void *p1, const void *p2)
1353 {
1354   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1355 }
1356
1357 /* Hash P1, an entry in the local specializations table.  */
1358
1359 static hashval_t
1360 hash_local_specialization (const void* p1)
1361 {
1362   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1363 }
1364
1365 /* Like register_specialization, but for local declarations.  We are
1366    registering SPEC, an instantiation of TMPL.  */
1367
1368 static void
1369 register_local_specialization (tree spec, tree tmpl)
1370 {
1371   void **slot;
1372
1373   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1374                                    htab_hash_pointer (tmpl), INSERT);
1375   *slot = build_tree_list (spec, tmpl);
1376 }
1377
1378 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1379    specialized class.  */
1380
1381 bool
1382 explicit_class_specialization_p (tree type)
1383 {
1384   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1385     return false;
1386   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1387 }
1388
1389 /* Print the list of candidate FNS in an error message.  */
1390
1391 void
1392 print_candidates (tree fns)
1393 {
1394   tree fn;
1395
1396   const char *str = "candidates are:";
1397
1398   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1399     {
1400       tree f;
1401
1402       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1403         error ("%s %+#D", str, OVL_CURRENT (f));
1404       str = "               ";
1405     }
1406 }
1407
1408 /* Returns the template (one of the functions given by TEMPLATE_ID)
1409    which can be specialized to match the indicated DECL with the
1410    explicit template args given in TEMPLATE_ID.  The DECL may be
1411    NULL_TREE if none is available.  In that case, the functions in
1412    TEMPLATE_ID are non-members.
1413
1414    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1415    specialization of a member template.
1416
1417    The TEMPLATE_COUNT is the number of references to qualifying
1418    template classes that appeared in the name of the function. See
1419    check_explicit_specialization for a more accurate description.
1420
1421    TSK indicates what kind of template declaration (if any) is being
1422    declared.  TSK_TEMPLATE indicates that the declaration given by
1423    DECL, though a FUNCTION_DECL, has template parameters, and is
1424    therefore a template function.
1425
1426    The template args (those explicitly specified and those deduced)
1427    are output in a newly created vector *TARGS_OUT.
1428
1429    If it is impossible to determine the result, an error message is
1430    issued.  The error_mark_node is returned to indicate failure.  */
1431
1432 static tree
1433 determine_specialization (tree template_id,
1434                           tree decl,
1435                           tree* targs_out,
1436                           int need_member_template,
1437                           int template_count,
1438                           tmpl_spec_kind tsk)
1439 {
1440   tree fns;
1441   tree targs;
1442   tree explicit_targs;
1443   tree candidates = NULL_TREE;
1444   /* A TREE_LIST of templates of which DECL may be a specialization.
1445      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1446      corresponding TREE_PURPOSE is the set of template arguments that,
1447      when used to instantiate the template, would produce a function
1448      with the signature of DECL.  */
1449   tree templates = NULL_TREE;
1450   int header_count;
1451   struct cp_binding_level *b;
1452
1453   *targs_out = NULL_TREE;
1454
1455   if (template_id == error_mark_node || decl == error_mark_node)
1456     return error_mark_node;
1457
1458   fns = TREE_OPERAND (template_id, 0);
1459   explicit_targs = TREE_OPERAND (template_id, 1);
1460
1461   if (fns == error_mark_node)
1462     return error_mark_node;
1463
1464   /* Check for baselinks.  */
1465   if (BASELINK_P (fns))
1466     fns = BASELINK_FUNCTIONS (fns);
1467
1468   if (!is_overloaded_fn (fns))
1469     {
1470       error ("%qD is not a function template", fns);
1471       return error_mark_node;
1472     }
1473
1474   /* Count the number of template headers specified for this
1475      specialization.  */
1476   header_count = 0;
1477   for (b = current_binding_level;
1478        b->kind == sk_template_parms;
1479        b = b->level_chain)
1480     ++header_count;
1481
1482   for (; fns; fns = OVL_NEXT (fns))
1483     {
1484       tree fn = OVL_CURRENT (fns);
1485
1486       if (TREE_CODE (fn) == TEMPLATE_DECL)
1487         {
1488           tree decl_arg_types;
1489           tree fn_arg_types;
1490
1491           /* In case of explicit specialization, we need to check if
1492              the number of template headers appearing in the specialization
1493              is correct. This is usually done in check_explicit_specialization,
1494              but the check done there cannot be exhaustive when specializing
1495              member functions. Consider the following code:
1496
1497              template <> void A<int>::f(int);
1498              template <> template <> void A<int>::f(int);
1499
1500              Assuming that A<int> is not itself an explicit specialization
1501              already, the first line specializes "f" which is a non-template
1502              member function, whilst the second line specializes "f" which
1503              is a template member function. So both lines are syntactically
1504              correct, and check_explicit_specialization does not reject
1505              them.
1506
1507              Here, we can do better, as we are matching the specialization
1508              against the declarations. We count the number of template
1509              headers, and we check if they match TEMPLATE_COUNT + 1
1510              (TEMPLATE_COUNT is the number of qualifying template classes,
1511              plus there must be another header for the member template
1512              itself).
1513
1514              Notice that if header_count is zero, this is not a
1515              specialization but rather a template instantiation, so there
1516              is no check we can perform here.  */
1517           if (header_count && header_count != template_count + 1)
1518             continue;
1519
1520           /* Check that the number of template arguments at the
1521              innermost level for DECL is the same as for FN.  */
1522           if (current_binding_level->kind == sk_template_parms
1523               && !current_binding_level->explicit_spec_p
1524               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1525                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1526                                       (current_template_parms))))
1527             continue;
1528
1529           /* DECL might be a specialization of FN.  */
1530           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1531           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1532
1533           /* For a non-static member function, we need to make sure
1534              that the const qualification is the same.  Since
1535              get_bindings does not try to merge the "this" parameter,
1536              we must do the comparison explicitly.  */
1537           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1538               && !same_type_p (TREE_VALUE (fn_arg_types),
1539                                TREE_VALUE (decl_arg_types)))
1540             continue;
1541
1542           /* Skip the "this" parameter and, for constructors of
1543              classes with virtual bases, the VTT parameter.  A
1544              full specialization of a constructor will have a VTT
1545              parameter, but a template never will.  */ 
1546           decl_arg_types 
1547             = skip_artificial_parms_for (decl, decl_arg_types);
1548           fn_arg_types 
1549             = skip_artificial_parms_for (fn, fn_arg_types);
1550
1551           /* Check that the number of function parameters matches.
1552              For example,
1553                template <class T> void f(int i = 0);
1554                template <> void f<int>();
1555              The specialization f<int> is invalid but is not caught
1556              by get_bindings below.  */
1557           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1558             continue;
1559
1560           /* Function templates cannot be specializations; there are
1561              no partial specializations of functions.  Therefore, if
1562              the type of DECL does not match FN, there is no
1563              match.  */
1564           if (tsk == tsk_template)
1565             {
1566               if (compparms (fn_arg_types, decl_arg_types))
1567                 candidates = tree_cons (NULL_TREE, fn, candidates);
1568               continue;
1569             }
1570
1571           /* See whether this function might be a specialization of this
1572              template.  */
1573           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1574
1575           if (!targs)
1576             /* We cannot deduce template arguments that when used to
1577                specialize TMPL will produce DECL.  */
1578             continue;
1579
1580           /* Save this template, and the arguments deduced.  */
1581           templates = tree_cons (targs, fn, templates);
1582         }
1583       else if (need_member_template)
1584         /* FN is an ordinary member function, and we need a
1585            specialization of a member template.  */
1586         ;
1587       else if (TREE_CODE (fn) != FUNCTION_DECL)
1588         /* We can get IDENTIFIER_NODEs here in certain erroneous
1589            cases.  */
1590         ;
1591       else if (!DECL_FUNCTION_MEMBER_P (fn))
1592         /* This is just an ordinary non-member function.  Nothing can
1593            be a specialization of that.  */
1594         ;
1595       else if (DECL_ARTIFICIAL (fn))
1596         /* Cannot specialize functions that are created implicitly.  */
1597         ;
1598       else
1599         {
1600           tree decl_arg_types;
1601
1602           /* This is an ordinary member function.  However, since
1603              we're here, we can assume it's enclosing class is a
1604              template class.  For example,
1605
1606                template <typename T> struct S { void f(); };
1607                template <> void S<int>::f() {}
1608
1609              Here, S<int>::f is a non-template, but S<int> is a
1610              template class.  If FN has the same type as DECL, we
1611              might be in business.  */
1612
1613           if (!DECL_TEMPLATE_INFO (fn))
1614             /* Its enclosing class is an explicit specialization
1615                of a template class.  This is not a candidate.  */
1616             continue;
1617
1618           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1619                             TREE_TYPE (TREE_TYPE (fn))))
1620             /* The return types differ.  */
1621             continue;
1622
1623           /* Adjust the type of DECL in case FN is a static member.  */
1624           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1625           if (DECL_STATIC_FUNCTION_P (fn)
1626               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1627             decl_arg_types = TREE_CHAIN (decl_arg_types);
1628
1629           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1630                          decl_arg_types))
1631             /* They match!  */
1632             candidates = tree_cons (NULL_TREE, fn, candidates);
1633         }
1634     }
1635
1636   if (templates && TREE_CHAIN (templates))
1637     {
1638       /* We have:
1639
1640            [temp.expl.spec]
1641
1642            It is possible for a specialization with a given function
1643            signature to be instantiated from more than one function
1644            template.  In such cases, explicit specification of the
1645            template arguments must be used to uniquely identify the
1646            function template specialization being specialized.
1647
1648          Note that here, there's no suggestion that we're supposed to
1649          determine which of the candidate templates is most
1650          specialized.  However, we, also have:
1651
1652            [temp.func.order]
1653
1654            Partial ordering of overloaded function template
1655            declarations is used in the following contexts to select
1656            the function template to which a function template
1657            specialization refers:
1658
1659            -- when an explicit specialization refers to a function
1660               template.
1661
1662          So, we do use the partial ordering rules, at least for now.
1663          This extension can only serve to make invalid programs valid,
1664          so it's safe.  And, there is strong anecdotal evidence that
1665          the committee intended the partial ordering rules to apply;
1666          the EDG front end has that behavior, and John Spicer claims
1667          that the committee simply forgot to delete the wording in
1668          [temp.expl.spec].  */
1669       tree tmpl = most_specialized_instantiation (templates);
1670       if (tmpl != error_mark_node)
1671         {
1672           templates = tmpl;
1673           TREE_CHAIN (templates) = NULL_TREE;
1674         }
1675     }
1676
1677   if (templates == NULL_TREE && candidates == NULL_TREE)
1678     {
1679       error ("template-id %qD for %q+D does not match any template "
1680              "declaration", template_id, decl);
1681       return error_mark_node;
1682     }
1683   else if ((templates && TREE_CHAIN (templates))
1684            || (candidates && TREE_CHAIN (candidates))
1685            || (templates && candidates))
1686     {
1687       error ("ambiguous template specialization %qD for %q+D",
1688              template_id, decl);
1689       chainon (candidates, templates);
1690       print_candidates (candidates);
1691       return error_mark_node;
1692     }
1693
1694   /* We have one, and exactly one, match.  */
1695   if (candidates)
1696     {
1697       tree fn = TREE_VALUE (candidates);
1698       /* DECL is a re-declaration of a template function.  */
1699       if (TREE_CODE (fn) == TEMPLATE_DECL)
1700         return fn;
1701       /* It was a specialization of an ordinary member function in a
1702          template class.  */
1703       *targs_out = copy_node (DECL_TI_ARGS (fn));
1704       return DECL_TI_TEMPLATE (fn);
1705     }
1706
1707   /* It was a specialization of a template.  */
1708   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1709   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1710     {
1711       *targs_out = copy_node (targs);
1712       SET_TMPL_ARGS_LEVEL (*targs_out,
1713                            TMPL_ARGS_DEPTH (*targs_out),
1714                            TREE_PURPOSE (templates));
1715     }
1716   else
1717     *targs_out = TREE_PURPOSE (templates);
1718   return TREE_VALUE (templates);
1719 }
1720
1721 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1722    but with the default argument values filled in from those in the
1723    TMPL_TYPES.  */
1724
1725 static tree
1726 copy_default_args_to_explicit_spec_1 (tree spec_types,
1727                                       tree tmpl_types)
1728 {
1729   tree new_spec_types;
1730
1731   if (!spec_types)
1732     return NULL_TREE;
1733
1734   if (spec_types == void_list_node)
1735     return void_list_node;
1736
1737   /* Substitute into the rest of the list.  */
1738   new_spec_types =
1739     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1740                                           TREE_CHAIN (tmpl_types));
1741
1742   /* Add the default argument for this parameter.  */
1743   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1744                          TREE_VALUE (spec_types),
1745                          new_spec_types);
1746 }
1747
1748 /* DECL is an explicit specialization.  Replicate default arguments
1749    from the template it specializes.  (That way, code like:
1750
1751      template <class T> void f(T = 3);
1752      template <> void f(double);
1753      void g () { f (); }
1754
1755    works, as required.)  An alternative approach would be to look up
1756    the correct default arguments at the call-site, but this approach
1757    is consistent with how implicit instantiations are handled.  */
1758
1759 static void
1760 copy_default_args_to_explicit_spec (tree decl)
1761 {
1762   tree tmpl;
1763   tree spec_types;
1764   tree tmpl_types;
1765   tree new_spec_types;
1766   tree old_type;
1767   tree new_type;
1768   tree t;
1769   tree object_type = NULL_TREE;
1770   tree in_charge = NULL_TREE;
1771   tree vtt = NULL_TREE;
1772
1773   /* See if there's anything we need to do.  */
1774   tmpl = DECL_TI_TEMPLATE (decl);
1775   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1776   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1777     if (TREE_PURPOSE (t))
1778       break;
1779   if (!t)
1780     return;
1781
1782   old_type = TREE_TYPE (decl);
1783   spec_types = TYPE_ARG_TYPES (old_type);
1784
1785   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1786     {
1787       /* Remove the this pointer, but remember the object's type for
1788          CV quals.  */
1789       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1790       spec_types = TREE_CHAIN (spec_types);
1791       tmpl_types = TREE_CHAIN (tmpl_types);
1792
1793       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1794         {
1795           /* DECL may contain more parameters than TMPL due to the extra
1796              in-charge parameter in constructors and destructors.  */
1797           in_charge = spec_types;
1798           spec_types = TREE_CHAIN (spec_types);
1799         }
1800       if (DECL_HAS_VTT_PARM_P (decl))
1801         {
1802           vtt = spec_types;
1803           spec_types = TREE_CHAIN (spec_types);
1804         }
1805     }
1806
1807   /* Compute the merged default arguments.  */
1808   new_spec_types =
1809     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1810
1811   /* Compute the new FUNCTION_TYPE.  */
1812   if (object_type)
1813     {
1814       if (vtt)
1815         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1816                                          TREE_VALUE (vtt),
1817                                          new_spec_types);
1818
1819       if (in_charge)
1820         /* Put the in-charge parameter back.  */
1821         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1822                                          TREE_VALUE (in_charge),
1823                                          new_spec_types);
1824
1825       new_type = build_method_type_directly (object_type,
1826                                              TREE_TYPE (old_type),
1827                                              new_spec_types);
1828     }
1829   else
1830     new_type = build_function_type (TREE_TYPE (old_type),
1831                                     new_spec_types);
1832   new_type = cp_build_type_attribute_variant (new_type,
1833                                               TYPE_ATTRIBUTES (old_type));
1834   new_type = build_exception_variant (new_type,
1835                                       TYPE_RAISES_EXCEPTIONS (old_type));
1836   TREE_TYPE (decl) = new_type;
1837 }
1838
1839 /* Check to see if the function just declared, as indicated in
1840    DECLARATOR, and in DECL, is a specialization of a function
1841    template.  We may also discover that the declaration is an explicit
1842    instantiation at this point.
1843
1844    Returns DECL, or an equivalent declaration that should be used
1845    instead if all goes well.  Issues an error message if something is
1846    amiss.  Returns error_mark_node if the error is not easily
1847    recoverable.
1848
1849    FLAGS is a bitmask consisting of the following flags:
1850
1851    2: The function has a definition.
1852    4: The function is a friend.
1853
1854    The TEMPLATE_COUNT is the number of references to qualifying
1855    template classes that appeared in the name of the function.  For
1856    example, in
1857
1858      template <class T> struct S { void f(); };
1859      void S<int>::f();
1860
1861    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1862    classes are not counted in the TEMPLATE_COUNT, so that in
1863
1864      template <class T> struct S {};
1865      template <> struct S<int> { void f(); }
1866      template <> void S<int>::f();
1867
1868    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1869    invalid; there should be no template <>.)
1870
1871    If the function is a specialization, it is marked as such via
1872    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1873    is set up correctly, and it is added to the list of specializations
1874    for that template.  */
1875
1876 tree
1877 check_explicit_specialization (tree declarator,
1878                                tree decl,
1879                                int template_count,
1880                                int flags)
1881 {
1882   int have_def = flags & 2;
1883   int is_friend = flags & 4;
1884   int specialization = 0;
1885   int explicit_instantiation = 0;
1886   int member_specialization = 0;
1887   tree ctype = DECL_CLASS_CONTEXT (decl);
1888   tree dname = DECL_NAME (decl);
1889   tmpl_spec_kind tsk;
1890
1891   if (is_friend)
1892     {
1893       if (!processing_specialization)
1894         tsk = tsk_none;
1895       else
1896         tsk = tsk_excessive_parms;
1897     }
1898   else
1899     tsk = current_tmpl_spec_kind (template_count);
1900
1901   switch (tsk)
1902     {
1903     case tsk_none:
1904       if (processing_specialization)
1905         {
1906           specialization = 1;
1907           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1908         }
1909       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1910         {
1911           if (is_friend)
1912             /* This could be something like:
1913
1914                template <class T> void f(T);
1915                class S { friend void f<>(int); }  */
1916             specialization = 1;
1917           else
1918             {
1919               /* This case handles bogus declarations like template <>
1920                  template <class T> void f<int>(); */
1921
1922               error ("template-id %qD in declaration of primary template",
1923                      declarator);
1924               return decl;
1925             }
1926         }
1927       break;
1928
1929     case tsk_invalid_member_spec:
1930       /* The error has already been reported in
1931          check_specialization_scope.  */
1932       return error_mark_node;
1933
1934     case tsk_invalid_expl_inst:
1935       error ("template parameter list used in explicit instantiation");
1936
1937       /* Fall through.  */
1938
1939     case tsk_expl_inst:
1940       if (have_def)
1941         error ("definition provided for explicit instantiation");
1942
1943       explicit_instantiation = 1;
1944       break;
1945
1946     case tsk_excessive_parms:
1947     case tsk_insufficient_parms:
1948       if (tsk == tsk_excessive_parms)
1949         error ("too many template parameter lists in declaration of %qD",
1950                decl);
1951       else if (template_header_count)
1952         error("too few template parameter lists in declaration of %qD", decl);
1953       else
1954         error("explicit specialization of %qD must be introduced by "
1955               "%<template <>%>", decl);
1956
1957       /* Fall through.  */
1958     case tsk_expl_spec:
1959       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1960       if (ctype)
1961         member_specialization = 1;
1962       else
1963         specialization = 1;
1964       break;
1965
1966     case tsk_template:
1967       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1968         {
1969           /* This case handles bogus declarations like template <>
1970              template <class T> void f<int>(); */
1971
1972           if (uses_template_parms (declarator))
1973             error ("function template partial specialization %qD "
1974                    "is not allowed", declarator);
1975           else
1976             error ("template-id %qD in declaration of primary template",
1977                    declarator);
1978           return decl;
1979         }
1980
1981       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1982         /* This is a specialization of a member template, without
1983            specialization the containing class.  Something like:
1984
1985              template <class T> struct S {
1986                template <class U> void f (U);
1987              };
1988              template <> template <class U> void S<int>::f(U) {}
1989
1990            That's a specialization -- but of the entire template.  */
1991         specialization = 1;
1992       break;
1993
1994     default:
1995       gcc_unreachable ();
1996     }
1997
1998   if (specialization || member_specialization)
1999     {
2000       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2001       for (; t; t = TREE_CHAIN (t))
2002         if (TREE_PURPOSE (t))
2003           {
2004             pedwarn
2005               ("default argument specified in explicit specialization");
2006             break;
2007           }
2008     }
2009
2010   if (specialization || member_specialization || explicit_instantiation)
2011     {
2012       tree tmpl = NULL_TREE;
2013       tree targs = NULL_TREE;
2014
2015       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2016       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2017         {
2018           tree fns;
2019
2020           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2021           if (ctype)
2022             fns = dname;
2023           else
2024             {
2025               /* If there is no class context, the explicit instantiation
2026                  must be at namespace scope.  */
2027               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2028
2029               /* Find the namespace binding, using the declaration
2030                  context.  */
2031               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2032                                            false, true);
2033               if (fns == error_mark_node || !is_overloaded_fn (fns))
2034                 {
2035                   error ("%qD is not a template function", dname);
2036                   fns = error_mark_node;
2037                 }
2038               else
2039                 {
2040                   tree fn = OVL_CURRENT (fns);
2041                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2042                                                 CP_DECL_CONTEXT (fn)))
2043                     error ("%qD is not declared in %qD",
2044                            decl, current_namespace);
2045                 }
2046             }
2047
2048           declarator = lookup_template_function (fns, NULL_TREE);
2049         }
2050
2051       if (declarator == error_mark_node)
2052         return error_mark_node;
2053
2054       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2055         {
2056           if (!explicit_instantiation)
2057             /* A specialization in class scope.  This is invalid,
2058                but the error will already have been flagged by
2059                check_specialization_scope.  */
2060             return error_mark_node;
2061           else
2062             {
2063               /* It's not valid to write an explicit instantiation in
2064                  class scope, e.g.:
2065
2066                    class C { template void f(); }
2067
2068                    This case is caught by the parser.  However, on
2069                    something like:
2070
2071                    template class C { void f(); };
2072
2073                    (which is invalid) we can get here.  The error will be
2074                    issued later.  */
2075               ;
2076             }
2077
2078           return decl;
2079         }
2080       else if (ctype != NULL_TREE
2081                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2082                    IDENTIFIER_NODE))
2083         {
2084           /* Find the list of functions in ctype that have the same
2085              name as the declared function.  */
2086           tree name = TREE_OPERAND (declarator, 0);
2087           tree fns = NULL_TREE;
2088           int idx;
2089
2090           if (constructor_name_p (name, ctype))
2091             {
2092               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2093
2094               if (is_constructor ? !TYPE_HAS_CONSTRUCTOR (ctype)
2095                   : !CLASSTYPE_DESTRUCTORS (ctype))
2096                 {
2097                   /* From [temp.expl.spec]:
2098
2099                      If such an explicit specialization for the member
2100                      of a class template names an implicitly-declared
2101                      special member function (clause _special_), the
2102                      program is ill-formed.
2103
2104                      Similar language is found in [temp.explicit].  */
2105                   error ("specialization of implicitly-declared special member function");
2106                   return error_mark_node;
2107                 }
2108
2109               name = is_constructor ? ctor_identifier : dtor_identifier;
2110             }
2111
2112           if (!DECL_CONV_FN_P (decl))
2113             {
2114               idx = lookup_fnfields_1 (ctype, name);
2115               if (idx >= 0)
2116                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2117             }
2118           else
2119             {
2120               VEC(tree,gc) *methods;
2121               tree ovl;
2122
2123               /* For a type-conversion operator, we cannot do a
2124                  name-based lookup.  We might be looking for `operator
2125                  int' which will be a specialization of `operator T'.
2126                  So, we find *all* the conversion operators, and then
2127                  select from them.  */
2128               fns = NULL_TREE;
2129
2130               methods = CLASSTYPE_METHOD_VEC (ctype);
2131               if (methods)
2132                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2133                      VEC_iterate (tree, methods, idx, ovl);
2134                      ++idx)
2135                   {
2136                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2137                       /* There are no more conversion functions.  */
2138                       break;
2139
2140                     /* Glue all these conversion functions together
2141                        with those we already have.  */
2142                     for (; ovl; ovl = OVL_NEXT (ovl))
2143                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2144                   }
2145             }
2146
2147           if (fns == NULL_TREE)
2148             {
2149               error ("no member function %qD declared in %qT", name, ctype);
2150               return error_mark_node;
2151             }
2152           else
2153             TREE_OPERAND (declarator, 0) = fns;
2154         }
2155
2156       /* Figure out what exactly is being specialized at this point.
2157          Note that for an explicit instantiation, even one for a
2158          member function, we cannot tell apriori whether the
2159          instantiation is for a member template, or just a member
2160          function of a template class.  Even if a member template is
2161          being instantiated, the member template arguments may be
2162          elided if they can be deduced from the rest of the
2163          declaration.  */
2164       tmpl = determine_specialization (declarator, decl,
2165                                        &targs,
2166                                        member_specialization,
2167                                        template_count,
2168                                        tsk);
2169
2170       if (!tmpl || tmpl == error_mark_node)
2171         /* We couldn't figure out what this declaration was
2172            specializing.  */
2173         return error_mark_node;
2174       else
2175         {
2176           tree gen_tmpl = most_general_template (tmpl);
2177
2178           if (explicit_instantiation)
2179             {
2180               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2181                  is done by do_decl_instantiation later.  */
2182
2183               int arg_depth = TMPL_ARGS_DEPTH (targs);
2184               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2185
2186               if (arg_depth > parm_depth)
2187                 {
2188                   /* If TMPL is not the most general template (for
2189                      example, if TMPL is a friend template that is
2190                      injected into namespace scope), then there will
2191                      be too many levels of TARGS.  Remove some of them
2192                      here.  */
2193                   int i;
2194                   tree new_targs;
2195
2196                   new_targs = make_tree_vec (parm_depth);
2197                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2198                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2199                       = TREE_VEC_ELT (targs, i);
2200                   targs = new_targs;
2201                 }
2202
2203               return instantiate_template (tmpl, targs, tf_error);
2204             }
2205
2206           /* If we thought that the DECL was a member function, but it
2207              turns out to be specializing a static member function,
2208              make DECL a static member function as well.  */
2209           if (DECL_STATIC_FUNCTION_P (tmpl)
2210               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2211             revert_static_member_fn (decl);
2212
2213           /* If this is a specialization of a member template of a
2214              template class, we want to return the TEMPLATE_DECL, not
2215              the specialization of it.  */
2216           if (tsk == tsk_template)
2217             {
2218               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2219               DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl)) = NULL_TREE;
2220               if (have_def)
2221                 {
2222                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2223                   DECL_SOURCE_LOCATION (DECL_TEMPLATE_RESULT (tmpl))
2224                     = DECL_SOURCE_LOCATION (decl);
2225                   /* We want to use the argument list specified in the
2226                      definition, not in the original declaration.  */
2227                   DECL_ARGUMENTS (DECL_TEMPLATE_RESULT (tmpl))
2228                     = DECL_ARGUMENTS (decl);
2229                 }
2230               return tmpl;
2231             }
2232
2233           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2234           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2235
2236           /* Inherit default function arguments from the template
2237              DECL is specializing.  */
2238           copy_default_args_to_explicit_spec (decl);
2239
2240           /* This specialization has the same protection as the
2241              template it specializes.  */
2242           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2243           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2244
2245           /* 7.1.1-1 [dcl.stc]
2246
2247              A storage-class-specifier shall not be specified in an
2248              explicit specialization...
2249
2250              The parser rejects these, so unless action is taken here,
2251              explicit function specializations will always appear with
2252              global linkage.
2253
2254              The action recommended by the C++ CWG in response to C++
2255              defect report 605 is to make the storage class and linkage
2256              of the explicit specialization match the templated function:
2257
2258              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2259            */
2260           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2261             {
2262               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2263               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2264
2265               /* This specialization has the same linkage and visibility as
2266                  the function template it specializes.  */
2267               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2268               if (! TREE_PUBLIC (decl))
2269                 {
2270                   DECL_INTERFACE_KNOWN (decl) = 1;
2271                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2272                 }
2273               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2274               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2275                 {
2276                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2277                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2278                 }
2279             }
2280
2281           /* If DECL is a friend declaration, declared using an
2282              unqualified name, the namespace associated with DECL may
2283              have been set incorrectly.  For example, in:
2284
2285                template <typename T> void f(T);
2286                namespace N {
2287                  struct S { friend void f<int>(int); }
2288                }
2289
2290              we will have set the DECL_CONTEXT for the friend
2291              declaration to N, rather than to the global namespace.  */
2292           if (DECL_NAMESPACE_SCOPE_P (decl))
2293             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2294
2295           if (is_friend && !have_def)
2296             /* This is not really a declaration of a specialization.
2297                It's just the name of an instantiation.  But, it's not
2298                a request for an instantiation, either.  */
2299             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2300           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2301             /* This is indeed a specialization.  In case of constructors
2302                and destructors, we need in-charge and not-in-charge
2303                versions in V3 ABI.  */
2304             clone_function_decl (decl, /*update_method_vec_p=*/0);
2305
2306           /* Register this specialization so that we can find it
2307              again.  */
2308           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2309         }
2310     }
2311
2312   return decl;
2313 }
2314
2315 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2316    parameters.  These are represented in the same format used for
2317    DECL_TEMPLATE_PARMS.  */
2318
2319 int
2320 comp_template_parms (const_tree parms1, const_tree parms2)
2321 {
2322   const_tree p1;
2323   const_tree p2;
2324
2325   if (parms1 == parms2)
2326     return 1;
2327
2328   for (p1 = parms1, p2 = parms2;
2329        p1 != NULL_TREE && p2 != NULL_TREE;
2330        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2331     {
2332       tree t1 = TREE_VALUE (p1);
2333       tree t2 = TREE_VALUE (p2);
2334       int i;
2335
2336       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2337       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2338
2339       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2340         return 0;
2341
2342       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2343         {
2344           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2345           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2346
2347           /* If either of the template parameters are invalid, assume
2348              they match for the sake of error recovery. */
2349           if (parm1 == error_mark_node || parm2 == error_mark_node)
2350             return 1;
2351
2352           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2353             return 0;
2354
2355           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2356               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2357                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2358             continue;
2359           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2360             return 0;
2361         }
2362     }
2363
2364   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2365     /* One set of parameters has more parameters lists than the
2366        other.  */
2367     return 0;
2368
2369   return 1;
2370 }
2371
2372 /* Determine whether PARM is a parameter pack.  */
2373 bool 
2374 template_parameter_pack_p (const_tree parm)
2375 {
2376   /* Determine if we have a non-type template parameter pack.  */
2377   if (TREE_CODE (parm) == PARM_DECL)
2378     return (DECL_TEMPLATE_PARM_P (parm) 
2379             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2380
2381   /* If this is a list of template parameters, we could get a
2382      TYPE_DECL or a TEMPLATE_DECL.  */ 
2383   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2384     parm = TREE_TYPE (parm);
2385
2386   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2387            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2388           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2389 }
2390
2391 /* Determine whether ARGS describes a variadic template args list,
2392    i.e., one that is terminated by a template argument pack.  */
2393 static bool 
2394 template_args_variadic_p (tree args)
2395 {
2396   int nargs;
2397   tree last_parm;
2398
2399   if (args == NULL_TREE)
2400     return false;
2401
2402   args = INNERMOST_TEMPLATE_ARGS (args);
2403   nargs = TREE_VEC_LENGTH (args);
2404
2405   if (nargs == 0)
2406     return false;
2407
2408   last_parm = TREE_VEC_ELT (args, nargs - 1);
2409
2410   return ARGUMENT_PACK_P (last_parm);
2411 }
2412
2413 /* Generate a new name for the parameter pack name NAME (an
2414    IDENTIFIER_NODE) that incorporates its */
2415 static tree
2416 make_ith_pack_parameter_name (tree name, int i)
2417 {
2418   /* Munge the name to include the parameter index.  */
2419   char numbuf[128];
2420   char* newname;
2421   
2422   sprintf(numbuf, "%i", i);
2423   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2424   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2425   return get_identifier (newname);
2426 }
2427
2428 /* Structure used to track the progress of find_parameter_packs_r.  */
2429 struct find_parameter_pack_data 
2430 {
2431   /* TREE_LIST that will contain all of the parameter packs found by
2432      the traversal.  */
2433   tree* parameter_packs;
2434
2435   /* Set of AST nodes that have been visited by the traversal.  */
2436   struct pointer_set_t *visited;
2437
2438   /* Whether we should replace parameter packs with
2439      ERROR_MARK_NODE. Used by check_for_bare_parameter_packs.  */
2440   bool set_packs_to_error;
2441 };
2442
2443 /* Identifies all of the argument packs that occur in a template
2444    argument and appends them to the TREE_LIST inside DATA, which is a
2445    find_parameter_pack_data structure. This is a subroutine of
2446    make_pack_expansion and uses_parameter_packs.  */
2447 static tree
2448 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2449 {
2450   tree t = *tp;
2451   struct find_parameter_pack_data* ppd = 
2452     (struct find_parameter_pack_data*)data;
2453   bool parameter_pack_p = false;
2454
2455   /* Don't visit nodes twice, except when we're clearing out parameter
2456      packs.  */
2457   if (pointer_set_contains (ppd->visited, *tp))
2458     {
2459       *walk_subtrees = 0;
2460       return NULL_TREE;
2461     }
2462
2463 recheck:
2464   /* Identify whether this is a parameter pack or not.  */
2465   switch (TREE_CODE (t))
2466     {
2467     case TEMPLATE_PARM_INDEX:
2468       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2469         parameter_pack_p = true;
2470       break;
2471
2472     case TEMPLATE_TYPE_PARM:
2473     case TEMPLATE_TEMPLATE_PARM:
2474       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2475         parameter_pack_p = true;
2476       break;
2477
2478     case PARM_DECL:
2479       if (FUNCTION_PARAMETER_PACK_P (t))
2480         {
2481           /* We don't want to walk into the type of a PARM_DECL,
2482              because we don't want to see the type parameter pack.  */
2483           *walk_subtrees = 0;
2484           parameter_pack_p = true;
2485         }
2486       break;
2487
2488     case POINTER_TYPE:
2489       if (ppd->set_packs_to_error)
2490         /* Pointer types are shared, set in that case the outermost
2491            POINTER_TYPE to error_mark_node rather than the parameter pack.  */
2492         {
2493           t = TREE_TYPE (t);
2494           goto recheck;
2495         }
2496       break;
2497
2498     default:
2499       /* Not a parameter pack.  */
2500       break;
2501     }
2502
2503   if (parameter_pack_p)
2504     {
2505       /* Add this parameter pack to the list.  */
2506       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2507
2508       if (ppd->set_packs_to_error)
2509         /* The caller requested that we set the parameter packs to
2510            ERROR_MARK_NODE so that they will not trip up the compiler
2511            later.  The caller is responsible for emitting an error.  */
2512         *tp = error_mark_node;
2513       else
2514         /* Make sure we do not visit this node again.  */
2515         pointer_set_insert (ppd->visited, *tp);
2516     }
2517   else
2518     /* Make sure we do not visit this node again.  */
2519     pointer_set_insert (ppd->visited, *tp);
2520
2521   if (TYPE_P (t))
2522     cp_walk_tree (&TYPE_CONTEXT (t), 
2523                   &find_parameter_packs_r, ppd, NULL);
2524
2525   /* This switch statement will return immediately if we don't find a
2526      parameter pack.  */
2527   switch (TREE_CODE (t)) 
2528     {
2529     case TEMPLATE_PARM_INDEX:
2530       return NULL_TREE;
2531
2532     case BOUND_TEMPLATE_TEMPLATE_PARM:
2533       /* Check the template itself.  */
2534       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2535                     &find_parameter_packs_r, ppd, NULL);
2536       /* Check the template arguments.  */
2537       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2538                     NULL);
2539       *walk_subtrees = 0;
2540       return NULL_TREE;
2541
2542     case TEMPLATE_TYPE_PARM:
2543     case TEMPLATE_TEMPLATE_PARM:
2544       return NULL_TREE;
2545
2546     case PARM_DECL:
2547       return NULL_TREE;
2548
2549     case RECORD_TYPE:
2550       if (TYPE_PTRMEMFUNC_P (t))
2551         return NULL_TREE;
2552       /* Fall through.  */
2553
2554     case UNION_TYPE:
2555     case ENUMERAL_TYPE:
2556       if (TYPE_TEMPLATE_INFO (t))
2557         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2558                       &find_parameter_packs_r, ppd, NULL);
2559
2560       *walk_subtrees = 0;
2561       return NULL_TREE;
2562
2563     case TEMPLATE_DECL:
2564       cp_walk_tree (&TREE_TYPE (t),
2565                     &find_parameter_packs_r, ppd, NULL);
2566       return NULL_TREE;
2567  
2568     case TYPENAME_TYPE:
2569       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2570                    ppd, NULL);
2571       *walk_subtrees = 0;
2572       return NULL_TREE;
2573       
2574     case TYPE_PACK_EXPANSION:
2575     case EXPR_PACK_EXPANSION:
2576       *walk_subtrees = 0;
2577       return NULL_TREE;
2578
2579     case INTEGER_TYPE:
2580       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2581                     ppd, NULL);
2582       *walk_subtrees = 0;
2583       return NULL_TREE;
2584
2585     case IDENTIFIER_NODE:
2586       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, NULL);
2587       *walk_subtrees = 0;
2588       return NULL_TREE;
2589
2590     default:
2591       return NULL_TREE;
2592     }
2593
2594   return NULL_TREE;
2595 }
2596
2597 /* Determines if the expression or type T uses any parameter packs.  */
2598 bool
2599 uses_parameter_packs (tree t)
2600 {
2601   tree parameter_packs = NULL_TREE;
2602   struct find_parameter_pack_data ppd;
2603   ppd.parameter_packs = &parameter_packs;
2604   ppd.visited = pointer_set_create ();
2605   ppd.set_packs_to_error = false;
2606   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, NULL);
2607   pointer_set_destroy (ppd.visited);
2608   return parameter_packs != NULL_TREE;
2609 }
2610
2611 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2612    representation a base-class initializer into a parameter pack
2613    expansion. If all goes well, the resulting node will be an
2614    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2615    respectively.  */
2616 tree 
2617 make_pack_expansion (tree arg)
2618 {
2619   tree result;
2620   tree parameter_packs = NULL_TREE;
2621   bool for_types = false;
2622   struct find_parameter_pack_data ppd;
2623
2624   ppd.set_packs_to_error = false;
2625
2626   if (!arg || arg == error_mark_node)
2627     return arg;
2628
2629   if (TREE_CODE (arg) == TREE_LIST)
2630     {
2631       /* The only time we will see a TREE_LIST here is for a base
2632          class initializer.  In this case, the TREE_PURPOSE will be a
2633          _TYPE node (representing the base class expansion we're
2634          initializing) and the TREE_VALUE will be a TREE_LIST
2635          containing the initialization arguments. 
2636
2637          The resulting expansion looks somewhat different from most
2638          expansions. Rather than returning just one _EXPANSION, we
2639          return a TREE_LIST whose TREE_PURPOSE is a
2640          TYPE_PACK_EXPANSION containing the bases that will be
2641          initialized.  The TREE_VALUE will be identical to the
2642          original TREE_VALUE, which is a list of arguments that will
2643          be passed to each base.  We do not introduce any new pack
2644          expansion nodes into the TREE_VALUE (although it is possible
2645          that some already exist), because the TREE_PURPOSE and
2646          TREE_VALUE all need to be expanded together with the same
2647          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2648          resulting TREE_PURPOSE will mention the parameter packs in
2649          both the bases and the arguments to the bases.  */
2650       tree purpose;
2651       tree value;
2652       tree parameter_packs = NULL_TREE;
2653
2654       /* Determine which parameter packs will be used by the base
2655          class expansion.  */
2656       ppd.visited = pointer_set_create ();
2657       ppd.parameter_packs = &parameter_packs;
2658       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2659                     &ppd, NULL);
2660
2661       if (parameter_packs == NULL_TREE)
2662         {
2663           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2664           pointer_set_destroy (ppd.visited);
2665           return error_mark_node;
2666         }
2667
2668       if (TREE_VALUE (arg) != void_type_node)
2669         {
2670           /* Collect the sets of parameter packs used in each of the
2671              initialization arguments.  */
2672           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2673             {
2674               /* Determine which parameter packs will be expanded in this
2675                  argument.  */
2676               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2677                             &ppd, NULL);
2678             }
2679         }
2680
2681       pointer_set_destroy (ppd.visited);
2682
2683       /* Create the pack expansion type for the base type.  */
2684       purpose = make_node (TYPE_PACK_EXPANSION);
2685       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2686       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2687
2688       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2689          they will rarely be compared to anything.  */
2690       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2691
2692       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2693     }
2694
2695   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2696     for_types = true;
2697
2698   /* Build the PACK_EXPANSION_* node.  */
2699   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2700   SET_PACK_EXPANSION_PATTERN (result, arg);
2701   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2702     {
2703       /* Propagate type and const-expression information.  */
2704       TREE_TYPE (result) = TREE_TYPE (arg);
2705       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2706     }
2707   else
2708     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2709        they will rarely be compared to anything.  */
2710     SET_TYPE_STRUCTURAL_EQUALITY (result);
2711
2712   /* Determine which parameter packs will be expanded.  */
2713   ppd.parameter_packs = &parameter_packs;
2714   ppd.visited = pointer_set_create ();
2715   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, NULL);
2716   pointer_set_destroy (ppd.visited);
2717
2718   /* Make sure we found some parameter packs.  */
2719   if (parameter_packs == NULL_TREE)
2720     {
2721       if (TYPE_P (arg))
2722         error ("expansion pattern %<%T%> contains no argument packs", arg);
2723       else
2724         error ("expansion pattern %<%E%> contains no argument packs", arg);
2725       return error_mark_node;
2726     }
2727   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2728
2729   return result;
2730 }
2731
2732 /* Checks T for any "bare" parameter packs, which have not yet been
2733    expanded, and issues an error if any are found. This operation can
2734    only be done on full expressions or types (e.g., an expression
2735    statement, "if" condition, etc.), because we could have expressions like:
2736
2737      foo(f(g(h(args)))...)
2738
2739    where "args" is a parameter pack. check_for_bare_parameter_packs
2740    should not be called for the subexpressions args, h(args),
2741    g(h(args)), or f(g(h(args))), because we would produce erroneous
2742    error messages. 
2743
2744    Returns TRUE and emits an error if there were bare parameter packs,
2745    returns FALSE otherwise.  */
2746 bool 
2747 check_for_bare_parameter_packs (tree* t)
2748 {
2749   tree parameter_packs = NULL_TREE;
2750   struct find_parameter_pack_data ppd;
2751
2752   if (!processing_template_decl || !t || !*t || *t == error_mark_node)
2753     return false;
2754
2755   if (TREE_CODE (*t) == TYPE_DECL)
2756     t = &TREE_TYPE (*t);
2757
2758   ppd.parameter_packs = &parameter_packs;
2759   ppd.visited = pointer_set_create ();
2760   ppd.set_packs_to_error = false;
2761   cp_walk_tree (t, &find_parameter_packs_r, &ppd, NULL);
2762   pointer_set_destroy (ppd.visited);
2763
2764   if (parameter_packs) 
2765     {
2766       error ("parameter packs not expanded with `...':");
2767       while (parameter_packs)
2768         {
2769           tree pack = TREE_VALUE (parameter_packs);
2770           tree name = NULL_TREE;
2771
2772           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2773               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2774             name = TYPE_NAME (pack);
2775           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2776             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2777           else
2778             name = DECL_NAME (pack);
2779
2780           if (name)
2781             inform ("        %qD", name);
2782           else
2783             inform ("        <anonymous>");
2784
2785           parameter_packs = TREE_CHAIN (parameter_packs);
2786         }
2787
2788       /* Clean up any references to these parameter packs within the
2789          tree.  */
2790       ppd.parameter_packs = &parameter_packs;
2791       ppd.visited = pointer_set_create ();
2792       ppd.set_packs_to_error = true;
2793       cp_walk_tree (t, &find_parameter_packs_r, &ppd, NULL);
2794       pointer_set_destroy (ppd.visited);
2795
2796       return true;
2797     }
2798
2799   return false;
2800 }
2801
2802 /* Expand any parameter packs that occur in the template arguments in
2803    ARGS.  */
2804 tree
2805 expand_template_argument_pack (tree args)
2806 {
2807   tree result_args = NULL_TREE;
2808   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2809   int num_result_args = -1;
2810
2811   /* First, determine if we need to expand anything, and the number of
2812      slots we'll need.  */
2813   for (in_arg = 0; in_arg < nargs; ++in_arg)
2814     {
2815       tree arg = TREE_VEC_ELT (args, in_arg);
2816       if (ARGUMENT_PACK_P (arg))
2817         {
2818           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2819           if (num_result_args < 0)
2820             num_result_args = in_arg + num_packed;
2821           else
2822             num_result_args += num_packed;
2823         }
2824       else
2825         {
2826           if (num_result_args >= 0)
2827             num_result_args++;
2828         }
2829     }
2830
2831   /* If no expansion is necessary, we're done.  */
2832   if (num_result_args < 0)
2833     return args;
2834
2835   /* Expand arguments.  */
2836   result_args = make_tree_vec (num_result_args);
2837   for (in_arg = 0; in_arg < nargs; ++in_arg)
2838     {
2839       tree arg = TREE_VEC_ELT (args, in_arg);
2840       if (ARGUMENT_PACK_P (arg))
2841         {
2842           tree packed = ARGUMENT_PACK_ARGS (arg);
2843           int i, num_packed = TREE_VEC_LENGTH (packed);
2844           for (i = 0; i < num_packed; ++i, ++out_arg)
2845             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2846         }
2847       else
2848         {
2849           TREE_VEC_ELT (result_args, out_arg) = arg;
2850           ++out_arg;
2851         }
2852     }
2853
2854   return result_args;
2855 }
2856
2857 /* Complain if DECL shadows a template parameter.
2858
2859    [temp.local]: A template-parameter shall not be redeclared within its
2860    scope (including nested scopes).  */
2861
2862 void
2863 check_template_shadow (tree decl)
2864 {
2865   tree olddecl;
2866
2867   /* If we're not in a template, we can't possibly shadow a template
2868      parameter.  */
2869   if (!current_template_parms)
2870     return;
2871
2872   /* Figure out what we're shadowing.  */
2873   if (TREE_CODE (decl) == OVERLOAD)
2874     decl = OVL_CURRENT (decl);
2875   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2876
2877   /* If there's no previous binding for this name, we're not shadowing
2878      anything, let alone a template parameter.  */
2879   if (!olddecl)
2880     return;
2881
2882   /* If we're not shadowing a template parameter, we're done.  Note
2883      that OLDDECL might be an OVERLOAD (or perhaps even an
2884      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2885      node.  */
2886   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2887     return;
2888
2889   /* We check for decl != olddecl to avoid bogus errors for using a
2890      name inside a class.  We check TPFI to avoid duplicate errors for
2891      inline member templates.  */
2892   if (decl == olddecl
2893       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2894     return;
2895
2896   error ("declaration of %q+#D", decl);
2897   error (" shadows template parm %q+#D", olddecl);
2898 }
2899
2900 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2901    ORIG_LEVEL, DECL, and TYPE.  */
2902
2903 static tree
2904 build_template_parm_index (int index,
2905                            int level,
2906                            int orig_level,
2907                            tree decl,
2908                            tree type)
2909 {
2910   tree t = make_node (TEMPLATE_PARM_INDEX);
2911   TEMPLATE_PARM_IDX (t) = index;
2912   TEMPLATE_PARM_LEVEL (t) = level;
2913   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2914   TEMPLATE_PARM_DECL (t) = decl;
2915   TREE_TYPE (t) = type;
2916   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2917   TREE_INVARIANT (t) = TREE_INVARIANT (decl);
2918   TREE_READONLY (t) = TREE_READONLY (decl);
2919
2920   return t;
2921 }
2922
2923 /* Find the canonical type parameter for the given template type
2924    parameter.  Returns the canonical type parameter, which may be TYPE
2925    if no such parameter existed.  */
2926 static tree
2927 canonical_type_parameter (tree type)
2928 {
2929   tree list;
2930   int idx = TEMPLATE_TYPE_IDX (type);
2931   if (!canonical_template_parms)
2932     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2933
2934   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2935     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2936
2937   list = VEC_index (tree, canonical_template_parms, idx);
2938   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2939     list = TREE_CHAIN (list);
2940
2941   if (list)
2942     return TREE_VALUE (list);
2943   else
2944     {
2945       VEC_replace(tree, canonical_template_parms, idx,
2946                   tree_cons (NULL_TREE, type, 
2947                              VEC_index (tree, canonical_template_parms, idx)));
2948       return type;
2949     }
2950 }
2951
2952 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2953    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2954    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2955    new one is created.  */
2956
2957 static tree
2958 reduce_template_parm_level (tree index, tree type, int levels, tree args,
2959                             tsubst_flags_t complain)
2960 {
2961   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2962       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2963           != TEMPLATE_PARM_LEVEL (index) - levels))
2964     {
2965       tree orig_decl = TEMPLATE_PARM_DECL (index);
2966       tree decl, t;
2967
2968       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2969       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2970       TREE_INVARIANT (decl) = TREE_INVARIANT (orig_decl);
2971       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2972       DECL_ARTIFICIAL (decl) = 1;
2973       SET_DECL_TEMPLATE_PARM_P (decl);
2974
2975       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2976                                      TEMPLATE_PARM_LEVEL (index) - levels,
2977                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2978                                      decl, type);
2979       TEMPLATE_PARM_DESCENDANTS (index) = t;
2980       TEMPLATE_PARM_PARAMETER_PACK (t) 
2981         = TEMPLATE_PARM_PARAMETER_PACK (index);
2982
2983         /* Template template parameters need this.  */
2984       if (TREE_CODE (decl) == TEMPLATE_DECL)
2985         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
2986           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
2987            args, complain);
2988     }
2989
2990   return TEMPLATE_PARM_DESCENDANTS (index);
2991 }
2992
2993 /* Process information from new template parameter PARM and append it to the
2994    LIST being built.  This new parameter is a non-type parameter iff
2995    IS_NON_TYPE is true. This new parameter is a parameter
2996    pack iff IS_PARAMETER_PACK is true.  */
2997
2998 tree
2999 process_template_parm (tree list, tree parm, bool is_non_type, 
3000                        bool is_parameter_pack)
3001 {
3002   tree decl = 0;
3003   tree defval;
3004   tree err_parm_list;
3005   int idx = 0;
3006
3007   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3008   defval = TREE_PURPOSE (parm);
3009
3010   if (list)
3011     {
3012       tree p = tree_last (list);
3013
3014       if (p && TREE_VALUE (p) != error_mark_node)
3015         {
3016           p = TREE_VALUE (p);
3017           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3018             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3019           else
3020             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3021         }
3022
3023       ++idx;
3024     }
3025   else
3026     idx = 0;
3027
3028   if (is_non_type)
3029     {
3030       parm = TREE_VALUE (parm);
3031
3032       SET_DECL_TEMPLATE_PARM_P (parm);
3033
3034       if (TREE_TYPE (parm) == error_mark_node)
3035         {
3036           err_parm_list = build_tree_list (defval, parm);
3037           TREE_VALUE (err_parm_list) = error_mark_node;
3038            return chainon (list, err_parm_list);
3039         }
3040       else
3041       {
3042         /* [temp.param]
3043
3044            The top-level cv-qualifiers on the template-parameter are
3045            ignored when determining its type.  */
3046         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3047         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3048           {
3049             err_parm_list = build_tree_list (defval, parm);
3050             TREE_VALUE (err_parm_list) = error_mark_node;
3051              return chainon (list, err_parm_list);
3052           }
3053
3054         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3055           {
3056             /* This template parameter is not a parameter pack, but it
3057                should be. Complain about "bare" parameter packs.  */
3058             check_for_bare_parameter_packs (&TREE_TYPE (parm));
3059             
3060             /* Recover by calling this a parameter pack.  */
3061             is_parameter_pack = true;
3062           }
3063       }
3064
3065       /* A template parameter is not modifiable.  */
3066       TREE_CONSTANT (parm) = 1;
3067       TREE_INVARIANT (parm) = 1;
3068       TREE_READONLY (parm) = 1;
3069       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3070       TREE_CONSTANT (decl) = 1;
3071       TREE_INVARIANT (decl) = 1;
3072       TREE_READONLY (decl) = 1;
3073       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3074         = build_template_parm_index (idx, processing_template_decl,
3075                                      processing_template_decl,
3076                                      decl, TREE_TYPE (parm));
3077
3078       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3079         = is_parameter_pack;
3080     }
3081   else
3082     {
3083       tree t;
3084       parm = TREE_VALUE (TREE_VALUE (parm));
3085
3086       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3087         {
3088           t = make_aggr_type (TEMPLATE_TEMPLATE_PARM);
3089           /* This is for distinguishing between real templates and template
3090              template parameters */
3091           TREE_TYPE (parm) = t;
3092           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3093           decl = parm;
3094         }
3095       else
3096         {
3097           t = make_aggr_type (TEMPLATE_TYPE_PARM);
3098           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3099           decl = build_decl (TYPE_DECL, parm, t);
3100         }
3101
3102       TYPE_NAME (t) = decl;
3103       TYPE_STUB_DECL (t) = decl;
3104       parm = decl;
3105       TEMPLATE_TYPE_PARM_INDEX (t)
3106         = build_template_parm_index (idx, processing_template_decl,
3107                                      processing_template_decl,
3108                                      decl, TREE_TYPE (parm));
3109       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3110       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3111     }
3112   DECL_ARTIFICIAL (decl) = 1;
3113   SET_DECL_TEMPLATE_PARM_P (decl);
3114   pushdecl (decl);
3115   parm = build_tree_list (defval, parm);
3116   return chainon (list, parm);
3117 }
3118
3119 /* The end of a template parameter list has been reached.  Process the
3120    tree list into a parameter vector, converting each parameter into a more
3121    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3122    as PARM_DECLs.  */
3123
3124 tree
3125 end_template_parm_list (tree parms)
3126 {
3127   int nparms;
3128   tree parm, next;
3129   tree saved_parmlist = make_tree_vec (list_length (parms));
3130
3131   current_template_parms
3132     = tree_cons (size_int (processing_template_decl),
3133                  saved_parmlist, current_template_parms);
3134
3135   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3136     {
3137       next = TREE_CHAIN (parm);
3138       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3139       TREE_CHAIN (parm) = NULL_TREE;
3140     }
3141
3142   --processing_template_parmlist;
3143
3144   return saved_parmlist;
3145 }
3146
3147 /* end_template_decl is called after a template declaration is seen.  */
3148
3149 void
3150 end_template_decl (void)
3151 {
3152   reset_specialization ();
3153
3154   if (! processing_template_decl)
3155     return;
3156
3157   /* This matches the pushlevel in begin_template_parm_list.  */
3158   finish_scope ();
3159
3160   --processing_template_decl;
3161   current_template_parms = TREE_CHAIN (current_template_parms);
3162 }
3163
3164 /* Within the declaration of a template, return all levels of template
3165    parameters that apply.  The template parameters are represented as
3166    a TREE_VEC, in the form documented in cp-tree.h for template
3167    arguments.  */
3168
3169 static tree
3170 current_template_args (void)
3171 {
3172   tree header;
3173   tree args = NULL_TREE;
3174   int length = TMPL_PARMS_DEPTH (current_template_parms);
3175   int l = length;
3176
3177   /* If there is only one level of template parameters, we do not
3178      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3179      TREE_VEC containing the arguments.  */
3180   if (length > 1)
3181     args = make_tree_vec (length);
3182
3183   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3184     {
3185       tree a = copy_node (TREE_VALUE (header));
3186       int i;
3187
3188       TREE_TYPE (a) = NULL_TREE;
3189       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3190         {
3191           tree t = TREE_VEC_ELT (a, i);
3192
3193           /* T will be a list if we are called from within a
3194              begin/end_template_parm_list pair, but a vector directly
3195              if within a begin/end_member_template_processing pair.  */
3196           if (TREE_CODE (t) == TREE_LIST)
3197             {
3198               t = TREE_VALUE (t);
3199
3200               if (!error_operand_p (t))
3201                 {
3202                   if (TREE_CODE (t) == TYPE_DECL
3203                       || TREE_CODE (t) == TEMPLATE_DECL)
3204                     {
3205                       t = TREE_TYPE (t);
3206                       
3207                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3208                         {
3209                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3210                              with a single element, which expands T.  */
3211                           tree vec = make_tree_vec (1);
3212                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3213                           
3214                           t = make_node (TYPE_ARGUMENT_PACK);
3215                           SET_ARGUMENT_PACK_ARGS (t, vec);
3216                         }
3217                     }
3218                   else
3219                     {
3220                       t = DECL_INITIAL (t);
3221                       
3222                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3223                         {
3224                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3225                              with a single element, which expands T.  */
3226                           tree vec = make_tree_vec (1);
3227                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3228                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3229                           
3230                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3231                           SET_ARGUMENT_PACK_ARGS (t, vec);
3232                           TREE_TYPE (t) = type;
3233                         }
3234                     }
3235                   TREE_VEC_ELT (a, i) = t;
3236                 }
3237             }
3238         }
3239
3240       if (length > 1)
3241         TREE_VEC_ELT (args, --l) = a;
3242       else
3243         args = a;
3244     }
3245
3246   return args;
3247 }
3248
3249 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3250    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3251    a member template.  Used by push_template_decl below.  */
3252
3253 static tree
3254 build_template_decl (tree decl, tree parms, bool member_template_p)
3255 {
3256   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3257   DECL_TEMPLATE_PARMS (tmpl) = parms;
3258   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3259   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3260   if (DECL_LANG_SPECIFIC (decl))
3261     {
3262       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3263       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3264       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3265       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3266       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3267       if (DECL_OVERLOADED_OPERATOR_P (decl))
3268         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3269                                       DECL_OVERLOADED_OPERATOR_P (decl));
3270     }
3271
3272   return tmpl;
3273 }
3274
3275 struct template_parm_data
3276 {
3277   /* The level of the template parameters we are currently
3278      processing.  */
3279   int level;
3280
3281   /* The index of the specialization argument we are currently
3282      processing.  */
3283   int current_arg;
3284
3285   /* An array whose size is the number of template parameters.  The
3286      elements are nonzero if the parameter has been used in any one
3287      of the arguments processed so far.  */
3288   int* parms;
3289
3290   /* An array whose size is the number of template arguments.  The
3291      elements are nonzero if the argument makes use of template
3292      parameters of this level.  */
3293   int* arg_uses_template_parms;
3294 };
3295
3296 /* Subroutine of push_template_decl used to see if each template
3297    parameter in a partial specialization is used in the explicit
3298    argument list.  If T is of the LEVEL given in DATA (which is
3299    treated as a template_parm_data*), then DATA->PARMS is marked
3300    appropriately.  */
3301
3302 static int
3303 mark_template_parm (tree t, void* data)
3304 {
3305   int level;
3306   int idx;
3307   struct template_parm_data* tpd = (struct template_parm_data*) data;
3308
3309   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3310     {
3311       level = TEMPLATE_PARM_LEVEL (t);
3312       idx = TEMPLATE_PARM_IDX (t);
3313     }
3314   else
3315     {
3316       level = TEMPLATE_TYPE_LEVEL (t);
3317       idx = TEMPLATE_TYPE_IDX (t);
3318     }
3319
3320   if (level == tpd->level)
3321     {
3322       tpd->parms[idx] = 1;
3323       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3324     }
3325
3326   /* Return zero so that for_each_template_parm will continue the
3327      traversal of the tree; we want to mark *every* template parm.  */
3328   return 0;
3329 }
3330
3331 /* Process the partial specialization DECL.  */
3332
3333 static tree
3334 process_partial_specialization (tree decl)
3335 {
3336   tree type = TREE_TYPE (decl);
3337   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3338   tree specargs = CLASSTYPE_TI_ARGS (type);
3339   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3340   tree inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3341   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3342   int nargs = TREE_VEC_LENGTH (inner_args);
3343   int ntparms = TREE_VEC_LENGTH (inner_parms);
3344   int  i;
3345   int did_error_intro = 0;
3346   struct template_parm_data tpd;
3347   struct template_parm_data tpd2;
3348
3349   /* We check that each of the template parameters given in the
3350      partial specialization is used in the argument list to the
3351      specialization.  For example:
3352
3353        template <class T> struct S;
3354        template <class T> struct S<T*>;
3355
3356      The second declaration is OK because `T*' uses the template
3357      parameter T, whereas
3358
3359        template <class T> struct S<int>;
3360
3361      is no good.  Even trickier is:
3362
3363        template <class T>
3364        struct S1
3365        {
3366           template <class U>
3367           struct S2;
3368           template <class U>
3369           struct S2<T>;
3370        };
3371
3372      The S2<T> declaration is actually invalid; it is a
3373      full-specialization.  Of course,
3374
3375           template <class U>
3376           struct S2<T (*)(U)>;
3377
3378      or some such would have been OK.  */
3379   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3380   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3381   memset (tpd.parms, 0, sizeof (int) * ntparms);
3382
3383   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3384   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3385   for (i = 0; i < nargs; ++i)
3386     {
3387       tpd.current_arg = i;
3388       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3389                               &mark_template_parm,
3390                               &tpd,
3391                               NULL,
3392                               /*include_nondeduced_p=*/false);
3393     }
3394   for (i = 0; i < ntparms; ++i)
3395     if (tpd.parms[i] == 0)
3396       {
3397         /* One of the template parms was not used in the
3398            specialization.  */
3399         if (!did_error_intro)
3400           {
3401             error ("template parameters not used in partial specialization:");
3402             did_error_intro = 1;
3403           }
3404
3405         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3406       }
3407
3408   /* [temp.class.spec]
3409
3410      The argument list of the specialization shall not be identical to
3411      the implicit argument list of the primary template.  */
3412   if (comp_template_args
3413       (inner_args,
3414        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3415                                                    (maintmpl)))))
3416     error ("partial specialization %qT does not specialize any template arguments", type);
3417
3418   /* [temp.class.spec]
3419
3420      A partially specialized non-type argument expression shall not
3421      involve template parameters of the partial specialization except
3422      when the argument expression is a simple identifier.
3423
3424      The type of a template parameter corresponding to a specialized
3425      non-type argument shall not be dependent on a parameter of the
3426      specialization. 
3427
3428      Also, we verify that pack expansions only occur at the
3429      end of the argument list.  */
3430   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3431   tpd2.parms = 0;
3432   for (i = 0; i < nargs; ++i)
3433     {
3434       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3435       tree arg = TREE_VEC_ELT (inner_args, i);
3436       tree packed_args = NULL_TREE;
3437       int j, len = 1;
3438
3439       if (ARGUMENT_PACK_P (arg))
3440         {
3441           /* Extract the arguments from the argument pack. We'll be
3442              iterating over these in the following loop.  */
3443           packed_args = ARGUMENT_PACK_ARGS (arg);
3444           len = TREE_VEC_LENGTH (packed_args);
3445         }
3446
3447       for (j = 0; j < len; j++)
3448         {
3449           if (packed_args)
3450             /* Get the Jth argument in the parameter pack.  */
3451             arg = TREE_VEC_ELT (packed_args, j);
3452
3453           if (PACK_EXPANSION_P (arg))
3454             {
3455               /* Pack expansions must come at the end of the
3456                  argument list.  */
3457               if ((packed_args && j < len - 1)
3458                   || (!packed_args && i < nargs - 1))
3459                 {
3460                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3461                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3462                   else
3463                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3464
3465                   if (packed_args)
3466                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3467                 }
3468             }
3469
3470           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3471             /* We only care about the pattern.  */
3472             arg = PACK_EXPANSION_PATTERN (arg);
3473
3474           if (/* These first two lines are the `non-type' bit.  */
3475               !TYPE_P (arg)
3476               && TREE_CODE (arg) != TEMPLATE_DECL
3477               /* This next line is the `argument expression is not just a
3478                  simple identifier' condition and also the `specialized
3479                  non-type argument' bit.  */
3480               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3481             {
3482               if ((!packed_args && tpd.arg_uses_template_parms[i])
3483                   || (packed_args && uses_template_parms (arg)))
3484                 error ("template argument %qE involves template parameter(s)",
3485                        arg);
3486               else 
3487                 {
3488                   /* Look at the corresponding template parameter,
3489                      marking which template parameters its type depends
3490                      upon.  */
3491                   tree type = TREE_TYPE (parm);
3492
3493                   if (!tpd2.parms)
3494                     {
3495                       /* We haven't yet initialized TPD2.  Do so now.  */
3496                       tpd2.arg_uses_template_parms 
3497                         = (int *) alloca (sizeof (int) * nargs);
3498                       /* The number of parameters here is the number in the
3499                          main template, which, as checked in the assertion
3500                          above, is NARGS.  */
3501                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3502                       tpd2.level = 
3503                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3504                     }
3505
3506                   /* Mark the template parameters.  But this time, we're
3507                      looking for the template parameters of the main
3508                      template, not in the specialization.  */
3509                   tpd2.current_arg = i;
3510                   tpd2.arg_uses_template_parms[i] = 0;
3511                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3512                   for_each_template_parm (type,
3513                                           &mark_template_parm,
3514                                           &tpd2,
3515                                           NULL,
3516                                           /*include_nondeduced_p=*/false);
3517
3518                   if (tpd2.arg_uses_template_parms [i])
3519                     {
3520                       /* The type depended on some template parameters.
3521                          If they are fully specialized in the
3522                          specialization, that's OK.  */
3523                       int j;
3524                       for (j = 0; j < nargs; ++j)
3525                         if (tpd2.parms[j] != 0
3526                             && tpd.arg_uses_template_parms [j])
3527                           {
3528                             error ("type %qT of template argument %qE depends "
3529                                    "on template parameter(s)", 
3530                                    type,
3531                                    arg);
3532                             break;
3533                           }
3534                     }
3535                 }
3536             }
3537         }
3538     }
3539
3540   if (retrieve_specialization (maintmpl, specargs,
3541                                /*class_specializations_p=*/true))
3542     /* We've already got this specialization.  */
3543     return decl;
3544
3545   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3546     = tree_cons (specargs, inner_parms,
3547                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3548   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3549   return decl;
3550 }
3551
3552 /* Check that a template declaration's use of default arguments and
3553    parameter packs is not invalid.  Here, PARMS are the template
3554    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3555    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3556    specialization.
3557    
3558
3559    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3560    declaration (but not a definition); 1 indicates a declaration, 2
3561    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3562    emitted for extraneous default arguments.
3563
3564    Returns TRUE if there were no errors found, FALSE otherwise. */
3565
3566 bool
3567 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3568                          int is_partial, int is_friend_decl)
3569 {
3570   const char *msg;
3571   int last_level_to_check;
3572   tree parm_level;
3573   bool no_errors = true;
3574
3575   /* [temp.param]
3576
3577      A default template-argument shall not be specified in a
3578      function template declaration or a function template definition, nor
3579      in the template-parameter-list of the definition of a member of a
3580      class template.  */
3581
3582   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3583     /* You can't have a function template declaration in a local
3584        scope, nor you can you define a member of a class template in a
3585        local scope.  */
3586     return true;
3587
3588   if (current_class_type
3589       && !TYPE_BEING_DEFINED (current_class_type)
3590       && DECL_LANG_SPECIFIC (decl)
3591       /* If this is either a friend defined in the scope of the class
3592          or a member function.  */
3593       && (DECL_FUNCTION_MEMBER_P (decl)
3594           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3595           : DECL_FRIEND_CONTEXT (decl)
3596           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3597           : false)
3598       /* And, if it was a member function, it really was defined in
3599          the scope of the class.  */
3600       && (!DECL_FUNCTION_MEMBER_P (decl)
3601           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3602     /* We already checked these parameters when the template was
3603        declared, so there's no need to do it again now.  This function
3604        was defined in class scope, but we're processing it's body now
3605        that the class is complete.  */
3606     return true;
3607
3608   /* Core issue 226 (C++0x only): the following only applies to class
3609      templates.  */
3610   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3611     {
3612       /* [temp.param]
3613
3614          If a template-parameter has a default template-argument, all
3615          subsequent template-parameters shall have a default
3616          template-argument supplied.  */
3617       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3618         {
3619           tree inner_parms = TREE_VALUE (parm_level);
3620           int ntparms = TREE_VEC_LENGTH (inner_parms);
3621           int seen_def_arg_p = 0;
3622           int i;
3623
3624           for (i = 0; i < ntparms; ++i)
3625             {
3626               tree parm = TREE_VEC_ELT (inner_parms, i);
3627
3628               if (parm == error_mark_node)
3629                 continue;
3630
3631               if (TREE_PURPOSE (parm))
3632                 seen_def_arg_p = 1;
3633               else if (seen_def_arg_p)
3634                 {
3635                   error ("no default argument for %qD", TREE_VALUE (parm));
3636                   /* For better subsequent error-recovery, we indicate that
3637                      there should have been a default argument.  */
3638                   TREE_PURPOSE (parm) = error_mark_node;
3639                   no_errors = false;
3640                 }
3641               else if (is_primary
3642                        && !is_partial
3643                        && !is_friend_decl
3644                        && TREE_CODE (decl) == TYPE_DECL
3645                        && i < ntparms - 1
3646                        && template_parameter_pack_p (TREE_VALUE (parm)))
3647                 {
3648                   /* A primary class template can only have one
3649                      parameter pack, at the end of the template
3650                      parameter list.  */
3651
3652                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3653                     error ("parameter pack %qE must be at the end of the"
3654                            " template parameter list", TREE_VALUE (parm));
3655                   else
3656                     error ("parameter pack %qT must be at the end of the"
3657                            " template parameter list", 
3658                            TREE_TYPE (TREE_VALUE (parm)));
3659
3660                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3661                     = error_mark_node;
3662                   no_errors = false;
3663                 }
3664             }
3665         }
3666     }
3667
3668   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3669       || is_partial 
3670       || !is_primary
3671       || is_friend_decl)
3672     /* For an ordinary class template, default template arguments are
3673        allowed at the innermost level, e.g.:
3674          template <class T = int>
3675          struct S {};
3676        but, in a partial specialization, they're not allowed even
3677        there, as we have in [temp.class.spec]:
3678
3679          The template parameter list of a specialization shall not
3680          contain default template argument values.
3681
3682        So, for a partial specialization, or for a function template
3683        (in C++98/C++03), we look at all of them.  */
3684     ;
3685   else
3686     /* But, for a primary class template that is not a partial
3687        specialization we look at all template parameters except the
3688        innermost ones.  */
3689     parms = TREE_CHAIN (parms);
3690
3691   /* Figure out what error message to issue.  */
3692   if (is_friend_decl == 2)
3693     msg = "default template arguments may not be used in function template friend re-declaration";
3694   else if (is_friend_decl)
3695     msg = "default template arguments may not be used in function template friend declarations";
3696   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3697     msg = "default template arguments may not be used in function templates";
3698   else if (is_partial)
3699     msg = "default template arguments may not be used in partial specializations";
3700   else
3701     msg = "default argument for template parameter for class enclosing %qD";
3702
3703   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3704     /* If we're inside a class definition, there's no need to
3705        examine the parameters to the class itself.  On the one
3706        hand, they will be checked when the class is defined, and,
3707        on the other, default arguments are valid in things like:
3708          template <class T = double>
3709          struct S { template <class U> void f(U); };
3710        Here the default argument for `S' has no bearing on the
3711        declaration of `f'.  */
3712     last_level_to_check = template_class_depth (current_class_type) + 1;
3713   else
3714     /* Check everything.  */
3715     last_level_to_check = 0;
3716
3717   for (parm_level = parms;
3718        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3719        parm_level = TREE_CHAIN (parm_level))
3720     {
3721       tree inner_parms = TREE_VALUE (parm_level);
3722       int i;
3723       int ntparms;
3724
3725       ntparms = TREE_VEC_LENGTH (inner_parms);
3726       for (i = 0; i < ntparms; ++i)
3727         {
3728           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3729             continue;
3730
3731           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3732             {
3733               if (msg)
3734                 {
3735                   no_errors = false;
3736                   if (is_friend_decl == 2)
3737                     return no_errors;
3738
3739                   error (msg, decl);
3740                   msg = 0;
3741                 }
3742
3743               /* Clear out the default argument so that we are not
3744                  confused later.  */
3745               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3746             }
3747         }
3748
3749       /* At this point, if we're still interested in issuing messages,
3750          they must apply to classes surrounding the object declared.  */
3751       if (msg)
3752         msg = "default argument for template parameter for class enclosing %qD";
3753     }
3754
3755   return no_errors;
3756 }
3757
3758 /* Worker for push_template_decl_real, called via
3759    for_each_template_parm.  DATA is really an int, indicating the
3760    level of the parameters we are interested in.  If T is a template
3761    parameter of that level, return nonzero.  */
3762
3763 static int
3764 template_parm_this_level_p (tree t, void* data)
3765 {
3766   int this_level = *(int *)data;
3767   int level;
3768
3769   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3770     level = TEMPLATE_PARM_LEVEL (t);
3771   else
3772     level = TEMPLATE_TYPE_LEVEL (t);
3773   return level == this_level;
3774 }
3775
3776 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3777    parameters given by current_template_args, or reuses a
3778    previously existing one, if appropriate.  Returns the DECL, or an
3779    equivalent one, if it is replaced via a call to duplicate_decls.
3780
3781    If IS_FRIEND is true, DECL is a friend declaration.  */
3782
3783 tree
3784 push_template_decl_real (tree decl, bool is_friend)
3785 {
3786   tree tmpl;
3787   tree args;
3788   tree info;
3789   tree ctx;
3790   int primary;
3791   int is_partial;
3792   int new_template_p = 0;
3793   /* True if the template is a member template, in the sense of
3794      [temp.mem].  */
3795   bool member_template_p = false;
3796
3797   if (decl == error_mark_node)
3798     return decl;
3799
3800   /* See if this is a partial specialization.  */
3801   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3802                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3803                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3804
3805   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3806     is_friend = true;
3807
3808   if (is_friend)
3809     /* For a friend, we want the context of the friend function, not
3810        the type of which it is a friend.  */
3811     ctx = DECL_CONTEXT (decl);
3812   else if (CP_DECL_CONTEXT (decl)
3813            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3814     /* In the case of a virtual function, we want the class in which
3815        it is defined.  */
3816     ctx = CP_DECL_CONTEXT (decl);
3817   else
3818     /* Otherwise, if we're currently defining some class, the DECL
3819        is assumed to be a member of the class.  */
3820     ctx = current_scope ();
3821
3822   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3823     ctx = NULL_TREE;
3824
3825   if (!DECL_CONTEXT (decl))
3826     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3827
3828   /* See if this is a primary template.  */
3829   if (is_friend && ctx)
3830     /* A friend template that specifies a class context, i.e.
3831          template <typename T> friend void A<T>::f();
3832        is not primary.  */
3833     primary = 0;
3834   else
3835     primary = template_parm_scope_p ();
3836
3837   if (primary)
3838     {
3839       if (DECL_CLASS_SCOPE_P (decl))
3840         member_template_p = true;
3841       if (TREE_CODE (decl) == TYPE_DECL
3842           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3843         error ("template class without a name");
3844       else if (TREE_CODE (decl) == FUNCTION_DECL)
3845         {
3846           if (DECL_DESTRUCTOR_P (decl))
3847             {
3848               /* [temp.mem]
3849
3850                  A destructor shall not be a member template.  */
3851               error ("destructor %qD declared as member template", decl);
3852               return error_mark_node;
3853             }
3854           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3855               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3856                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3857                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3858                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3859                       == void_list_node)))
3860             {
3861               /* [basic.stc.dynamic.allocation]
3862
3863                  An allocation function can be a function
3864                  template. ... Template allocation functions shall
3865                  have two or more parameters.  */
3866               error ("invalid template declaration of %qD", decl);
3867               return error_mark_node;
3868             }
3869         }
3870       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3871                && CLASS_TYPE_P (TREE_TYPE (decl)))
3872         /* OK */;
3873       else
3874         {
3875           error ("template declaration of %q#D", decl);
3876           return error_mark_node;
3877         }
3878     }
3879
3880   /* Check to see that the rules regarding the use of default
3881      arguments are not being violated.  */
3882   check_default_tmpl_args (decl, current_template_parms,
3883                            primary, is_partial, /*is_friend_decl=*/0);
3884
3885   /* Ensure that there are no parameter packs in the type of this
3886      declaration that have not been expanded.  */
3887   if (TREE_CODE (decl) == FUNCTION_DECL)
3888     {
3889       /* Check each of the arguments individually to see if there are
3890          any bare parameter packs.  */
3891       tree type = TREE_TYPE (decl);
3892       tree arg = DECL_ARGUMENTS (decl);
3893       tree argtype = TYPE_ARG_TYPES (type);
3894
3895       while (arg && argtype)
3896         {
3897           if (!FUNCTION_PARAMETER_PACK_P (arg)
3898               && check_for_bare_parameter_packs (&TREE_TYPE (arg)))
3899             {
3900             /* This is a PARM_DECL that contains unexpanded parameter
3901                packs. We have already complained about this in the
3902                check_for_bare_parameter_packs call, so just replace
3903                these types with ERROR_MARK_NODE.  */
3904               TREE_TYPE (arg) = error_mark_node;
3905               TREE_VALUE (argtype) = error_mark_node;
3906             }
3907
3908           arg = TREE_CHAIN (arg);
3909           argtype = TREE_CHAIN (argtype);
3910         }
3911
3912       /* Check for bare parameter packs in the return type and the
3913          exception specifiers.  */
3914       if (check_for_bare_parameter_packs (&TREE_TYPE (type)))
3915         /* Errors were already issued, set return type to int
3916            as the frontend doesn't expect error_mark_node as
3917            the return type.  */
3918         TREE_TYPE (type) = integer_type_node;
3919       check_for_bare_parameter_packs (&TYPE_RAISES_EXCEPTIONS (type));
3920     }
3921   else if (check_for_bare_parameter_packs (&TREE_TYPE (decl)))
3922     return error_mark_node;
3923
3924   if (is_partial)
3925     return process_partial_specialization (decl);
3926
3927   args = current_template_args ();
3928
3929   if (!ctx
3930       || TREE_CODE (ctx) == FUNCTION_DECL
3931       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3932       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3933     {
3934       if (DECL_LANG_SPECIFIC (decl)
3935           && DECL_TEMPLATE_INFO (decl)
3936           && DECL_TI_TEMPLATE (decl))
3937         tmpl = DECL_TI_TEMPLATE (decl);
3938       /* If DECL is a TYPE_DECL for a class-template, then there won't
3939          be DECL_LANG_SPECIFIC.  The information equivalent to
3940          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3941       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3942                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3943                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3944         {
3945           /* Since a template declaration already existed for this
3946              class-type, we must be redeclaring it here.  Make sure
3947              that the redeclaration is valid.  */
3948           redeclare_class_template (TREE_TYPE (decl),
3949                                     current_template_parms);
3950           /* We don't need to create a new TEMPLATE_DECL; just use the
3951              one we already had.  */
3952           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3953         }
3954       else
3955         {
3956           tmpl = build_template_decl (decl, current_template_parms,
3957                                       member_template_p);
3958           new_template_p = 1;
3959
3960           if (DECL_LANG_SPECIFIC (decl)
3961               && DECL_TEMPLATE_SPECIALIZATION (decl))
3962             {
3963               /* A specialization of a member template of a template
3964                  class.  */
3965               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3966               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3967               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3968             }
3969         }
3970     }
3971   else
3972     {
3973       tree a, t, current, parms;
3974       int i;
3975       tree tinfo = get_template_info (decl);
3976
3977       if (!tinfo)
3978         {
3979           error ("template definition of non-template %q#D", decl);
3980           return decl;
3981         }
3982
3983       tmpl = TI_TEMPLATE (tinfo);
3984
3985       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3986           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3987           && DECL_TEMPLATE_SPECIALIZATION (decl)
3988           && DECL_MEMBER_TEMPLATE_P (tmpl))
3989         {
3990           tree new_tmpl;
3991
3992           /* The declaration is a specialization of a member
3993              template, declared outside the class.  Therefore, the
3994              innermost template arguments will be NULL, so we
3995              replace them with the arguments determined by the
3996              earlier call to check_explicit_specialization.  */
3997           args = DECL_TI_ARGS (decl);
3998
3999           new_tmpl
4000             = build_template_decl (decl, current_template_parms,
4001                                    member_template_p);
4002           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4003           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4004           DECL_TI_TEMPLATE (decl) = new_tmpl;
4005           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4006           DECL_TEMPLATE_INFO (new_tmpl)
4007             = tree_cons (tmpl, args, NULL_TREE);
4008
4009           register_specialization (new_tmpl,
4010                                    most_general_template (tmpl),
4011                                    args,
4012                                    is_friend);
4013           return decl;
4014         }
4015
4016       /* Make sure the template headers we got make sense.  */
4017
4018       parms = DECL_TEMPLATE_PARMS (tmpl);
4019       i = TMPL_PARMS_DEPTH (parms);
4020       if (TMPL_ARGS_DEPTH (args) != i)
4021         {
4022           error ("expected %d levels of template parms for %q#D, got %d",
4023                  i, decl, TMPL_ARGS_DEPTH (args));
4024         }
4025       else
4026         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4027           {
4028             a = TMPL_ARGS_LEVEL (args, i);
4029             t = INNERMOST_TEMPLATE_PARMS (parms);
4030
4031             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4032               {
4033                 if (current == decl)
4034                   error ("got %d template parameters for %q#D",
4035                          TREE_VEC_LENGTH (a), decl);
4036                 else
4037                   error ("got %d template parameters for %q#T",
4038                          TREE_VEC_LENGTH (a), current);
4039                 error ("  but %d required", TREE_VEC_LENGTH (t));
4040                 return error_mark_node;
4041               }
4042
4043             if (current == decl)
4044               current = ctx;
4045             else
4046               current = (TYPE_P (current)
4047                          ? TYPE_CONTEXT (current)
4048                          : DECL_CONTEXT (current));
4049           }
4050
4051       /* Check that the parms are used in the appropriate qualifying scopes
4052          in the declarator.  */
4053       if (!comp_template_args
4054           (TI_ARGS (tinfo),
4055            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4056         {
4057           error ("\
4058 template arguments to %qD do not match original template %qD",
4059                  decl, DECL_TEMPLATE_RESULT (tmpl));
4060           if (!uses_template_parms (TI_ARGS (tinfo)))
4061             inform ("use template<> for an explicit specialization");
4062           /* Avoid crash in import_export_decl.  */
4063           DECL_INTERFACE_KNOWN (decl) = 1;
4064           return error_mark_node;
4065         }
4066     }
4067
4068   DECL_TEMPLATE_RESULT (tmpl) = decl;
4069   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4070
4071   /* Push template declarations for global functions and types.  Note
4072      that we do not try to push a global template friend declared in a
4073      template class; such a thing may well depend on the template
4074      parameters of the class.  */
4075   if (new_template_p && !ctx
4076       && !(is_friend && template_class_depth (current_class_type) > 0))
4077     {
4078       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4079       if (tmpl == error_mark_node)
4080         return error_mark_node;
4081
4082       /* Hide template friend classes that haven't been declared yet.  */
4083       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4084         {
4085           DECL_ANTICIPATED (tmpl) = 1;
4086           DECL_FRIEND_P (tmpl) = 1;
4087         }
4088     }
4089
4090   if (primary)
4091     {
4092       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4093       int i;
4094
4095       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4096       if (DECL_CONV_FN_P (tmpl))
4097         {
4098           int depth = TMPL_PARMS_DEPTH (parms);
4099
4100           /* It is a conversion operator. See if the type converted to
4101              depends on innermost template operands.  */
4102
4103           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4104                                          depth))
4105             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4106         }
4107
4108       /* Give template template parms a DECL_CONTEXT of the template
4109          for which they are a parameter.  */
4110       parms = INNERMOST_TEMPLATE_PARMS (parms);
4111       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4112         {
4113           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4114           if (TREE_CODE (parm) == TEMPLATE_DECL)
4115             DECL_CONTEXT (parm) = tmpl;
4116         }
4117     }
4118
4119   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4120      back to its most general template.  If TMPL is a specialization,
4121      ARGS may only have the innermost set of arguments.  Add the missing
4122      argument levels if necessary.  */
4123   if (DECL_TEMPLATE_INFO (tmpl))
4124     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4125
4126   info = tree_cons (tmpl, args, NULL_TREE);
4127
4128   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4129     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4130   else if (DECL_LANG_SPECIFIC (decl))
4131     DECL_TEMPLATE_INFO (decl) = info;
4132
4133   return DECL_TEMPLATE_RESULT (tmpl);
4134 }
4135
4136 tree
4137 push_template_decl (tree decl)
4138 {
4139   return push_template_decl_real (decl, false);
4140 }
4141
4142 /* Called when a class template TYPE is redeclared with the indicated
4143    template PARMS, e.g.:
4144
4145      template <class T> struct S;
4146      template <class T> struct S {};  */
4147
4148 bool
4149 redeclare_class_template (tree type, tree parms)
4150 {
4151   tree tmpl;
4152   tree tmpl_parms;
4153   int i;
4154
4155   if (!TYPE_TEMPLATE_INFO (type))
4156     {
4157       error ("%qT is not a template type", type);
4158       return false;
4159     }
4160
4161   tmpl = TYPE_TI_TEMPLATE (type);
4162   if (!PRIMARY_TEMPLATE_P (tmpl))
4163     /* The type is nested in some template class.  Nothing to worry
4164        about here; there are no new template parameters for the nested
4165        type.  */
4166     return true;
4167
4168   if (!parms)
4169     {
4170       error ("template specifiers not specified in declaration of %qD",
4171              tmpl);
4172       return false;
4173     }
4174
4175   parms = INNERMOST_TEMPLATE_PARMS (parms);
4176   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4177
4178   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4179     {
4180       error ("redeclared with %d template parameter(s)", 
4181              TREE_VEC_LENGTH (parms));
4182       inform ("previous declaration %q+D used %d template parameter(s)", 
4183              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4184       return false;
4185     }
4186
4187   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4188     {
4189       tree tmpl_parm;
4190       tree parm;
4191       tree tmpl_default;
4192       tree parm_default;
4193
4194       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4195           || TREE_VEC_ELT (parms, i) == error_mark_node)
4196         continue;
4197
4198       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4199       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4200       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4201       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4202
4203       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4204          TEMPLATE_DECL.  */
4205       if (tmpl_parm != error_mark_node
4206           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4207               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4208                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4209               || (TREE_CODE (tmpl_parm) != PARM_DECL
4210                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4211                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4212               || (TREE_CODE (tmpl_parm) == PARM_DECL
4213                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4214                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4215         {
4216           error ("template parameter %q+#D", tmpl_parm);
4217           error ("redeclared here as %q#D", parm);
4218           return false;
4219         }
4220
4221       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4222         {
4223           /* We have in [temp.param]:
4224
4225              A template-parameter may not be given default arguments
4226              by two different declarations in the same scope.  */
4227           error ("redefinition of default argument for %q#D", parm);
4228           inform ("%Joriginal definition appeared here", tmpl_parm);
4229           return false;
4230         }
4231
4232       if (parm_default != NULL_TREE)
4233         /* Update the previous template parameters (which are the ones
4234            that will really count) with the new default value.  */
4235         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4236       else if (tmpl_default != NULL_TREE)
4237         /* Update the new parameters, too; they'll be used as the
4238            parameters for any members.  */
4239         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4240     }
4241
4242     return true;
4243 }
4244
4245 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4246    (possibly simplified) expression.  */
4247
4248 tree
4249 fold_non_dependent_expr (tree expr)
4250 {
4251   if (expr == NULL_TREE)
4252     return NULL_TREE;
4253
4254   /* If we're in a template, but EXPR isn't value dependent, simplify
4255      it.  We're supposed to treat:
4256
4257        template <typename T> void f(T[1 + 1]);
4258        template <typename T> void f(T[2]);
4259
4260      as two declarations of the same function, for example.  */
4261   if (processing_template_decl
4262       && !type_dependent_expression_p (expr)
4263       && !value_dependent_expression_p (expr))
4264     {
4265       HOST_WIDE_INT saved_processing_template_decl;
4266
4267       saved_processing_template_decl = processing_template_decl;
4268       processing_template_decl = 0;
4269       expr = tsubst_copy_and_build (expr,
4270                                     /*args=*/NULL_TREE,
4271                                     tf_error,
4272                                     /*in_decl=*/NULL_TREE,
4273                                     /*function_p=*/false,
4274                                     /*integral_constant_expression_p=*/true);
4275       processing_template_decl = saved_processing_template_decl;
4276     }
4277   return expr;
4278 }
4279
4280 /* EXPR is an expression which is used in a constant-expression context.
4281    For instance, it could be a VAR_DECL with a constant initializer.
4282    Extract the innest constant expression.
4283
4284    This is basically a more powerful version of
4285    integral_constant_value, which can be used also in templates where
4286    initializers can maintain a syntactic rather than semantic form
4287    (even if they are non-dependent, for access-checking purposes).  */
4288
4289 static tree
4290 fold_decl_constant_value (tree expr)
4291 {
4292   tree const_expr = expr;
4293   do
4294     {
4295       expr = fold_non_dependent_expr (const_expr);
4296       const_expr = integral_constant_value (expr);
4297     }
4298   while (expr != const_expr);
4299
4300   return expr;
4301 }
4302
4303 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4304    must be a function or a pointer-to-function type, as specified
4305    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4306    and check that the resulting function has external linkage.  */
4307
4308 static tree
4309 convert_nontype_argument_function (tree type, tree expr)
4310 {
4311   tree fns = expr;
4312   tree fn, fn_no_ptr;
4313
4314   fn = instantiate_type (type, fns, tf_none);
4315   if (fn == error_mark_node)
4316     return error_mark_node;
4317
4318   fn_no_ptr = fn;
4319   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4320     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4321   if (TREE_CODE (fn_no_ptr) == BASELINK)
4322     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4323  
4324   /* [temp.arg.nontype]/1
4325
4326      A template-argument for a non-type, non-template template-parameter
4327      shall be one of:
4328      [...]
4329      -- the address of an object or function with external linkage.  */
4330   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4331     {
4332       error ("%qE is not a valid template argument for type %qT "
4333              "because function %qD has not external linkage",
4334              expr, type, fn_no_ptr);
4335       return NULL_TREE;
4336     }
4337
4338   return fn;
4339 }
4340
4341 /* Attempt to convert the non-type template parameter EXPR to the
4342    indicated TYPE.  If the conversion is successful, return the
4343    converted value.  If the conversion is unsuccessful, return
4344    NULL_TREE if we issued an error message, or error_mark_node if we
4345    did not.  We issue error messages for out-and-out bad template
4346    parameters, but not simply because the conversion failed, since we
4347    might be just trying to do argument deduction.  Both TYPE and EXPR
4348    must be non-dependent.
4349
4350    The conversion follows the special rules described in
4351    [temp.arg.nontype], and it is much more strict than an implicit
4352    conversion.
4353
4354    This function is called twice for each template argument (see
4355    lookup_template_class for a more accurate description of this
4356    problem). This means that we need to handle expressions which
4357    are not valid in a C++ source, but can be created from the
4358    first call (for instance, casts to perform conversions). These
4359    hacks can go away after we fix the double coercion problem.  */
4360
4361 static tree
4362 convert_nontype_argument (tree type, tree expr)
4363 {
4364   tree expr_type;
4365
4366   /* Detect immediately string literals as invalid non-type argument.
4367      This special-case is not needed for correctness (we would easily
4368      catch this later), but only to provide better diagnostic for this
4369      common user mistake. As suggested by DR 100, we do not mention
4370      linkage issues in the diagnostic as this is not the point.  */
4371   if (TREE_CODE (expr) == STRING_CST)
4372     {
4373       error ("%qE is not a valid template argument for type %qT "
4374              "because string literals can never be used in this context",
4375              expr, type);
4376       return NULL_TREE;
4377     }
4378
4379   /* If we are in a template, EXPR may be non-dependent, but still
4380      have a syntactic, rather than semantic, form.  For example, EXPR
4381      might be a SCOPE_REF, rather than the VAR_DECL to which the
4382      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4383      so that access checking can be performed when the template is
4384      instantiated -- but here we need the resolved form so that we can
4385      convert the argument.  */
4386   expr = fold_non_dependent_expr (expr);
4387   if (error_operand_p (expr))
4388     return error_mark_node;
4389   expr_type = TREE_TYPE (expr);
4390
4391   /* HACK: Due to double coercion, we can get a
4392      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4393      which is the tree that we built on the first call (see
4394      below when coercing to reference to object or to reference to
4395      function). We just strip everything and get to the arg.
4396      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4397      for examples.  */
4398   if (TREE_CODE (expr) == NOP_EXPR)
4399     {
4400       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4401         {
4402           /* ??? Maybe we could use convert_from_reference here, but we
4403              would need to relax its constraints because the NOP_EXPR
4404              could actually change the type to something more cv-qualified,
4405              and this is not folded by convert_from_reference.  */
4406           tree addr = TREE_OPERAND (expr, 0);
4407           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4408           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4409           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4410           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4411                       (TREE_TYPE (expr_type),
4412                        TREE_TYPE (TREE_TYPE (addr))));
4413
4414           expr = TREE_OPERAND (addr, 0);
4415           expr_type = TREE_TYPE (expr);
4416         }
4417
4418       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4419          parameter is a pointer to object, through decay and
4420          qualification conversion. Let's strip everything.  */
4421       else if (TYPE_PTROBV_P (type))
4422         {
4423           STRIP_NOPS (expr);
4424           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4425           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4426           /* Skip the ADDR_EXPR only if it is part of the decay for
4427              an array. Otherwise, it is part of the original argument
4428              in the source code.  */
4429           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4430             expr = TREE_OPERAND (expr, 0);
4431           expr_type = TREE_TYPE (expr);
4432         }
4433     }
4434
4435   /* [temp.arg.nontype]/5, bullet 1
4436
4437      For a non-type template-parameter of integral or enumeration type,
4438      integral promotions (_conv.prom_) and integral conversions
4439      (_conv.integral_) are applied.  */
4440   if (INTEGRAL_TYPE_P (type))
4441     {
4442       if (!INTEGRAL_TYPE_P (expr_type))
4443         return error_mark_node;
4444
4445       expr = fold_decl_constant_value (expr);
4446       /* Notice that there are constant expressions like '4 % 0' which
4447          do not fold into integer constants.  */
4448       if (TREE_CODE (expr) != INTEGER_CST)
4449         {
4450           error ("%qE is not a valid template argument for type %qT "
4451                  "because it is a non-constant expression", expr, type);
4452           return NULL_TREE;
4453         }
4454
4455       /* At this point, an implicit conversion does what we want,
4456          because we already know that the expression is of integral
4457          type.  */
4458       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4459       if (expr == error_mark_node)
4460         return error_mark_node;
4461
4462       /* Conversion was allowed: fold it to a bare integer constant.  */
4463       expr = fold (expr);
4464     }
4465   /* [temp.arg.nontype]/5, bullet 2
4466
4467      For a non-type template-parameter of type pointer to object,
4468      qualification conversions (_conv.qual_) and the array-to-pointer
4469      conversion (_conv.array_) are applied.  */
4470   else if (TYPE_PTROBV_P (type))
4471     {
4472       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4473
4474          A template-argument for a non-type, non-template template-parameter
4475          shall be one of: [...]
4476
4477          -- the name of a non-type template-parameter;
4478          -- the address of an object or function with external linkage, [...]
4479             expressed as "& id-expression" where the & is optional if the name
4480             refers to a function or array, or if the corresponding
4481             template-parameter is a reference.
4482
4483         Here, we do not care about functions, as they are invalid anyway
4484         for a parameter of type pointer-to-object.  */
4485
4486       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4487         /* Non-type template parameters are OK.  */
4488         ;
4489       else if (TREE_CODE (expr) != ADDR_EXPR
4490                && TREE_CODE (expr_type) != ARRAY_TYPE)
4491         {
4492           if (TREE_CODE (expr) == VAR_DECL)
4493             {
4494               error ("%qD is not a valid template argument "
4495                      "because %qD is a variable, not the address of "
4496                      "a variable",
4497                      expr, expr);
4498               return NULL_TREE;
4499             }
4500           /* Other values, like integer constants, might be valid
4501              non-type arguments of some other type.  */
4502           return error_mark_node;
4503         }
4504       else
4505         {
4506           tree decl;
4507
4508           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4509                   ? TREE_OPERAND (expr, 0) : expr);
4510           if (TREE_CODE (decl) != VAR_DECL)
4511             {
4512               error ("%qE is not a valid template argument of type %qT "
4513                      "because %qE is not a variable",
4514                      expr, type, decl);
4515               return NULL_TREE;
4516             }
4517           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4518             {
4519               error ("%qE is not a valid template argument of type %qT "
4520                      "because %qD does not have external linkage",
4521                      expr, type, decl);
4522               return NULL_TREE;
4523             }
4524         }
4525
4526       expr = decay_conversion (expr);
4527       if (expr == error_mark_node)
4528         return error_mark_node;
4529
4530       expr = perform_qualification_conversions (type, expr);
4531       if (expr == error_mark_node)
4532         return error_mark_node;
4533     }
4534   /* [temp.arg.nontype]/5, bullet 3
4535
4536      For a non-type template-parameter of type reference to object, no
4537      conversions apply. The type referred to by the reference may be more
4538      cv-qualified than the (otherwise identical) type of the
4539      template-argument. The template-parameter is bound directly to the
4540      template-argument, which must be an lvalue.  */
4541   else if (TYPE_REF_OBJ_P (type))
4542     {
4543       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4544                                                       expr_type))
4545         return error_mark_node;
4546
4547       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4548         {
4549           error ("%qE is not a valid template argument for type %qT "
4550                  "because of conflicts in cv-qualification", expr, type);
4551           return NULL_TREE;
4552         }
4553
4554       if (!real_lvalue_p (expr))
4555         {
4556           error ("%qE is not a valid template argument for type %qT "
4557                  "because it is not an lvalue", expr, type);
4558           return NULL_TREE;
4559         }
4560
4561       /* [temp.arg.nontype]/1
4562
4563          A template-argument for a non-type, non-template template-parameter
4564          shall be one of: [...]
4565
4566          -- the address of an object or function with external linkage.  */
4567       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4568         {
4569           error ("%qE is not a valid template argument for type %qT "
4570                  "because object %qD has not external linkage",
4571                  expr, type, expr);
4572           return NULL_TREE;
4573         }
4574
4575       expr = build_nop (type, build_address (expr));
4576     }
4577   /* [temp.arg.nontype]/5, bullet 4
4578
4579      For a non-type template-parameter of type pointer to function, only
4580      the function-to-pointer conversion (_conv.func_) is applied. If the
4581      template-argument represents a set of overloaded functions (or a
4582      pointer to such), the matching function is selected from the set
4583      (_over.over_).  */
4584   else if (TYPE_PTRFN_P (type))
4585     {
4586       /* If the argument is a template-id, we might not have enough
4587          context information to decay the pointer.  */
4588       if (!type_unknown_p (expr_type))
4589         {
4590           expr = decay_conversion (expr);
4591           if (expr == error_mark_node)
4592             return error_mark_node;
4593         }
4594
4595       expr = convert_nontype_argument_function (type, expr);
4596       if (!expr || expr == error_mark_node)
4597         return expr;
4598     }
4599   /* [temp.arg.nontype]/5, bullet 5
4600
4601      For a non-type template-parameter of type reference to function, no
4602      conversions apply. If the template-argument represents a set of
4603      overloaded functions, the matching function is selected from the set
4604      (_over.over_).  */
4605   else if (TYPE_REFFN_P (type))
4606     {
4607       if (TREE_CODE (expr) == ADDR_EXPR)
4608         {
4609           error ("%qE is not a valid template argument for type %qT "
4610                  "because it is a pointer", expr, type);
4611           inform ("try using %qE instead", TREE_OPERAND (expr, 0));
4612           return NULL_TREE;
4613         }
4614
4615       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4616       if (!expr || expr == error_mark_node)
4617         return expr;
4618
4619       expr = build_nop (type, build_address (expr));
4620     }
4621   /* [temp.arg.nontype]/5, bullet 6
4622
4623      For a non-type template-parameter of type pointer to member function,
4624      no conversions apply. If the template-argument represents a set of
4625      overloaded member functions, the matching member function is selected
4626      from the set (_over.over_).  */
4627   else if (TYPE_PTRMEMFUNC_P (type))
4628     {
4629       expr = instantiate_type (type, expr, tf_none);
4630       if (expr == error_mark_node)
4631         return error_mark_node;
4632
4633       /* There is no way to disable standard conversions in
4634          resolve_address_of_overloaded_function (called by
4635          instantiate_type). It is possible that the call succeeded by
4636          converting &B::I to &D::I (where B is a base of D), so we need
4637          to reject this conversion here.
4638
4639          Actually, even if there was a way to disable standard conversions,
4640          it would still be better to reject them here so that we can
4641          provide a superior diagnostic.  */
4642       if (!same_type_p (TREE_TYPE (expr), type))
4643         {
4644           /* Make sure we are just one standard conversion off.  */
4645           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4646           error ("%qE is not a valid template argument for type %qT "
4647                  "because it is of type %qT", expr, type,
4648                  TREE_TYPE (expr));
4649           inform ("standard conversions are not allowed in this context");
4650           return NULL_TREE;
4651         }
4652     }
4653   /* [temp.arg.nontype]/5, bullet 7
4654
4655      For a non-type template-parameter of type pointer to data member,
4656      qualification conversions (_conv.qual_) are applied.  */
4657   else if (TYPE_PTRMEM_P (type))
4658     {
4659       expr = perform_qualification_conversions (type, expr);
4660       if (expr == error_mark_node)
4661         return expr;
4662     }
4663   /* A template non-type parameter must be one of the above.  */
4664   else
4665     gcc_unreachable ();
4666
4667   /* Sanity check: did we actually convert the argument to the
4668      right type?  */
4669   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4670   return expr;
4671 }
4672
4673
4674 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4675    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4676    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4677    or PARM_DECL.
4678
4679    Consider the example:
4680      template <class T> class A;
4681      template<template <class U> class TT> class B;
4682
4683    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4684    the parameters to A, and OUTER_ARGS contains A.  */
4685
4686 static int
4687 coerce_template_template_parms (tree parm_parms,
4688                                 tree arg_parms,
4689                                 tsubst_flags_t complain,
4690                                 tree in_decl,
4691                                 tree outer_args)
4692 {
4693   int nparms, nargs, i;
4694   tree parm, arg;
4695
4696   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4697   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4698
4699   nparms = TREE_VEC_LENGTH (parm_parms);
4700   nargs = TREE_VEC_LENGTH (arg_parms);
4701
4702   if (nargs != nparms)
4703     return 0;
4704
4705   for (i = 0; i < nparms; ++i)
4706     {
4707       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4708           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4709         continue;
4710
4711       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4712       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4713
4714       if (arg == NULL_TREE || arg == error_mark_node
4715           || parm == NULL_TREE || parm == error_mark_node)
4716         return 0;
4717
4718       if (TREE_CODE (arg) != TREE_CODE (parm))
4719         return 0;
4720
4721       switch (TREE_CODE (parm))
4722         {
4723         case TEMPLATE_DECL:
4724           /* We encounter instantiations of templates like
4725                template <template <template <class> class> class TT>
4726                class C;  */
4727           {
4728             tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4729             tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4730
4731             if (!coerce_template_template_parms
4732                 (parmparm, argparm, complain, in_decl, outer_args))
4733               return 0;
4734           }
4735           /* Fall through.  */
4736
4737         case TYPE_DECL:
4738           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))
4739               != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg)))
4740             /* One is a parameter pack, the other is not.  */
4741             return 0;
4742           break;
4743
4744         case PARM_DECL:
4745           /* The tsubst call is used to handle cases such as
4746
4747                template <int> class C {};
4748                template <class T, template <T> class TT> class D {};
4749                D<int, C> d;
4750
4751              i.e. the parameter list of TT depends on earlier parameters.  */
4752           if (!dependent_type_p (TREE_TYPE (arg))
4753               && !same_type_p
4754                     (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4755                              TREE_TYPE (arg)))
4756             return 0;
4757
4758           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4759               != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg)))
4760             /* One is a parameter pack, the other is not.  */
4761             return 0;
4762           break;
4763
4764         default:
4765           gcc_unreachable ();
4766         }
4767     }
4768   return 1;
4769 }
4770
4771 /* Verifies that the deduced template arguments (in TARGS) for the
4772    template template parameters (in TPARMS) represent valid bindings,
4773    by comparing the template parameter list of each template argument
4774    to the template parameter list of its corresponding template
4775    template parameter, in accordance with DR150. This
4776    routine can only be called after all template arguments have been
4777    deduced. It will return TRUE if all of the template template
4778    parameter bindings are okay, FALSE otherwise.  */
4779 bool 
4780 template_template_parm_bindings_ok_p (tree tparms, tree targs)
4781 {
4782   int i, ntparms = TREE_VEC_LENGTH (tparms);
4783
4784   targs = INNERMOST_TEMPLATE_ARGS (targs);
4785
4786   for (i = 0; i < ntparms; ++i)
4787     {
4788       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
4789       tree targ = TREE_VEC_ELT (targs, i);
4790
4791       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
4792         {
4793           tree packed_args = NULL_TREE;
4794           int idx, len = 1;
4795
4796           if (ARGUMENT_PACK_P (targ))
4797             {
4798               /* Look inside the argument pack.  */
4799               packed_args = ARGUMENT_PACK_ARGS (targ);
4800               len = TREE_VEC_LENGTH (packed_args);
4801             }
4802
4803           for (idx = 0; idx < len; ++idx)
4804             {
4805               tree targ_parms = NULL_TREE;
4806
4807               if (packed_args)
4808                 /* Extract the next argument from the argument
4809                    pack.  */
4810                 targ = TREE_VEC_ELT (packed_args, idx);
4811
4812               if (PACK_EXPANSION_P (targ))
4813                 /* Look at the pattern of the pack expansion.  */
4814                 targ = PACK_EXPANSION_PATTERN (targ);
4815
4816               /* Extract the template parameters from the template
4817                  argument.  */
4818               if (TREE_CODE (targ) == TEMPLATE_DECL)
4819                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
4820               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
4821                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
4822
4823               /* Verify that we can coerce the template template
4824                  parameters from the template argument to the template
4825                  parameter.  This requires an exact match.  */
4826               if (targ_parms
4827                   && !coerce_template_template_parms
4828                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
4829                         targ_parms,
4830                         tf_none,
4831                         tparm,
4832                         targs))
4833                 return false;
4834             }
4835         }
4836     }
4837
4838   /* Everything is okay.  */
4839   return true;
4840 }
4841
4842 /* Convert the indicated template ARG as necessary to match the
4843    indicated template PARM.  Returns the converted ARG, or
4844    error_mark_node if the conversion was unsuccessful.  Error and
4845    warning messages are issued under control of COMPLAIN.  This
4846    conversion is for the Ith parameter in the parameter list.  ARGS is
4847    the full set of template arguments deduced so far.  */
4848
4849 static tree
4850 convert_template_argument (tree parm,
4851                            tree arg,
4852                            tree args,
4853                            tsubst_flags_t complain,
4854                            int i,
4855                            tree in_decl)
4856 {
4857   tree orig_arg;
4858   tree val;
4859   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4860
4861   if (TREE_CODE (arg) == TREE_LIST
4862       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4863     {
4864       /* The template argument was the name of some
4865          member function.  That's usually
4866          invalid, but static members are OK.  In any
4867          case, grab the underlying fields/functions
4868          and issue an error later if required.  */
4869       orig_arg = TREE_VALUE (arg);
4870       TREE_TYPE (arg) = unknown_type_node;
4871     }
4872
4873   orig_arg = arg;
4874
4875   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4876   requires_type = (TREE_CODE (parm) == TYPE_DECL
4877                    || requires_tmpl_type);
4878
4879   /* When determining whether an argument pack expansion is a template,
4880      look at the pattern.  */
4881   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
4882     arg = PACK_EXPANSION_PATTERN (arg);
4883
4884   is_tmpl_type = 
4885     ((TREE_CODE (arg) == TEMPLATE_DECL
4886       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
4887      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4888      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
4889
4890   if (is_tmpl_type
4891       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4892           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4893     arg = TYPE_STUB_DECL (arg);
4894
4895   is_type = TYPE_P (arg) || is_tmpl_type;
4896
4897   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4898       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4899     {
4900       pedwarn ("to refer to a type member of a template parameter, "
4901                "use %<typename %E%>", orig_arg);
4902
4903       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
4904                                      TREE_OPERAND (arg, 1),
4905                                      typename_type,
4906                                      complain & tf_error);
4907       arg = orig_arg;
4908       is_type = 1;
4909     }
4910   if (is_type != requires_type)
4911     {
4912       if (in_decl)
4913         {
4914           if (complain & tf_error)
4915             {
4916               error ("type/value mismatch at argument %d in template "
4917                      "parameter list for %qD",
4918                      i + 1, in_decl);
4919               if (is_type)
4920                 error ("  expected a constant of type %qT, got %qT",
4921                        TREE_TYPE (parm),
4922                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
4923               else if (requires_tmpl_type)
4924                 error ("  expected a class template, got %qE", orig_arg);
4925               else
4926                 error ("  expected a type, got %qE", orig_arg);
4927             }
4928         }
4929       return error_mark_node;
4930     }
4931   if (is_tmpl_type ^ requires_tmpl_type)
4932     {
4933       if (in_decl && (complain & tf_error))
4934         {
4935           error ("type/value mismatch at argument %d in template "
4936                  "parameter list for %qD",
4937                  i + 1, in_decl);
4938           if (is_tmpl_type)
4939             error ("  expected a type, got %qT", DECL_NAME (arg));
4940           else
4941             error ("  expected a class template, got %qT", orig_arg);
4942         }
4943       return error_mark_node;
4944     }
4945
4946   if (is_type)
4947     {
4948       if (requires_tmpl_type)
4949         {
4950           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
4951             /* The number of argument required is not known yet.
4952                Just accept it for now.  */
4953             val = TREE_TYPE (arg);
4954           else
4955             {
4956               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4957               tree argparm;
4958
4959               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4960
4961               if (coerce_template_template_parms (parmparm, argparm,
4962                                                   complain, in_decl,
4963                                                   args))
4964                 {
4965                   val = orig_arg;
4966
4967                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
4968                      TEMPLATE_DECL.  */
4969                   if (val != error_mark_node)
4970                     {
4971                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
4972                         val = TREE_TYPE (val);
4973                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
4974                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
4975                         {
4976                           val = TREE_TYPE (arg);
4977                           val = make_pack_expansion (val);
4978                         }
4979                     }
4980                 }
4981               else
4982                 {
4983                   if (in_decl && (complain & tf_error))
4984                     {
4985                       error ("type/value mismatch at argument %d in "
4986                              "template parameter list for %qD",
4987                              i + 1, in_decl);
4988                       error ("  expected a template of type %qD, got %qD",
4989                              parm, orig_arg);
4990                     }
4991
4992                   val = error_mark_node;
4993                 }
4994             }
4995         }
4996       else
4997         val = orig_arg;
4998       /* We only form one instance of each template specialization.
4999          Therefore, if we use a non-canonical variant (i.e., a
5000          typedef), any future messages referring to the type will use
5001          the typedef, which is confusing if those future uses do not
5002          themselves also use the typedef.  */
5003       if (TYPE_P (val))
5004         val = canonical_type_variant (val);
5005     }
5006   else
5007     {
5008       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5009
5010       if (invalid_nontype_parm_type_p (t, complain))
5011         return error_mark_node;
5012
5013       if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5014         /* We used to call digest_init here.  However, digest_init
5015            will report errors, which we don't want when complain
5016            is zero.  More importantly, digest_init will try too
5017            hard to convert things: for example, `0' should not be
5018            converted to pointer type at this point according to
5019            the standard.  Accepting this is not merely an
5020            extension, since deciding whether or not these
5021            conversions can occur is part of determining which
5022            function template to call, or whether a given explicit
5023            argument specification is valid.  */
5024         val = convert_nontype_argument (t, orig_arg);
5025       else
5026         val = orig_arg;
5027
5028       if (val == NULL_TREE)
5029         val = error_mark_node;
5030       else if (val == error_mark_node && (complain & tf_error))
5031         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5032     }
5033
5034   return val;
5035 }
5036
5037 /* Coerces the remaining template arguments in INNER_ARGS (from
5038    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5039    Returns the coerced argument pack. PARM_IDX is the position of this
5040    parameter in the template parameter list. ARGS is the original
5041    template argument list.  */
5042 static tree
5043 coerce_template_parameter_pack (tree parms,
5044                                 int parm_idx,
5045                                 tree args,
5046                                 tree inner_args,
5047                                 int arg_idx,
5048                                 tree new_args,
5049                                 int* lost,
5050                                 tree in_decl,
5051                                 tsubst_flags_t complain)
5052 {
5053   tree parm = TREE_VEC_ELT (parms, parm_idx);
5054   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5055   tree packed_args;
5056   tree argument_pack;
5057   tree packed_types = NULL_TREE;
5058
5059   if (arg_idx > nargs)
5060     arg_idx = nargs;
5061
5062   packed_args = make_tree_vec (nargs - arg_idx);
5063
5064   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5065       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5066     {
5067       /* When the template parameter is a non-type template
5068          parameter pack whose type uses parameter packs, we need
5069          to look at each of the template arguments
5070          separately. Build a vector of the types for these
5071          non-type template parameters in PACKED_TYPES.  */
5072       tree expansion 
5073         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5074       packed_types = tsubst_pack_expansion (expansion, args,
5075                                             complain, in_decl);
5076
5077       if (packed_types == error_mark_node)
5078         return error_mark_node;
5079
5080       /* Check that we have the right number of arguments.  */
5081       if (arg_idx < nargs
5082           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5083           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5084         {
5085           int needed_parms 
5086             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5087           error ("wrong number of template arguments (%d, should be %d)",
5088                  nargs, needed_parms);
5089           return error_mark_node;
5090         }
5091
5092       /* If we aren't able to check the actual arguments now
5093          (because they haven't been expanded yet), we can at least
5094          verify that all of the types used for the non-type
5095          template parameter pack are, in fact, valid for non-type
5096          template parameters.  */
5097       if (arg_idx < nargs 
5098           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5099         {
5100           int j, len = TREE_VEC_LENGTH (packed_types);
5101           for (j = 0; j < len; ++j)
5102             {
5103               tree t = TREE_VEC_ELT (packed_types, j);
5104               if (invalid_nontype_parm_type_p (t, complain))
5105                 return error_mark_node;
5106             }
5107         }
5108     }
5109
5110   /* Convert the remaining arguments, which will be a part of the
5111      parameter pack "parm".  */
5112   for (; arg_idx < nargs; ++arg_idx)
5113     {
5114       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5115       tree actual_parm = TREE_VALUE (parm);
5116
5117       if (packed_types && !PACK_EXPANSION_P (arg))
5118         {
5119           /* When we have a vector of types (corresponding to the
5120              non-type template parameter pack that uses parameter
5121              packs in its type, as mention above), and the
5122              argument is not an expansion (which expands to a
5123              currently unknown number of arguments), clone the
5124              parm and give it the next type in PACKED_TYPES.  */
5125           actual_parm = copy_node (actual_parm);
5126           TREE_TYPE (actual_parm) = 
5127             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5128         }
5129
5130       if (arg != error_mark_node)
5131         arg = convert_template_argument (actual_parm, 
5132                                          arg, new_args, complain, parm_idx,
5133                                          in_decl);
5134       if (arg == error_mark_node)
5135         (*lost)++;
5136       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5137     }
5138
5139   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5140       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5141     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5142   else
5143     {
5144       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5145       TREE_TYPE (argument_pack) 
5146         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5147       TREE_CONSTANT (argument_pack) = 1;
5148     }
5149
5150   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5151   return argument_pack;
5152 }
5153
5154 /* Convert all template arguments to their appropriate types, and
5155    return a vector containing the innermost resulting template
5156    arguments.  If any error occurs, return error_mark_node. Error and
5157    warning messages are issued under control of COMPLAIN.
5158
5159    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5160    for arguments not specified in ARGS.  Otherwise, if
5161    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5162    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5163    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5164    ARGS.  */
5165
5166 static tree
5167 coerce_template_parms (tree parms,
5168                        tree args,
5169                        tree in_decl,
5170                        tsubst_flags_t complain,
5171                        bool require_all_args,
5172                        bool use_default_args)
5173 {
5174   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5175   tree inner_args;
5176   tree new_args;
5177   tree new_inner_args;
5178   bool saved_skip_evaluation;
5179
5180   /* When used as a boolean value, indicates whether this is a
5181      variadic template parameter list. Since it's an int, we can also
5182      subtract it from nparms to get the number of non-variadic
5183      parameters.  */
5184   int variadic_p = 0;
5185
5186   inner_args 
5187     = expand_template_argument_pack (INNERMOST_TEMPLATE_ARGS (args));
5188
5189   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5190   nparms = TREE_VEC_LENGTH (parms);
5191
5192   /* Determine if there are any parameter packs.  */
5193   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5194     {
5195       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5196       if (template_parameter_pack_p (tparm))
5197         {
5198           variadic_p = 1;
5199           break;
5200         }
5201     }
5202
5203   if ((nargs > nparms - variadic_p && !variadic_p)
5204       || (nargs < nparms - variadic_p
5205           && require_all_args
5206           && (!use_default_args
5207               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5208                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5209     {
5210       if (complain & tf_error)
5211         {
5212           const char *or_more = "";
5213           if (variadic_p)
5214             {
5215               or_more = " or more";
5216               --nparms;
5217             }
5218
5219           error ("wrong number of template arguments (%d, should be %d%s)",
5220                  nargs, nparms, or_more);
5221
5222           if (in_decl)
5223             error ("provided for %q+D", in_decl);
5224         }
5225
5226       return error_mark_node;
5227     }
5228
5229   /* We need to evaluate the template arguments, even though this
5230      template-id may be nested within a "sizeof".  */
5231   saved_skip_evaluation = skip_evaluation;
5232   skip_evaluation = false;
5233   new_inner_args = make_tree_vec (nparms);
5234   new_args = add_outermost_template_args (args, new_inner_args);
5235   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5236     {
5237       tree arg;
5238       tree parm;
5239
5240       /* Get the Ith template parameter.  */
5241       parm = TREE_VEC_ELT (parms, parm_idx);
5242  
5243       if (parm == error_mark_node)
5244       {
5245         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5246         continue;
5247       }
5248
5249       /* Calculate the next argument.  */
5250       if (template_parameter_pack_p (TREE_VALUE (parm)))
5251         {
5252           /* All remaining arguments will be placed in the
5253              template parameter pack PARM.  */
5254           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5255                                                 inner_args, arg_idx,
5256                                                 new_args, &lost,
5257                                                 in_decl, complain);
5258           
5259           /* Store this argument.  */
5260           if (arg == error_mark_node)
5261             lost++;
5262           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5263
5264           /* We are done with all of the arguments.  */
5265           arg_idx = nargs;
5266
5267           continue;
5268         }
5269       else if (arg_idx < nargs)
5270         {
5271           arg = TREE_VEC_ELT (inner_args, arg_idx);
5272
5273           if (arg && PACK_EXPANSION_P (arg))
5274             {
5275               if (complain & tf_error)
5276                 {
5277                   /* If ARG is a pack expansion, but PARM is not a
5278                      template parameter pack (if it were, we would have
5279                      handled it above), we're trying to expand into a
5280                      fixed-length argument list.  */
5281                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5282                     error ("cannot expand %<%E%> into a fixed-length "
5283                            "argument list", arg);
5284                   else
5285                     error ("cannot expand %<%T%> into a fixed-length "
5286                            "argument list", arg);
5287                 }
5288               return error_mark_node;
5289             }
5290         }
5291       else if (require_all_args)
5292         /* There must be a default arg in this case.  */
5293         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5294                                    complain, in_decl);
5295       else
5296         break;
5297
5298       if (arg == error_mark_node)
5299         {
5300           if (complain & tf_error)
5301             error ("template argument %d is invalid", arg_idx + 1);
5302         }
5303       else if (!arg)
5304         /* This only occurs if there was an error in the template
5305            parameter list itself (which we would already have
5306            reported) that we are trying to recover from, e.g., a class
5307            template with a parameter list such as
5308            template<typename..., typename>.  */
5309         return error_mark_node;
5310       else
5311         arg = convert_template_argument (TREE_VALUE (parm),
5312                                          arg, new_args, complain, 
5313                                          parm_idx, in_decl);
5314
5315       if (arg == error_mark_node)
5316         lost++;
5317       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5318     }
5319   skip_evaluation = saved_skip_evaluation;
5320
5321   if (lost)
5322     return error_mark_node;
5323
5324   return new_inner_args;
5325 }
5326
5327 /* Returns 1 if template args OT and NT are equivalent.  */
5328
5329 static int
5330 template_args_equal (tree ot, tree nt)
5331 {
5332   if (nt == ot)
5333     return 1;
5334
5335   if (TREE_CODE (nt) == TREE_VEC)
5336     /* For member templates */
5337     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5338   else if (PACK_EXPANSION_P (ot))
5339     return PACK_EXPANSION_P (nt) 
5340       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5341                               PACK_EXPANSION_PATTERN (nt));
5342   else if (TYPE_P (nt))
5343     return TYPE_P (ot) && same_type_p (ot, nt);
5344   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5345     return 0;
5346   else
5347     return cp_tree_equal (ot, nt);
5348 }
5349
5350 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5351    of template arguments.  Returns 0 otherwise.  */
5352
5353 int
5354 comp_template_args (tree oldargs, tree newargs)
5355 {
5356   int i;
5357
5358   oldargs = expand_template_argument_pack (oldargs);
5359   newargs = expand_template_argument_pack (newargs);
5360
5361   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5362     return 0;
5363
5364   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5365     {
5366       tree nt = TREE_VEC_ELT (newargs, i);
5367       tree ot = TREE_VEC_ELT (oldargs, i);
5368
5369       if (! template_args_equal (ot, nt))
5370         return 0;
5371     }
5372   return 1;
5373 }
5374
5375 static void
5376 add_pending_template (tree d)
5377 {
5378   tree ti = (TYPE_P (d)
5379              ? CLASSTYPE_TEMPLATE_INFO (d)
5380              : DECL_TEMPLATE_INFO (d));
5381   struct pending_template *pt;
5382   int level;
5383
5384   if (TI_PENDING_TEMPLATE_FLAG (ti))
5385     return;
5386
5387   /* We are called both from instantiate_decl, where we've already had a
5388      tinst_level pushed, and instantiate_template, where we haven't.
5389      Compensate.  */
5390   level = !current_tinst_level || current_tinst_level->decl != d;
5391
5392   if (level)
5393     push_tinst_level (d);
5394
5395   pt = GGC_NEW (struct pending_template);
5396   pt->next = NULL;
5397   pt->tinst = current_tinst_level;
5398   if (last_pending_template)
5399     last_pending_template->next = pt;
5400   else
5401     pending_templates = pt;
5402
5403   last_pending_template = pt;
5404
5405   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5406
5407   if (level)
5408     pop_tinst_level ();
5409 }
5410
5411
5412 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5413    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5414    documentation for TEMPLATE_ID_EXPR.  */
5415
5416 tree
5417 lookup_template_function (tree fns, tree arglist)
5418 {
5419   tree type;
5420
5421   if (fns == error_mark_node || arglist == error_mark_node)
5422     return error_mark_node;
5423
5424   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5425   gcc_assert (fns && (is_overloaded_fn (fns)
5426                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5427
5428   if (BASELINK_P (fns))
5429     {
5430       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5431                                          unknown_type_node,
5432                                          BASELINK_FUNCTIONS (fns),
5433                                          arglist);
5434       return fns;
5435     }
5436
5437   type = TREE_TYPE (fns);
5438   if (TREE_CODE (fns) == OVERLOAD || !type)
5439     type = unknown_type_node;
5440
5441   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5442 }
5443
5444 /* Within the scope of a template class S<T>, the name S gets bound
5445    (in build_self_reference) to a TYPE_DECL for the class, not a
5446    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5447    or one of its enclosing classes, and that type is a template,
5448    return the associated TEMPLATE_DECL.  Otherwise, the original
5449    DECL is returned.  */
5450
5451 tree
5452 maybe_get_template_decl_from_type_decl (tree decl)
5453 {
5454   return (decl != NULL_TREE
5455           && TREE_CODE (decl) == TYPE_DECL
5456           && DECL_ARTIFICIAL (decl)
5457           && CLASS_TYPE_P (TREE_TYPE (decl))
5458           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5459     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5460 }
5461
5462 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5463    parameters, find the desired type.
5464
5465    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5466
5467    IN_DECL, if non-NULL, is the template declaration we are trying to
5468    instantiate.
5469
5470    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5471    the class we are looking up.
5472
5473    Issue error and warning messages under control of COMPLAIN.
5474
5475    If the template class is really a local class in a template
5476    function, then the FUNCTION_CONTEXT is the function in which it is
5477    being instantiated.
5478
5479    ??? Note that this function is currently called *twice* for each
5480    template-id: the first time from the parser, while creating the
5481    incomplete type (finish_template_type), and the second type during the
5482    real instantiation (instantiate_template_class). This is surely something
5483    that we want to avoid. It also causes some problems with argument
5484    coercion (see convert_nontype_argument for more information on this).  */
5485
5486 tree
5487 lookup_template_class (tree d1,
5488                        tree arglist,
5489                        tree in_decl,
5490                        tree context,
5491                        int entering_scope,
5492                        tsubst_flags_t complain)
5493 {
5494   tree template = NULL_TREE, parmlist;
5495   tree t;
5496
5497   timevar_push (TV_NAME_LOOKUP);
5498
5499   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5500     {
5501       tree value = innermost_non_namespace_value (d1);
5502       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5503         template = value;
5504       else
5505         {
5506           if (context)
5507             push_decl_namespace (context);
5508           template = lookup_name (d1);
5509           template = maybe_get_template_decl_from_type_decl (template);
5510           if (context)
5511             pop_decl_namespace ();
5512         }
5513       if (template)
5514         context = DECL_CONTEXT (template);
5515     }
5516   else if (TREE_CODE (d1) == TYPE_DECL && IS_AGGR_TYPE (TREE_TYPE (d1)))
5517     {
5518       tree type = TREE_TYPE (d1);
5519
5520       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5521          an implicit typename for the second A.  Deal with it.  */
5522       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5523         type = TREE_TYPE (type);
5524
5525       if (CLASSTYPE_TEMPLATE_INFO (type))
5526         {
5527           template = CLASSTYPE_TI_TEMPLATE (type);
5528           d1 = DECL_NAME (template);
5529         }
5530     }
5531   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5532            || (TYPE_P (d1) && IS_AGGR_TYPE (d1)))
5533     {
5534       template = TYPE_TI_TEMPLATE (d1);
5535       d1 = DECL_NAME (template);
5536     }
5537   else if (TREE_CODE (d1) == TEMPLATE_DECL
5538            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5539     {
5540       template = d1;
5541       d1 = DECL_NAME (template);
5542       context = DECL_CONTEXT (template);
5543     }
5544
5545   /* Issue an error message if we didn't find a template.  */
5546   if (! template)
5547     {
5548       if (complain & tf_error)
5549         error ("%qT is not a template", d1);
5550       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5551     }
5552
5553   if (TREE_CODE (template) != TEMPLATE_DECL
5554          /* Make sure it's a user visible template, if it was named by
5555             the user.  */
5556       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (template)
5557           && !PRIMARY_TEMPLATE_P (template)))
5558     {
5559       if (complain & tf_error)
5560         {
5561           error ("non-template type %qT used as a template", d1);
5562           if (in_decl)
5563             error ("for template declaration %q+D", in_decl);
5564         }
5565       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5566     }
5567
5568   complain &= ~tf_user;
5569
5570   if (DECL_TEMPLATE_TEMPLATE_PARM_P (template))
5571     {
5572       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5573          template arguments */
5574
5575       tree parm;
5576       tree arglist2;
5577       tree outer;
5578
5579       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (template);
5580
5581       /* Consider an example where a template template parameter declared as
5582
5583            template <class T, class U = std::allocator<T> > class TT
5584
5585          The template parameter level of T and U are one level larger than
5586          of TT.  To proper process the default argument of U, say when an
5587          instantiation `TT<int>' is seen, we need to build the full
5588          arguments containing {int} as the innermost level.  Outer levels,
5589          available when not appearing as default template argument, can be
5590          obtained from the arguments of the enclosing template.
5591
5592          Suppose that TT is later substituted with std::vector.  The above
5593          instantiation is `TT<int, std::allocator<T> >' with TT at
5594          level 1, and T at level 2, while the template arguments at level 1
5595          becomes {std::vector} and the inner level 2 is {int}.  */
5596
5597       outer = DECL_CONTEXT (template);
5598       if (outer)
5599         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5600       else if (current_template_parms)
5601         /* This is an argument of the current template, so we haven't set
5602            DECL_CONTEXT yet.  */
5603         outer = current_template_args ();
5604
5605       if (outer)
5606         arglist = add_to_template_args (outer, arglist);
5607
5608       arglist2 = coerce_template_parms (parmlist, arglist, template,
5609                                         complain,
5610                                         /*require_all_args=*/true,
5611                                         /*use_default_args=*/true);
5612       if (arglist2 == error_mark_node
5613           || (!uses_template_parms (arglist2)
5614               && check_instantiated_args (template, arglist2, complain)))
5615         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5616
5617       parm = bind_template_template_parm (TREE_TYPE (template), arglist2);
5618       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5619     }
5620   else
5621     {
5622       tree template_type = TREE_TYPE (template);
5623       tree gen_tmpl;
5624       tree type_decl;
5625       tree found = NULL_TREE;
5626       int arg_depth;
5627       int parm_depth;
5628       int is_partial_instantiation;
5629
5630       gen_tmpl = most_general_template (template);
5631       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5632       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5633       arg_depth = TMPL_ARGS_DEPTH (arglist);
5634
5635       if (arg_depth == 1 && parm_depth > 1)
5636         {
5637           /* We've been given an incomplete set of template arguments.
5638              For example, given:
5639
5640                template <class T> struct S1 {
5641                  template <class U> struct S2 {};
5642                  template <class U> struct S2<U*> {};
5643                 };
5644
5645              we will be called with an ARGLIST of `U*', but the
5646              TEMPLATE will be `template <class T> template
5647              <class U> struct S1<T>::S2'.  We must fill in the missing
5648              arguments.  */
5649           arglist
5650             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (template)),
5651                                            arglist);
5652           arg_depth = TMPL_ARGS_DEPTH (arglist);
5653         }
5654
5655       /* Now we should have enough arguments.  */
5656       gcc_assert (parm_depth == arg_depth);
5657
5658       /* From here on, we're only interested in the most general
5659          template.  */
5660       template = gen_tmpl;
5661
5662       /* Calculate the BOUND_ARGS.  These will be the args that are
5663          actually tsubst'd into the definition to create the
5664          instantiation.  */
5665       if (parm_depth > 1)
5666         {
5667           /* We have multiple levels of arguments to coerce, at once.  */
5668           int i;
5669           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5670
5671           tree bound_args = make_tree_vec (parm_depth);
5672
5673           for (i = saved_depth,
5674                  t = DECL_TEMPLATE_PARMS (template);
5675                i > 0 && t != NULL_TREE;
5676                --i, t = TREE_CHAIN (t))
5677             {
5678               tree a = coerce_template_parms (TREE_VALUE (t),
5679                                               arglist, template,
5680                                               complain,
5681                                               /*require_all_args=*/true,
5682                                               /*use_default_args=*/true);
5683
5684               /* Don't process further if one of the levels fails.  */
5685               if (a == error_mark_node)
5686                 {
5687                   /* Restore the ARGLIST to its full size.  */
5688                   TREE_VEC_LENGTH (arglist) = saved_depth;
5689                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5690                 }
5691
5692               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5693
5694               /* We temporarily reduce the length of the ARGLIST so
5695                  that coerce_template_parms will see only the arguments
5696                  corresponding to the template parameters it is
5697                  examining.  */
5698               TREE_VEC_LENGTH (arglist)--;
5699             }
5700
5701           /* Restore the ARGLIST to its full size.  */
5702           TREE_VEC_LENGTH (arglist) = saved_depth;
5703
5704           arglist = bound_args;
5705         }
5706       else
5707         arglist
5708           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5709                                    INNERMOST_TEMPLATE_ARGS (arglist),
5710                                    template,
5711                                    complain,
5712                                    /*require_all_args=*/true,
5713                                    /*use_default_args=*/true);
5714
5715       if (arglist == error_mark_node)
5716         /* We were unable to bind the arguments.  */
5717         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5718
5719       /* In the scope of a template class, explicit references to the
5720          template class refer to the type of the template, not any
5721          instantiation of it.  For example, in:
5722
5723            template <class T> class C { void f(C<T>); }
5724
5725          the `C<T>' is just the same as `C'.  Outside of the
5726          class, however, such a reference is an instantiation.  */
5727       if (comp_template_args (TYPE_TI_ARGS (template_type),
5728                               arglist))
5729         {
5730           found = template_type;
5731
5732           if (!entering_scope && PRIMARY_TEMPLATE_P (template))
5733             {
5734               tree ctx;
5735
5736               for (ctx = current_class_type;
5737                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5738                    ctx = (TYPE_P (ctx)
5739                           ? TYPE_CONTEXT (ctx)
5740                           : DECL_CONTEXT (ctx)))
5741                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5742                   goto found_ctx;
5743
5744               /* We're not in the scope of the class, so the
5745                  TEMPLATE_TYPE is not the type we want after all.  */
5746               found = NULL_TREE;
5747             found_ctx:;
5748             }
5749         }
5750       if (found)
5751         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5752
5753       /* If we already have this specialization, return it.  */
5754       found = retrieve_specialization (template, arglist,
5755                                        /*class_specializations_p=*/false);
5756       if (found)
5757         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5758
5759       /* This type is a "partial instantiation" if any of the template
5760          arguments still involve template parameters.  Note that we set
5761          IS_PARTIAL_INSTANTIATION for partial specializations as
5762          well.  */
5763       is_partial_instantiation = uses_template_parms (arglist);
5764
5765       /* If the deduced arguments are invalid, then the binding
5766          failed.  */
5767       if (!is_partial_instantiation
5768           && check_instantiated_args (template,
5769                                       INNERMOST_TEMPLATE_ARGS (arglist),
5770                                       complain))
5771         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5772
5773       if (!is_partial_instantiation
5774           && !PRIMARY_TEMPLATE_P (template)
5775           && TREE_CODE (CP_DECL_CONTEXT (template)) == NAMESPACE_DECL)
5776         {
5777           found = xref_tag_from_type (TREE_TYPE (template),
5778                                       DECL_NAME (template),
5779                                       /*tag_scope=*/ts_global);
5780           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5781         }
5782
5783       context = tsubst (DECL_CONTEXT (template), arglist,
5784                         complain, in_decl);
5785       if (!context)
5786         context = global_namespace;
5787
5788       /* Create the type.  */
5789       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5790         {
5791           if (!is_partial_instantiation)
5792             {
5793               set_current_access_from_decl (TYPE_NAME (template_type));
5794               t = start_enum (TYPE_IDENTIFIER (template_type));
5795             }
5796           else
5797             /* We don't want to call start_enum for this type, since
5798                the values for the enumeration constants may involve
5799                template parameters.  And, no one should be interested
5800                in the enumeration constants for such a type.  */
5801             t = make_node (ENUMERAL_TYPE);
5802         }
5803       else
5804         {
5805           t = make_aggr_type (TREE_CODE (template_type));
5806           CLASSTYPE_DECLARED_CLASS (t)
5807             = CLASSTYPE_DECLARED_CLASS (template_type);
5808           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5809           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5810
5811           /* A local class.  Make sure the decl gets registered properly.  */
5812           if (context == current_function_decl)
5813             pushtag (DECL_NAME (template), t, /*tag_scope=*/ts_current);
5814
5815           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5816             /* This instantiation is another name for the primary
5817                template type. Set the TYPE_CANONICAL field
5818                appropriately. */
5819             TYPE_CANONICAL (t) = template_type;
5820           else if (any_template_arguments_need_structural_equality_p (arglist))
5821             /* Some of the template arguments require structural
5822                equality testing, so this template class requires
5823                structural equality testing. */
5824             SET_TYPE_STRUCTURAL_EQUALITY (t);
5825         }
5826
5827       /* If we called start_enum or pushtag above, this information
5828          will already be set up.  */
5829       if (!TYPE_NAME (t))
5830         {
5831           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5832
5833           type_decl = create_implicit_typedef (DECL_NAME (template), t);
5834           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5835           TYPE_STUB_DECL (t) = type_decl;
5836           DECL_SOURCE_LOCATION (type_decl)
5837             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5838         }
5839       else
5840         type_decl = TYPE_NAME (t);
5841
5842       TREE_PRIVATE (type_decl)
5843         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5844       TREE_PROTECTED (type_decl)
5845         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5846       DECL_IN_SYSTEM_HEADER (type_decl)
5847         = DECL_IN_SYSTEM_HEADER (template);
5848       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5849         {
5850           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5851           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5852         }
5853
5854       /* Set up the template information.  We have to figure out which
5855          template is the immediate parent if this is a full
5856          instantiation.  */
5857       if (parm_depth == 1 || is_partial_instantiation
5858           || !PRIMARY_TEMPLATE_P (template))
5859         /* This case is easy; there are no member templates involved.  */
5860         found = template;
5861       else
5862         {
5863           /* This is a full instantiation of a member template.  Look
5864              for a partial instantiation of which this is an instance.  */
5865
5866           for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
5867                found; found = TREE_CHAIN (found))
5868             {
5869               int success;
5870               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5871
5872               /* We only want partial instantiations, here, not
5873                  specializations or full instantiations.  */
5874               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5875                   || !uses_template_parms (TREE_VALUE (found)))
5876                 continue;
5877
5878               /* Temporarily reduce by one the number of levels in the
5879                  ARGLIST and in FOUND so as to avoid comparing the
5880                  last set of arguments.  */
5881               TREE_VEC_LENGTH (arglist)--;
5882               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
5883
5884               /* See if the arguments match.  If they do, then TMPL is
5885                  the partial instantiation we want.  */
5886               success = comp_template_args (TREE_PURPOSE (found), arglist);
5887
5888               /* Restore the argument vectors to their full size.  */
5889               TREE_VEC_LENGTH (arglist)++;
5890               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
5891
5892               if (success)
5893                 {
5894                   found = tmpl;
5895                   break;
5896                 }
5897             }
5898
5899           if (!found)
5900             {
5901               /* There was no partial instantiation. This happens
5902                  where C<T> is a member template of A<T> and it's used
5903                  in something like
5904
5905                   template <typename T> struct B { A<T>::C<int> m; };
5906                   B<float>;
5907
5908                  Create the partial instantiation.
5909                */
5910               TREE_VEC_LENGTH (arglist)--;
5911               found = tsubst (template, arglist, complain, NULL_TREE);
5912               TREE_VEC_LENGTH (arglist)++;
5913             }
5914         }
5915
5916       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
5917       DECL_TEMPLATE_INSTANTIATIONS (template)
5918         = tree_cons (arglist, t,
5919                      DECL_TEMPLATE_INSTANTIATIONS (template));
5920
5921       if (TREE_CODE (t) == ENUMERAL_TYPE
5922           && !is_partial_instantiation)
5923         /* Now that the type has been registered on the instantiations
5924            list, we set up the enumerators.  Because the enumeration
5925            constants may involve the enumeration type itself, we make
5926            sure to register the type first, and then create the
5927            constants.  That way, doing tsubst_expr for the enumeration
5928            constants won't result in recursive calls here; we'll find
5929            the instantiation and exit above.  */
5930         tsubst_enum (template_type, t, arglist);
5931
5932       if (is_partial_instantiation)
5933         /* If the type makes use of template parameters, the
5934            code that generates debugging information will crash.  */
5935         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
5936
5937       /* Possibly limit visibility based on template args.  */
5938       TREE_PUBLIC (type_decl) = 1;
5939       determine_visibility (type_decl);
5940
5941       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
5942     }
5943   timevar_pop (TV_NAME_LOOKUP);
5944 }
5945 \f
5946 struct pair_fn_data
5947 {
5948   tree_fn_t fn;
5949   void *data;
5950   /* True when we should also visit template parameters that occur in
5951      non-deduced contexts.  */
5952   bool include_nondeduced_p;
5953   struct pointer_set_t *visited;
5954 };
5955
5956 /* Called from for_each_template_parm via walk_tree.  */
5957
5958 static tree
5959 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
5960 {
5961   tree t = *tp;
5962   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
5963   tree_fn_t fn = pfd->fn;
5964   void *data = pfd->data;
5965
5966   if (TYPE_P (t)
5967       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
5968       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
5969                                  pfd->include_nondeduced_p))
5970     return error_mark_node;
5971
5972   switch (TREE_CODE (t))
5973     {
5974     case RECORD_TYPE:
5975       if (TYPE_PTRMEMFUNC_P (t))
5976         break;
5977       /* Fall through.  */
5978
5979     case UNION_TYPE:
5980     case ENUMERAL_TYPE:
5981       if (!TYPE_TEMPLATE_INFO (t))
5982         *walk_subtrees = 0;
5983       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
5984                                        fn, data, pfd->visited, 
5985                                        pfd->include_nondeduced_p))
5986         return error_mark_node;
5987       break;
5988
5989     case INTEGER_TYPE:
5990       if (for_each_template_parm (TYPE_MIN_VALUE (t),
5991                                   fn, data, pfd->visited, 
5992                                   pfd->include_nondeduced_p)
5993           || for_each_template_parm (TYPE_MAX_VALUE (t),
5994                                      fn, data, pfd->visited,
5995                                      pfd->include_nondeduced_p))
5996         return error_mark_node;
5997       break;
5998
5999     case METHOD_TYPE:
6000       /* Since we're not going to walk subtrees, we have to do this
6001          explicitly here.  */
6002       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6003                                   pfd->visited, pfd->include_nondeduced_p))
6004         return error_mark_node;
6005       /* Fall through.  */
6006
6007     case FUNCTION_TYPE:
6008       /* Check the return type.  */
6009       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6010                                   pfd->include_nondeduced_p))
6011         return error_mark_node;
6012
6013       /* Check the parameter types.  Since default arguments are not
6014          instantiated until they are needed, the TYPE_ARG_TYPES may
6015          contain expressions that involve template parameters.  But,
6016          no-one should be looking at them yet.  And, once they're
6017          instantiated, they don't contain template parameters, so
6018          there's no point in looking at them then, either.  */
6019       {
6020         tree parm;
6021
6022         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6023           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6024                                       pfd->visited, pfd->include_nondeduced_p))
6025             return error_mark_node;
6026
6027         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6028            want walk_tree walking into them itself.  */
6029         *walk_subtrees = 0;
6030       }
6031       break;
6032
6033     case TYPEOF_TYPE:
6034       if (pfd->include_nondeduced_p
6035           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6036                                      pfd->visited, 
6037                                      pfd->include_nondeduced_p))
6038         return error_mark_node;
6039       break;
6040
6041     case FUNCTION_DECL:
6042     case VAR_DECL:
6043       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6044           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6045                                      pfd->visited, pfd->include_nondeduced_p))
6046         return error_mark_node;
6047       /* Fall through.  */
6048
6049     case PARM_DECL:
6050     case CONST_DECL:
6051       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6052           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6053                                      pfd->visited, pfd->include_nondeduced_p))
6054         return error_mark_node;
6055       if (DECL_CONTEXT (t)
6056           && pfd->include_nondeduced_p
6057           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6058                                      pfd->visited, pfd->include_nondeduced_p))
6059         return error_mark_node;
6060       break;
6061
6062     case BOUND_TEMPLATE_TEMPLATE_PARM:
6063       /* Record template parameters such as `T' inside `TT<T>'.  */
6064       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6065                                   pfd->include_nondeduced_p))
6066         return error_mark_node;
6067       /* Fall through.  */
6068
6069     case TEMPLATE_TEMPLATE_PARM:
6070     case TEMPLATE_TYPE_PARM:
6071     case TEMPLATE_PARM_INDEX:
6072       if (fn && (*fn)(t, data))
6073         return error_mark_node;
6074       else if (!fn)
6075         return error_mark_node;
6076       break;
6077
6078     case TEMPLATE_DECL:
6079       /* A template template parameter is encountered.  */
6080       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6081           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6082                                      pfd->include_nondeduced_p))
6083         return error_mark_node;
6084
6085       /* Already substituted template template parameter */
6086       *walk_subtrees = 0;
6087       break;
6088
6089     case TYPENAME_TYPE:
6090       if (!fn
6091           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6092                                      data, pfd->visited, 
6093                                      pfd->include_nondeduced_p))
6094         return error_mark_node;
6095       break;
6096
6097     case CONSTRUCTOR:
6098       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6099           && pfd->include_nondeduced_p
6100           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6101                                      (TREE_TYPE (t)), fn, data,
6102                                      pfd->visited, pfd->include_nondeduced_p))
6103         return error_mark_node;
6104       break;
6105
6106     case INDIRECT_REF:
6107     case COMPONENT_REF:
6108       /* If there's no type, then this thing must be some expression
6109          involving template parameters.  */
6110       if (!fn && !TREE_TYPE (t))
6111         return error_mark_node;
6112       break;
6113
6114     case MODOP_EXPR:
6115     case CAST_EXPR:
6116     case REINTERPRET_CAST_EXPR:
6117     case CONST_CAST_EXPR:
6118     case STATIC_CAST_EXPR:
6119     case DYNAMIC_CAST_EXPR:
6120     case ARROW_EXPR:
6121     case DOTSTAR_EXPR:
6122     case TYPEID_EXPR:
6123     case PSEUDO_DTOR_EXPR:
6124       if (!fn)
6125         return error_mark_node;
6126       break;
6127
6128     default:
6129       break;
6130     }
6131
6132   /* We didn't find any template parameters we liked.  */
6133   return NULL_TREE;
6134 }
6135
6136 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6137    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6138    call FN with the parameter and the DATA.
6139    If FN returns nonzero, the iteration is terminated, and
6140    for_each_template_parm returns 1.  Otherwise, the iteration
6141    continues.  If FN never returns a nonzero value, the value
6142    returned by for_each_template_parm is 0.  If FN is NULL, it is
6143    considered to be the function which always returns 1.
6144
6145    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6146    parameters that occur in non-deduced contexts.  When false, only
6147    visits those template parameters that can be deduced.  */
6148
6149 static int
6150 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6151                         struct pointer_set_t *visited,
6152                         bool include_nondeduced_p)
6153 {
6154   struct pair_fn_data pfd;
6155   int result;
6156
6157   /* Set up.  */
6158   pfd.fn = fn;
6159   pfd.data = data;
6160   pfd.include_nondeduced_p = include_nondeduced_p;
6161
6162   /* Walk the tree.  (Conceptually, we would like to walk without
6163      duplicates, but for_each_template_parm_r recursively calls
6164      for_each_template_parm, so we would need to reorganize a fair
6165      bit to use walk_tree_without_duplicates, so we keep our own
6166      visited list.)  */
6167   if (visited)
6168     pfd.visited = visited;
6169   else
6170     pfd.visited = pointer_set_create ();
6171   result = cp_walk_tree (&t,
6172                          for_each_template_parm_r,
6173                          &pfd,
6174                          pfd.visited) != NULL_TREE;
6175
6176   /* Clean up.  */
6177   if (!visited)
6178     {
6179       pointer_set_destroy (pfd.visited);
6180       pfd.visited = 0;
6181     }
6182
6183   return result;
6184 }
6185
6186 /* Returns true if T depends on any template parameter.  */
6187
6188 int
6189 uses_template_parms (tree t)
6190 {
6191   bool dependent_p;
6192   int saved_processing_template_decl;
6193
6194   saved_processing_template_decl = processing_template_decl;
6195   if (!saved_processing_template_decl)
6196     processing_template_decl = 1;
6197   if (TYPE_P (t))
6198     dependent_p = dependent_type_p (t);
6199   else if (TREE_CODE (t) == TREE_VEC)
6200     dependent_p = any_dependent_template_arguments_p (t);
6201   else if (TREE_CODE (t) == TREE_LIST)
6202     dependent_p = (uses_template_parms (TREE_VALUE (t))
6203                    || uses_template_parms (TREE_CHAIN (t)));
6204   else if (TREE_CODE (t) == TYPE_DECL)
6205     dependent_p = dependent_type_p (TREE_TYPE (t));
6206   else if (DECL_P (t)
6207            || EXPR_P (t)
6208            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6209            || TREE_CODE (t) == OVERLOAD
6210            || TREE_CODE (t) == BASELINK
6211            || TREE_CODE (t) == IDENTIFIER_NODE
6212            || TREE_CODE (t) == TRAIT_EXPR
6213            || CONSTANT_CLASS_P (t))
6214     dependent_p = (type_dependent_expression_p (t)
6215                    || value_dependent_expression_p (t));
6216   else
6217     {
6218       gcc_assert (t == error_mark_node);
6219       dependent_p = false;
6220     }
6221
6222   processing_template_decl = saved_processing_template_decl;
6223
6224   return dependent_p;
6225 }
6226
6227 /* Returns true if T depends on any template parameter with level LEVEL.  */
6228
6229 int
6230 uses_template_parms_level (tree t, int level)
6231 {
6232   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6233                                  /*include_nondeduced_p=*/true);
6234 }
6235
6236 static int tinst_depth;
6237 extern int max_tinst_depth;
6238 #ifdef GATHER_STATISTICS
6239 int depth_reached;
6240 #endif
6241 static int tinst_level_tick;
6242 static int last_template_error_tick;
6243
6244 /* We're starting to instantiate D; record the template instantiation context
6245    for diagnostics and to restore it later.  */
6246
6247 static int
6248 push_tinst_level (tree d)
6249 {
6250   struct tinst_level *new;
6251
6252   if (tinst_depth >= max_tinst_depth)
6253     {
6254       /* If the instantiation in question still has unbound template parms,
6255          we don't really care if we can't instantiate it, so just return.
6256          This happens with base instantiation for implicit `typename'.  */
6257       if (uses_template_parms (d))
6258         return 0;
6259
6260       last_template_error_tick = tinst_level_tick;
6261       error ("template instantiation depth exceeds maximum of %d (use "
6262              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6263              max_tinst_depth, d);
6264
6265       print_instantiation_context ();
6266
6267       return 0;
6268     }
6269
6270   new = GGC_NEW (struct tinst_level);
6271   new->decl = d;
6272   new->locus = input_location;
6273   new->in_system_header_p = in_system_header;
6274   new->next = current_tinst_level;
6275   current_tinst_level = new;
6276
6277   ++tinst_depth;
6278 #ifdef GATHER_STATISTICS
6279   if (tinst_depth > depth_reached)
6280     depth_reached = tinst_depth;
6281 #endif
6282
6283   ++tinst_level_tick;
6284   return 1;
6285 }
6286
6287 /* We're done instantiating this template; return to the instantiation
6288    context.  */
6289
6290 static void
6291 pop_tinst_level (void)
6292 {
6293   /* Restore the filename and line number stashed away when we started
6294      this instantiation.  */
6295   input_location = current_tinst_level->locus;
6296   in_system_header = current_tinst_level->in_system_header_p;
6297   current_tinst_level = current_tinst_level->next;
6298   --tinst_depth;
6299   ++tinst_level_tick;
6300 }
6301
6302 /* We're instantiating a deferred template; restore the template
6303    instantiation context in which the instantiation was requested, which
6304    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6305
6306 static tree
6307 reopen_tinst_level (struct tinst_level *level)
6308 {
6309   struct tinst_level *t;
6310
6311   tinst_depth = 0;
6312   for (t = level; t; t = t->next)
6313     ++tinst_depth;
6314
6315   current_tinst_level = level;
6316   pop_tinst_level ();
6317   return level->decl;
6318 }
6319
6320 /* Returns the TINST_LEVEL which gives the original instantiation
6321    context.  */
6322
6323 struct tinst_level *
6324 outermost_tinst_level (void)
6325 {
6326   struct tinst_level *level = current_tinst_level;
6327   if (level)
6328     while (level->next)
6329       level = level->next;
6330   return level;
6331 }
6332
6333 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6334    vector of template arguments, as for tsubst.
6335
6336    Returns an appropriate tsubst'd friend declaration.  */
6337
6338 static tree
6339 tsubst_friend_function (tree decl, tree args)
6340 {
6341   tree new_friend;
6342
6343   if (TREE_CODE (decl) == FUNCTION_DECL
6344       && DECL_TEMPLATE_INSTANTIATION (decl)
6345       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6346     /* This was a friend declared with an explicit template
6347        argument list, e.g.:
6348
6349        friend void f<>(T);
6350
6351        to indicate that f was a template instantiation, not a new
6352        function declaration.  Now, we have to figure out what
6353        instantiation of what template.  */
6354     {
6355       tree template_id, arglist, fns;
6356       tree new_args;
6357       tree tmpl;
6358       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6359
6360       /* Friend functions are looked up in the containing namespace scope.
6361          We must enter that scope, to avoid finding member functions of the
6362          current cless with same name.  */
6363       push_nested_namespace (ns);
6364       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6365                          tf_warning_or_error, NULL_TREE,
6366                          /*integral_constant_expression_p=*/false);
6367       pop_nested_namespace (ns);
6368       arglist = tsubst (DECL_TI_ARGS (decl), args,
6369                         tf_warning_or_error, NULL_TREE);
6370       template_id = lookup_template_function (fns, arglist);
6371
6372       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6373       tmpl = determine_specialization (template_id, new_friend,
6374                                        &new_args,
6375                                        /*need_member_template=*/0,
6376                                        TREE_VEC_LENGTH (args),
6377                                        tsk_none);
6378       return instantiate_template (tmpl, new_args, tf_error);
6379     }
6380
6381   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6382
6383   /* The NEW_FRIEND will look like an instantiation, to the
6384      compiler, but is not an instantiation from the point of view of
6385      the language.  For example, we might have had:
6386
6387      template <class T> struct S {
6388        template <class U> friend void f(T, U);
6389      };
6390
6391      Then, in S<int>, template <class U> void f(int, U) is not an
6392      instantiation of anything.  */
6393   if (new_friend == error_mark_node)
6394     return error_mark_node;
6395
6396   DECL_USE_TEMPLATE (new_friend) = 0;
6397   if (TREE_CODE (decl) == TEMPLATE_DECL)
6398     {
6399       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6400       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6401         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6402     }
6403
6404   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6405      is not a template instantiation and should not be mangled like
6406      one.  Therefore, we forget the mangling here; we'll recompute it
6407      later if we need it.  */
6408   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6409     {
6410       SET_DECL_RTL (new_friend, NULL_RTX);
6411       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6412     }
6413
6414   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6415     {
6416       tree old_decl;
6417       tree new_friend_template_info;
6418       tree new_friend_result_template_info;
6419       tree ns;
6420       int  new_friend_is_defn;
6421
6422       /* We must save some information from NEW_FRIEND before calling
6423          duplicate decls since that function will free NEW_FRIEND if
6424          possible.  */
6425       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6426       new_friend_is_defn =
6427             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6428                            (template_for_substitution (new_friend)))
6429              != NULL_TREE);
6430       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6431         {
6432           /* This declaration is a `primary' template.  */
6433           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6434
6435           new_friend_result_template_info
6436             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6437         }
6438       else
6439         new_friend_result_template_info = NULL_TREE;
6440
6441       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6442       if (new_friend_is_defn)
6443         DECL_INITIAL (new_friend) = error_mark_node;
6444
6445       /* Inside pushdecl_namespace_level, we will push into the
6446          current namespace. However, the friend function should go
6447          into the namespace of the template.  */
6448       ns = decl_namespace_context (new_friend);
6449       push_nested_namespace (ns);
6450       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6451       pop_nested_namespace (ns);
6452
6453       if (old_decl == error_mark_node)
6454         return error_mark_node;
6455
6456       if (old_decl != new_friend)
6457         {
6458           /* This new friend declaration matched an existing
6459              declaration.  For example, given:
6460
6461                template <class T> void f(T);
6462                template <class U> class C {
6463                  template <class T> friend void f(T) {}
6464                };
6465
6466              the friend declaration actually provides the definition
6467              of `f', once C has been instantiated for some type.  So,
6468              old_decl will be the out-of-class template declaration,
6469              while new_friend is the in-class definition.
6470
6471              But, if `f' was called before this point, the
6472              instantiation of `f' will have DECL_TI_ARGS corresponding
6473              to `T' but not to `U', references to which might appear
6474              in the definition of `f'.  Previously, the most general
6475              template for an instantiation of `f' was the out-of-class
6476              version; now it is the in-class version.  Therefore, we
6477              run through all specialization of `f', adding to their
6478              DECL_TI_ARGS appropriately.  In particular, they need a
6479              new set of outer arguments, corresponding to the
6480              arguments for this class instantiation.
6481
6482              The same situation can arise with something like this:
6483
6484                friend void f(int);
6485                template <class T> class C {
6486                  friend void f(T) {}
6487                };
6488
6489              when `C<int>' is instantiated.  Now, `f(int)' is defined
6490              in the class.  */
6491
6492           if (!new_friend_is_defn)
6493             /* On the other hand, if the in-class declaration does
6494                *not* provide a definition, then we don't want to alter
6495                existing definitions.  We can just leave everything
6496                alone.  */
6497             ;
6498           else
6499             {
6500               /* Overwrite whatever template info was there before, if
6501                  any, with the new template information pertaining to
6502                  the declaration.  */
6503               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6504
6505               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6506                 reregister_specialization (new_friend,
6507                                            most_general_template (old_decl),
6508                                            old_decl);
6509               else
6510                 {
6511                   tree t;
6512                   tree new_friend_args;
6513
6514                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6515                     = new_friend_result_template_info;
6516
6517                   new_friend_args = TI_ARGS (new_friend_template_info);
6518                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6519                        t != NULL_TREE;
6520                        t = TREE_CHAIN (t))
6521                     {
6522                       tree spec = TREE_VALUE (t);
6523
6524                       DECL_TI_ARGS (spec)
6525                         = add_outermost_template_args (new_friend_args,
6526                                                        DECL_TI_ARGS (spec));
6527                     }
6528
6529                   /* Now, since specializations are always supposed to
6530                      hang off of the most general template, we must move
6531                      them.  */
6532                   t = most_general_template (old_decl);
6533                   if (t != old_decl)
6534                     {
6535                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6536                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6537                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6538                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6539                     }
6540                 }
6541             }
6542
6543           /* The information from NEW_FRIEND has been merged into OLD_DECL
6544              by duplicate_decls.  */
6545           new_friend = old_decl;
6546         }
6547     }
6548   else
6549     {
6550       tree context = DECL_CONTEXT (new_friend);
6551       bool dependent_p;
6552
6553       /* In the code
6554            template <class T> class C {
6555              template <class U> friend void C1<U>::f (); // case 1
6556              friend void C2<T>::f ();                    // case 2
6557            };
6558          we only need to make sure CONTEXT is a complete type for
6559          case 2.  To distinguish between the two cases, we note that
6560          CONTEXT of case 1 remains dependent type after tsubst while
6561          this isn't true for case 2.  */
6562       ++processing_template_decl;
6563       dependent_p = dependent_type_p (context);
6564       --processing_template_decl;
6565
6566       if (!dependent_p
6567           && !complete_type_or_else (context, NULL_TREE))
6568         return error_mark_node;
6569
6570       if (COMPLETE_TYPE_P (context))
6571         {
6572           /* Check to see that the declaration is really present, and,
6573              possibly obtain an improved declaration.  */
6574           tree fn = check_classfn (context,
6575                                    new_friend, NULL_TREE);
6576
6577           if (fn)
6578             new_friend = fn;
6579         }
6580     }
6581
6582   return new_friend;
6583 }
6584
6585 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6586    template arguments, as for tsubst.
6587
6588    Returns an appropriate tsubst'd friend type or error_mark_node on
6589    failure.  */
6590
6591 static tree
6592 tsubst_friend_class (tree friend_tmpl, tree args)
6593 {
6594   tree friend_type;
6595   tree tmpl;
6596   tree context;
6597
6598   context = DECL_CONTEXT (friend_tmpl);
6599
6600   if (context)
6601     {
6602       if (TREE_CODE (context) == NAMESPACE_DECL)
6603         push_nested_namespace (context);
6604       else
6605         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6606     }
6607
6608   /* Look for a class template declaration.  We look for hidden names
6609      because two friend declarations of the same template are the
6610      same.  For example, in:
6611
6612        struct A { 
6613          template <typename> friend class F;
6614        };
6615        template <typename> struct B { 
6616          template <typename> friend class F;
6617        };
6618
6619      both F templates are the same.  */
6620   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6621                            /*block_p=*/true, 0, 
6622                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6623
6624   /* But, if we don't find one, it might be because we're in a
6625      situation like this:
6626
6627        template <class T>
6628        struct S {
6629          template <class U>
6630          friend struct S;
6631        };
6632
6633      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6634      for `S<int>', not the TEMPLATE_DECL.  */
6635   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6636     {
6637       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6638       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6639     }
6640
6641   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6642     {
6643       /* The friend template has already been declared.  Just
6644          check to see that the declarations match, and install any new
6645          default parameters.  We must tsubst the default parameters,
6646          of course.  We only need the innermost template parameters
6647          because that is all that redeclare_class_template will look
6648          at.  */
6649       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6650           > TMPL_ARGS_DEPTH (args))
6651         {
6652           tree parms;
6653           location_t saved_input_location;
6654           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6655                                          args, tf_warning_or_error);
6656
6657           saved_input_location = input_location;
6658           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6659           redeclare_class_template (TREE_TYPE (tmpl), parms);
6660           input_location = saved_input_location;
6661           
6662         }
6663
6664       friend_type = TREE_TYPE (tmpl);
6665     }
6666   else
6667     {
6668       /* The friend template has not already been declared.  In this
6669          case, the instantiation of the template class will cause the
6670          injection of this template into the global scope.  */
6671       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6672       if (tmpl == error_mark_node)
6673         return error_mark_node;
6674
6675       /* The new TMPL is not an instantiation of anything, so we
6676          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6677          the new type because that is supposed to be the corresponding
6678          template decl, i.e., TMPL.  */
6679       DECL_USE_TEMPLATE (tmpl) = 0;
6680       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6681       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6682       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6683         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6684
6685       /* Inject this template into the global scope.  */
6686       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6687     }
6688
6689   if (context)
6690     {
6691       if (TREE_CODE (context) == NAMESPACE_DECL)
6692         pop_nested_namespace (context);
6693       else
6694         pop_nested_class ();
6695     }
6696
6697   return friend_type;
6698 }
6699
6700 /* Returns zero if TYPE cannot be completed later due to circularity.
6701    Otherwise returns one.  */
6702
6703 static int
6704 can_complete_type_without_circularity (tree type)
6705 {
6706   if (type == NULL_TREE || type == error_mark_node)
6707     return 0;
6708   else if (COMPLETE_TYPE_P (type))
6709     return 1;
6710   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6711     return can_complete_type_without_circularity (TREE_TYPE (type));
6712   else if (CLASS_TYPE_P (type)
6713            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6714     return 0;
6715   else
6716     return 1;
6717 }
6718
6719 /* Apply any attributes which had to be deferred until instantiation
6720    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6721    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6722
6723 static void
6724 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6725                                 tree args, tsubst_flags_t complain, tree in_decl)
6726 {
6727   tree last_dep = NULL_TREE;
6728   tree t;
6729   tree *p;
6730
6731   for (t = attributes; t; t = TREE_CHAIN (t))
6732     if (ATTR_IS_DEPENDENT (t))
6733       {
6734         last_dep = t;
6735         attributes = copy_list (attributes);
6736         break;
6737       }
6738
6739   if (DECL_P (*decl_p))
6740     {
6741       if (TREE_TYPE (*decl_p) == error_mark_node)
6742         return;
6743       p = &DECL_ATTRIBUTES (*decl_p);
6744     }
6745   else
6746     p = &TYPE_ATTRIBUTES (*decl_p);
6747
6748   if (last_dep)
6749     {
6750       tree late_attrs = NULL_TREE;
6751       tree *q = &late_attrs;
6752
6753       for (*p = attributes; *p; )
6754         {
6755           t = *p;
6756           if (ATTR_IS_DEPENDENT (t))
6757             {
6758               *p = TREE_CHAIN (t);
6759               TREE_CHAIN (t) = NULL_TREE;
6760               TREE_VALUE (t)
6761                 = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6762                                /*integral_constant_expression_p=*/false);
6763               *q = t;
6764               q = &TREE_CHAIN (t);
6765             }
6766           else
6767             p = &TREE_CHAIN (t);
6768         }
6769
6770       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
6771     }
6772 }
6773
6774 tree
6775 instantiate_class_template (tree type)
6776 {
6777   tree template, args, pattern, t, member;
6778   tree typedecl;
6779   tree pbinfo;
6780   tree base_list;
6781
6782   if (type == error_mark_node)
6783     return error_mark_node;
6784
6785   if (TYPE_BEING_DEFINED (type)
6786       || COMPLETE_TYPE_P (type)
6787       || dependent_type_p (type))
6788     return type;
6789
6790   /* Figure out which template is being instantiated.  */
6791   template = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6792   gcc_assert (TREE_CODE (template) == TEMPLATE_DECL);
6793
6794   /* Determine what specialization of the original template to
6795      instantiate.  */
6796   t = most_specialized_class (type, template);
6797   if (t == error_mark_node)
6798     {
6799       TYPE_BEING_DEFINED (type) = 1;
6800       return error_mark_node;
6801     }
6802   else if (t)
6803     {
6804       /* This TYPE is actually an instantiation of a partial
6805          specialization.  We replace the innermost set of ARGS with
6806          the arguments appropriate for substitution.  For example,
6807          given:
6808
6809            template <class T> struct S {};
6810            template <class T> struct S<T*> {};
6811
6812          and supposing that we are instantiating S<int*>, ARGS will
6813          presently be {int*} -- but we need {int}.  */
6814       pattern = TREE_TYPE (t);
6815       args = TREE_PURPOSE (t);
6816     }
6817   else
6818     {
6819       pattern = TREE_TYPE (template);
6820       args = CLASSTYPE_TI_ARGS (type);
6821     }
6822
6823   /* If the template we're instantiating is incomplete, then clearly
6824      there's nothing we can do.  */
6825   if (!COMPLETE_TYPE_P (pattern))
6826     return type;
6827
6828   /* If we've recursively instantiated too many templates, stop.  */
6829   if (! push_tinst_level (type))
6830     return type;
6831
6832   /* Now we're really doing the instantiation.  Mark the type as in
6833      the process of being defined.  */
6834   TYPE_BEING_DEFINED (type) = 1;
6835
6836   /* We may be in the middle of deferred access check.  Disable
6837      it now.  */
6838   push_deferring_access_checks (dk_no_deferred);
6839
6840   push_to_top_level ();
6841
6842   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
6843
6844   /* Set the input location to the template definition. This is needed
6845      if tsubsting causes an error.  */
6846   typedecl = TYPE_MAIN_DECL (type);
6847   input_location = DECL_SOURCE_LOCATION (typedecl);
6848   in_system_header = DECL_IN_SYSTEM_HEADER (typedecl);
6849
6850   TYPE_HAS_CONSTRUCTOR (type) = TYPE_HAS_CONSTRUCTOR (pattern);
6851   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
6852   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
6853   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
6854   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
6855   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
6856   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
6857   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
6858   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
6859   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
6860   TYPE_PACKED (type) = TYPE_PACKED (pattern);
6861   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
6862   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
6863   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
6864   if (ANON_AGGR_TYPE_P (pattern))
6865     SET_ANON_AGGR_TYPE_P (type);
6866   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
6867     {
6868       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
6869       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
6870     }
6871
6872   pbinfo = TYPE_BINFO (pattern);
6873
6874   /* We should never instantiate a nested class before its enclosing
6875      class; we need to look up the nested class by name before we can
6876      instantiate it, and that lookup should instantiate the enclosing
6877      class.  */
6878   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
6879               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
6880               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
6881
6882   base_list = NULL_TREE;
6883   if (BINFO_N_BASE_BINFOS (pbinfo))
6884     {
6885       tree pbase_binfo;
6886       tree context = TYPE_CONTEXT (type);
6887       tree pushed_scope;
6888       int i;
6889
6890       /* We must enter the scope containing the type, as that is where
6891          the accessibility of types named in dependent bases are
6892          looked up from.  */
6893       pushed_scope = push_scope (context ? context : global_namespace);
6894
6895       /* Substitute into each of the bases to determine the actual
6896          basetypes.  */
6897       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
6898         {
6899           tree base;
6900           tree access = BINFO_BASE_ACCESS (pbinfo, i);
6901           tree expanded_bases = NULL_TREE;
6902           int idx, len = 1;
6903
6904           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
6905             {
6906               expanded_bases = 
6907                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
6908                                        args, tf_error, NULL_TREE);
6909               if (expanded_bases == error_mark_node)
6910                 continue;
6911
6912               len = TREE_VEC_LENGTH (expanded_bases);
6913             }
6914
6915           for (idx = 0; idx < len; idx++)
6916             {
6917               if (expanded_bases)
6918                 /* Extract the already-expanded base class.  */
6919                 base = TREE_VEC_ELT (expanded_bases, idx);
6920               else
6921                 /* Substitute to figure out the base class.  */
6922                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
6923                                NULL_TREE);
6924
6925               if (base == error_mark_node)
6926                 continue;
6927
6928               base_list = tree_cons (access, base, base_list);
6929               if (BINFO_VIRTUAL_P (pbase_binfo))
6930                 TREE_TYPE (base_list) = integer_type_node;
6931             }
6932         }
6933
6934       /* The list is now in reverse order; correct that.  */
6935       base_list = nreverse (base_list);
6936
6937       if (pushed_scope)
6938         pop_scope (pushed_scope);
6939     }
6940   /* Now call xref_basetypes to set up all the base-class
6941      information.  */
6942   xref_basetypes (type, base_list);
6943
6944   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
6945                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
6946                                   args, tf_error, NULL_TREE);
6947
6948   /* Now that our base classes are set up, enter the scope of the
6949      class, so that name lookups into base classes, etc. will work
6950      correctly.  This is precisely analogous to what we do in
6951      begin_class_definition when defining an ordinary non-template
6952      class, except we also need to push the enclosing classes.  */
6953   push_nested_class (type);
6954
6955   /* Now members are processed in the order of declaration.  */
6956   for (member = CLASSTYPE_DECL_LIST (pattern);
6957        member; member = TREE_CHAIN (member))
6958     {
6959       tree t = TREE_VALUE (member);
6960
6961       if (TREE_PURPOSE (member))
6962         {
6963           if (TYPE_P (t))
6964             {
6965               /* Build new CLASSTYPE_NESTED_UTDS.  */
6966
6967               tree newtag;
6968               bool class_template_p;
6969
6970               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
6971                                   && TYPE_LANG_SPECIFIC (t)
6972                                   && CLASSTYPE_IS_TEMPLATE (t));
6973               /* If the member is a class template, then -- even after
6974                  substitution -- there may be dependent types in the
6975                  template argument list for the class.  We increment
6976                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
6977                  that function will assume that no types are dependent
6978                  when outside of a template.  */
6979               if (class_template_p)
6980                 ++processing_template_decl;
6981               newtag = tsubst (t, args, tf_error, NULL_TREE);
6982               if (class_template_p)
6983                 --processing_template_decl;
6984               if (newtag == error_mark_node)
6985                 continue;
6986
6987               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
6988                 {
6989                   tree name = TYPE_IDENTIFIER (t);
6990
6991                   if (class_template_p)
6992                     /* Unfortunately, lookup_template_class sets
6993                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
6994                        instantiation (i.e., for the type of a member
6995                        template class nested within a template class.)
6996                        This behavior is required for
6997                        maybe_process_partial_specialization to work
6998                        correctly, but is not accurate in this case;
6999                        the TAG is not an instantiation of anything.
7000                        (The corresponding TEMPLATE_DECL is an
7001                        instantiation, but the TYPE is not.) */
7002                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7003
7004                   /* Now, we call pushtag to put this NEWTAG into the scope of
7005                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7006                      pushtag calling push_template_decl.  We don't have to do
7007                      this for enums because it will already have been done in
7008                      tsubst_enum.  */
7009                   if (name)
7010                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7011                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7012                 }
7013             }
7014           else if (TREE_CODE (t) == FUNCTION_DECL
7015                    || DECL_FUNCTION_TEMPLATE_P (t))
7016             {
7017               /* Build new TYPE_METHODS.  */
7018               tree r;
7019
7020               if (TREE_CODE (t) == TEMPLATE_DECL)
7021                 ++processing_template_decl;
7022               r = tsubst (t, args, tf_error, NULL_TREE);
7023               if (TREE_CODE (t) == TEMPLATE_DECL)
7024                 --processing_template_decl;
7025               set_current_access_from_decl (r);
7026               finish_member_declaration (r);
7027             }
7028           else
7029             {
7030               /* Build new TYPE_FIELDS.  */
7031               if (TREE_CODE (t) == STATIC_ASSERT)
7032                 {
7033                   tree condition = 
7034                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7035                                  tf_warning_or_error, NULL_TREE,
7036                                  /*integral_constant_expression_p=*/true);
7037                   finish_static_assert (condition,
7038                                         STATIC_ASSERT_MESSAGE (t), 
7039                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7040                                         /*member_p=*/true);
7041                 }
7042               else if (TREE_CODE (t) != CONST_DECL)
7043                 {
7044                   tree r;
7045
7046                   /* The the file and line for this declaration, to
7047                      assist in error message reporting.  Since we
7048                      called push_tinst_level above, we don't need to
7049                      restore these.  */
7050                   input_location = DECL_SOURCE_LOCATION (t);
7051
7052                   if (TREE_CODE (t) == TEMPLATE_DECL)
7053                     ++processing_template_decl;
7054                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7055                   if (TREE_CODE (t) == TEMPLATE_DECL)
7056                     --processing_template_decl;
7057                   if (TREE_CODE (r) == VAR_DECL)
7058                     {
7059                       /* In [temp.inst]:
7060
7061                            [t]he initialization (and any associated
7062                            side-effects) of a static data member does
7063                            not occur unless the static data member is
7064                            itself used in a way that requires the
7065                            definition of the static data member to
7066                            exist.
7067
7068                          Therefore, we do not substitute into the
7069                          initialized for the static data member here.  */
7070                       finish_static_data_member_decl
7071                         (r,
7072                          /*init=*/NULL_TREE,
7073                          /*init_const_expr_p=*/false,
7074                          /*asmspec_tree=*/NULL_TREE,
7075                          /*flags=*/0);
7076                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7077                         check_static_variable_definition (r, TREE_TYPE (r));
7078                     }
7079                   else if (TREE_CODE (r) == FIELD_DECL)
7080                     {
7081                       /* Determine whether R has a valid type and can be
7082                          completed later.  If R is invalid, then it is
7083                          replaced by error_mark_node so that it will not be
7084                          added to TYPE_FIELDS.  */
7085                       tree rtype = TREE_TYPE (r);
7086                       if (can_complete_type_without_circularity (rtype))
7087                         complete_type (rtype);
7088
7089                       if (!COMPLETE_TYPE_P (rtype))
7090                         {
7091                           cxx_incomplete_type_error (r, rtype);
7092                           r = error_mark_node;
7093                         }
7094                     }
7095
7096                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7097                      such a thing will already have been added to the field
7098                      list by tsubst_enum in finish_member_declaration in the
7099                      CLASSTYPE_NESTED_UTDS case above.  */
7100                   if (!(TREE_CODE (r) == TYPE_DECL
7101                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7102                         && DECL_ARTIFICIAL (r)))
7103                     {
7104                       set_current_access_from_decl (r);
7105                       finish_member_declaration (r);
7106                     }
7107                 }
7108             }
7109         }
7110       else
7111         {
7112           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7113             {
7114               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7115
7116               tree friend_type = t;
7117               bool adjust_processing_template_decl = false;
7118
7119               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7120                 {
7121                   /* template <class T> friend class C;  */
7122                   friend_type = tsubst_friend_class (friend_type, args);
7123                   adjust_processing_template_decl = true;
7124                 }
7125               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7126                 {
7127                   /* template <class T> friend class C::D;  */
7128                   friend_type = tsubst (friend_type, args,
7129                                         tf_warning_or_error, NULL_TREE);
7130                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7131                     friend_type = TREE_TYPE (friend_type);
7132                   adjust_processing_template_decl = true;
7133                 }
7134               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7135                 {
7136                   /* This could be either
7137
7138                        friend class T::C;
7139
7140                      when dependent_type_p is false or
7141
7142                        template <class U> friend class T::C;
7143
7144                      otherwise.  */
7145                   friend_type = tsubst (friend_type, args,
7146                                         tf_warning_or_error, NULL_TREE);
7147                   /* Bump processing_template_decl for correct
7148                      dependent_type_p calculation.  */
7149                   ++processing_template_decl;
7150                   if (dependent_type_p (friend_type))
7151                     adjust_processing_template_decl = true;
7152                   --processing_template_decl;
7153                 }
7154               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7155                        && hidden_name_p (TYPE_NAME (friend_type)))
7156                 {
7157                   /* friend class C;
7158
7159                      where C hasn't been declared yet.  Let's lookup name
7160                      from namespace scope directly, bypassing any name that
7161                      come from dependent base class.  */
7162                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7163
7164                   /* The call to xref_tag_from_type does injection for friend
7165                      classes.  */
7166                   push_nested_namespace (ns);
7167                   friend_type =
7168                     xref_tag_from_type (friend_type, NULL_TREE,
7169                                         /*tag_scope=*/ts_current);
7170                   pop_nested_namespace (ns);
7171                 }
7172               else if (uses_template_parms (friend_type))
7173                 /* friend class C<T>;  */
7174                 friend_type = tsubst (friend_type, args,
7175                                       tf_warning_or_error, NULL_TREE);
7176               /* Otherwise it's
7177
7178                    friend class C;
7179
7180                  where C is already declared or
7181
7182                    friend class C<int>;
7183
7184                  We don't have to do anything in these cases.  */
7185
7186               if (adjust_processing_template_decl)
7187                 /* Trick make_friend_class into realizing that the friend
7188                    we're adding is a template, not an ordinary class.  It's
7189                    important that we use make_friend_class since it will
7190                    perform some error-checking and output cross-reference
7191                    information.  */
7192                 ++processing_template_decl;
7193
7194               if (friend_type != error_mark_node)
7195                 make_friend_class (type, friend_type, /*complain=*/false);
7196
7197               if (adjust_processing_template_decl)
7198                 --processing_template_decl;
7199             }
7200           else
7201             {
7202               /* Build new DECL_FRIENDLIST.  */
7203               tree r;
7204
7205               /* The the file and line for this declaration, to
7206                  assist in error message reporting.  Since we
7207                  called push_tinst_level above, we don't need to
7208                  restore these.  */
7209               input_location = DECL_SOURCE_LOCATION (t);
7210
7211               if (TREE_CODE (t) == TEMPLATE_DECL)
7212                 {
7213                   ++processing_template_decl;
7214                   push_deferring_access_checks (dk_no_check);
7215                 }
7216
7217               r = tsubst_friend_function (t, args);
7218               add_friend (type, r, /*complain=*/false);
7219               if (TREE_CODE (t) == TEMPLATE_DECL)
7220                 {
7221                   pop_deferring_access_checks ();
7222                   --processing_template_decl;
7223                 }
7224             }
7225         }
7226     }
7227
7228   /* Set the file and line number information to whatever is given for
7229      the class itself.  This puts error messages involving generated
7230      implicit functions at a predictable point, and the same point
7231      that would be used for non-template classes.  */
7232   input_location = DECL_SOURCE_LOCATION (typedecl);
7233
7234   unreverse_member_declarations (type);
7235   finish_struct_1 (type);
7236   TYPE_BEING_DEFINED (type) = 0;
7237
7238   /* Now that the class is complete, instantiate default arguments for
7239      any member functions.  We don't do this earlier because the
7240      default arguments may reference members of the class.  */
7241   if (!PRIMARY_TEMPLATE_P (template))
7242     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7243       if (TREE_CODE (t) == FUNCTION_DECL
7244           /* Implicitly generated member functions will not have template
7245              information; they are not instantiations, but instead are
7246              created "fresh" for each instantiation.  */
7247           && DECL_TEMPLATE_INFO (t))
7248         tsubst_default_arguments (t);
7249
7250   pop_nested_class ();
7251   pop_from_top_level ();
7252   pop_deferring_access_checks ();
7253   pop_tinst_level ();
7254
7255   /* The vtable for a template class can be emitted in any translation
7256      unit in which the class is instantiated.  When there is no key
7257      method, however, finish_struct_1 will already have added TYPE to
7258      the keyed_classes list.  */
7259   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7260     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7261
7262   return type;
7263 }
7264
7265 static tree
7266 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7267 {
7268   tree r;
7269
7270   if (!t)
7271     r = t;
7272   else if (TYPE_P (t))
7273     r = tsubst (t, args, complain, in_decl);
7274   else
7275     {
7276       r = tsubst_expr (t, args, complain, in_decl,
7277                        /*integral_constant_expression_p=*/true);
7278       r = fold_non_dependent_expr (r);
7279     }
7280   return r;
7281 }
7282
7283 /* Substitute ARGS into T, which is an pack expansion
7284    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7285    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7286    (if only a partial substitution could be performed) or
7287    ERROR_MARK_NODE if there was an error.  */
7288 tree
7289 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7290                        tree in_decl)
7291 {
7292   tree pattern;
7293   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7294   tree first_arg_pack; int i, len = -1;
7295   tree result;
7296   int incomplete = 0;
7297
7298   gcc_assert (PACK_EXPANSION_P (t));
7299   pattern = PACK_EXPANSION_PATTERN (t);
7300
7301   /* Determine the argument packs that will instantiate the parameter
7302      packs used in the expansion expression. While we're at it,
7303      compute the number of arguments to be expanded and make sure it
7304      is consistent.  */
7305   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7306        pack = TREE_CHAIN (pack))
7307     {
7308       tree parm_pack = TREE_VALUE (pack);
7309       tree arg_pack = NULL_TREE;
7310       tree orig_arg = NULL_TREE;
7311
7312       if (TREE_CODE (parm_pack) == PARM_DECL)
7313         arg_pack = retrieve_local_specialization (parm_pack);
7314       else
7315         {
7316           int level, idx, levels;
7317           template_parm_level_and_index (parm_pack, &level, &idx);
7318
7319           levels = TMPL_ARGS_DEPTH (args);
7320           if (level <= levels)
7321             arg_pack = TMPL_ARG (args, level, idx);
7322         }
7323
7324       orig_arg = arg_pack;
7325       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7326         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7327       
7328       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7329         /* This can only happen if we forget to expand an argument
7330            pack somewhere else. Just return an error, silently.  */
7331         {
7332           result = make_tree_vec (1);
7333           TREE_VEC_ELT (result, 0) = error_mark_node;
7334           return result;
7335         }
7336
7337       if (arg_pack
7338           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7339           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7340         {
7341           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7342           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7343           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7344               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7345             /* The argument pack that the parameter maps to is just an
7346                expansion of the parameter itself, such as one would
7347                find in the implicit typedef of a class inside the
7348                class itself.  Consider this parameter "unsubstituted",
7349                so that we will maintain the outer pack expansion.  */
7350             arg_pack = NULL_TREE;
7351         }
7352           
7353       if (arg_pack)
7354         {
7355           int my_len = 
7356             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7357
7358           /* It's all-or-nothing with incomplete argument packs.  */
7359           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7360             return error_mark_node;
7361           
7362           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7363             incomplete = 1;
7364
7365           if (len < 0)
7366             {
7367               len = my_len;
7368               first_arg_pack = arg_pack;
7369             }
7370           else if (len != my_len)
7371             {
7372               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7373                 error ("mismatched argument pack lengths while expanding "
7374                        "%<%T%>",
7375                        pattern);
7376               else
7377                 error ("mismatched argument pack lengths while expanding "
7378                        "%<%E%>",
7379                        pattern);
7380               return error_mark_node;
7381             }
7382
7383           /* Keep track of the parameter packs and their corresponding
7384              argument packs.  */
7385           packs = tree_cons (parm_pack, arg_pack, packs);
7386           TREE_TYPE (packs) = orig_arg;
7387         }
7388       else
7389         /* We can't substitute for this parameter pack.  */
7390         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7391                                          TREE_VALUE (pack),
7392                                          unsubstituted_packs);
7393     }
7394
7395   /* We cannot expand this expansion expression, because we don't have
7396      all of the argument packs we need. Substitute into the pattern
7397      and return a PACK_EXPANSION_*. The caller will need to deal with
7398      that.  */
7399   if (unsubstituted_packs)
7400     return make_pack_expansion (tsubst (pattern, args, complain, 
7401                                         in_decl));
7402
7403   /* We could not find any argument packs that work.  */
7404   if (len < 0)
7405     return error_mark_node;
7406
7407   /* For each argument in each argument pack, substitute into the
7408      pattern.  */
7409   result = make_tree_vec (len + incomplete);
7410   for (i = 0; i < len + incomplete; ++i)
7411     {
7412       /* For parameter pack, change the substitution of the parameter
7413          pack to the ith argument in its argument pack, then expand
7414          the pattern.  */
7415       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7416         {
7417           tree parm = TREE_PURPOSE (pack);
7418
7419           if (TREE_CODE (parm) == PARM_DECL)
7420             {
7421               /* Select the Ith argument from the pack.  */
7422               tree arg = make_node (ARGUMENT_PACK_SELECT);
7423               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7424               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7425               mark_used (parm);
7426               register_local_specialization (arg, parm);
7427             }
7428           else
7429             {
7430               tree value = parm;
7431               int idx, level;
7432               template_parm_level_and_index (parm, &level, &idx);
7433               
7434               if (i < len) 
7435                 {
7436                   /* Select the Ith argument from the pack. */
7437                   value = make_node (ARGUMENT_PACK_SELECT);
7438                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7439                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7440                 }
7441
7442               /* Update the corresponding argument.  */
7443               TMPL_ARG (args, level, idx) = value;
7444             }
7445         }
7446
7447       /* Substitute into the PATTERN with the altered arguments.  */
7448       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7449         TREE_VEC_ELT (result, i) = 
7450           tsubst_expr (pattern, args, complain, in_decl,
7451                        /*integral_constant_expression_p=*/false);
7452       else
7453         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7454
7455       if (i == len)
7456         /* When we have incomplete argument packs, the last "expanded"
7457            result is itself a pack expansion, which allows us
7458            to deduce more arguments.  */
7459         TREE_VEC_ELT (result, i) = 
7460           make_pack_expansion (TREE_VEC_ELT (result, i));
7461
7462       if (TREE_VEC_ELT (result, i) == error_mark_node)
7463         {
7464           result = error_mark_node;
7465           break;
7466         }
7467     }
7468   
7469   /* Update ARGS to restore the substitution from parameter packs to
7470      their argument packs.  */
7471   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7472     {
7473       tree parm = TREE_PURPOSE (pack);
7474
7475       if (TREE_CODE (parm) == PARM_DECL)
7476         register_local_specialization (TREE_TYPE (pack), parm);
7477       else
7478         {
7479           int idx, level;
7480           template_parm_level_and_index (parm, &level, &idx);
7481           
7482           /* Update the corresponding argument.  */
7483           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7484             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7485               TREE_TYPE (pack);
7486           else
7487             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7488         }
7489     }
7490
7491   return result;
7492 }
7493
7494 /* Substitute ARGS into the vector or list of template arguments T.  */
7495
7496 static tree
7497 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7498 {
7499   tree orig_t = t;
7500   int len = TREE_VEC_LENGTH (t);
7501   int need_new = 0, i, expanded_len_adjust = 0, out;
7502   tree *elts = (tree *) alloca (len * sizeof (tree));
7503
7504   for (i = 0; i < len; i++)
7505     {
7506       tree orig_arg = TREE_VEC_ELT (t, i);
7507       tree new_arg;
7508
7509       if (TREE_CODE (orig_arg) == TREE_VEC)
7510         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7511       else if (PACK_EXPANSION_P (orig_arg))
7512         {
7513           /* Substitute into an expansion expression.  */
7514           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7515
7516           if (TREE_CODE (new_arg) == TREE_VEC)
7517             /* Add to the expanded length adjustment the number of
7518                expanded arguments. We subtract one from this
7519                measurement, because the argument pack expression
7520                itself is already counted as 1 in
7521                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7522                the argument pack is empty.  */
7523             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7524         }
7525       else if (ARGUMENT_PACK_P (orig_arg))
7526         {
7527           /* Substitute into each of the arguments.  */
7528           new_arg = make_node (TREE_CODE (orig_arg));
7529           
7530           SET_ARGUMENT_PACK_ARGS (
7531             new_arg,
7532             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7533                                   args, complain, in_decl));
7534
7535           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7536             new_arg = error_mark_node;
7537
7538           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7539             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7540                                           complain, in_decl);
7541             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7542
7543             if (TREE_TYPE (new_arg) == error_mark_node)
7544               new_arg = error_mark_node;
7545           }
7546         }
7547       else
7548         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7549
7550       if (new_arg == error_mark_node)
7551         return error_mark_node;
7552
7553       elts[i] = new_arg;
7554       if (new_arg != orig_arg)
7555         need_new = 1;
7556     }
7557
7558   if (!need_new)
7559     return t;
7560
7561   /* Make space for the expanded arguments coming from template
7562      argument packs.  */
7563   t = make_tree_vec (len + expanded_len_adjust);
7564   for (i = 0, out = 0; i < len; i++)
7565     {
7566       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7567            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7568           && TREE_CODE (elts[i]) == TREE_VEC)
7569         {
7570           int idx;
7571
7572           /* Now expand the template argument pack "in place".  */
7573           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7574             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7575         }
7576       else
7577         {
7578           TREE_VEC_ELT (t, out) = elts[i];
7579           out++;
7580         }
7581     }
7582
7583   return t;
7584 }
7585
7586 /* Return the result of substituting ARGS into the template parameters
7587    given by PARMS.  If there are m levels of ARGS and m + n levels of
7588    PARMS, then the result will contain n levels of PARMS.  For
7589    example, if PARMS is `template <class T> template <class U>
7590    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7591    result will be `template <int*, double, class V>'.  */
7592
7593 static tree
7594 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7595 {
7596   tree r = NULL_TREE;
7597   tree* new_parms;
7598
7599   /* When substituting into a template, we must set
7600      PROCESSING_TEMPLATE_DECL as the template parameters may be
7601      dependent if they are based on one-another, and the dependency
7602      predicates are short-circuit outside of templates.  */
7603   ++processing_template_decl;
7604
7605   for (new_parms = &r;
7606        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7607        new_parms = &(TREE_CHAIN (*new_parms)),
7608          parms = TREE_CHAIN (parms))
7609     {
7610       tree new_vec =
7611         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7612       int i;
7613
7614       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7615         {
7616           tree tuple;
7617           tree default_value;
7618           tree parm_decl;
7619
7620           if (parms == error_mark_node)
7621             continue;
7622
7623           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7624
7625           if (tuple == error_mark_node)
7626             continue;
7627
7628           default_value = TREE_PURPOSE (tuple);
7629           parm_decl = TREE_VALUE (tuple);
7630
7631           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7632           if (TREE_CODE (parm_decl) == PARM_DECL
7633               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7634             parm_decl = error_mark_node;
7635           default_value = tsubst_template_arg (default_value, args,
7636                                                complain, NULL_TREE);
7637
7638           tuple = build_tree_list (default_value, parm_decl);
7639           TREE_VEC_ELT (new_vec, i) = tuple;
7640         }
7641
7642       *new_parms =
7643         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7644                              - TMPL_ARGS_DEPTH (args)),
7645                    new_vec, NULL_TREE);
7646     }
7647
7648   --processing_template_decl;
7649
7650   return r;
7651 }
7652
7653 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7654    type T.  If T is not an aggregate or enumeration type, it is
7655    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7656    ENTERING_SCOPE is nonzero, T is the context for a template which
7657    we are presently tsubst'ing.  Return the substituted value.  */
7658
7659 static tree
7660 tsubst_aggr_type (tree t,
7661                   tree args,
7662                   tsubst_flags_t complain,
7663                   tree in_decl,
7664                   int entering_scope)
7665 {
7666   if (t == NULL_TREE)
7667     return NULL_TREE;
7668
7669   switch (TREE_CODE (t))
7670     {
7671     case RECORD_TYPE:
7672       if (TYPE_PTRMEMFUNC_P (t))
7673         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7674
7675       /* Else fall through.  */
7676     case ENUMERAL_TYPE:
7677     case UNION_TYPE:
7678       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
7679         {
7680           tree argvec;
7681           tree context;
7682           tree r;
7683           bool saved_skip_evaluation;
7684
7685           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7686           saved_skip_evaluation = skip_evaluation;
7687           skip_evaluation = false;
7688
7689           /* First, determine the context for the type we are looking
7690              up.  */
7691           context = TYPE_CONTEXT (t);
7692           if (context)
7693             {
7694               context = tsubst_aggr_type (context, args, complain,
7695                                           in_decl, /*entering_scope=*/1);
7696               /* If context is a nested class inside a class template,
7697                  it may still need to be instantiated (c++/33959).  */
7698               if (TYPE_P (context))
7699                 context = complete_type (context);
7700             }
7701
7702           /* Then, figure out what arguments are appropriate for the
7703              type we are trying to find.  For example, given:
7704
7705                template <class T> struct S;
7706                template <class T, class U> void f(T, U) { S<U> su; }
7707
7708              and supposing that we are instantiating f<int, double>,
7709              then our ARGS will be {int, double}, but, when looking up
7710              S we only want {double}.  */
7711           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7712                                          complain, in_decl);
7713           if (argvec == error_mark_node)
7714             r = error_mark_node;
7715           else
7716             {
7717               r = lookup_template_class (t, argvec, in_decl, context,
7718                                          entering_scope, complain);
7719               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7720             }
7721
7722           skip_evaluation = saved_skip_evaluation;
7723
7724           return r;
7725         }
7726       else
7727         /* This is not a template type, so there's nothing to do.  */
7728         return t;
7729
7730     default:
7731       return tsubst (t, args, complain, in_decl);
7732     }
7733 }
7734
7735 /* Substitute into the default argument ARG (a default argument for
7736    FN), which has the indicated TYPE.  */
7737
7738 tree
7739 tsubst_default_argument (tree fn, tree type, tree arg)
7740 {
7741   tree saved_class_ptr = NULL_TREE;
7742   tree saved_class_ref = NULL_TREE;
7743
7744   /* This default argument came from a template.  Instantiate the
7745      default argument here, not in tsubst.  In the case of
7746      something like:
7747
7748        template <class T>
7749        struct S {
7750          static T t();
7751          void f(T = t());
7752        };
7753
7754      we must be careful to do name lookup in the scope of S<T>,
7755      rather than in the current class.  */
7756   push_access_scope (fn);
7757   /* The "this" pointer is not valid in a default argument.  */
7758   if (cfun)
7759     {
7760       saved_class_ptr = current_class_ptr;
7761       cp_function_chain->x_current_class_ptr = NULL_TREE;
7762       saved_class_ref = current_class_ref;
7763       cp_function_chain->x_current_class_ref = NULL_TREE;
7764     }
7765
7766   push_deferring_access_checks(dk_no_deferred);
7767   /* The default argument expression may cause implicitly defined
7768      member functions to be synthesized, which will result in garbage
7769      collection.  We must treat this situation as if we were within
7770      the body of function so as to avoid collecting live data on the
7771      stack.  */
7772   ++function_depth;
7773   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
7774                      tf_warning_or_error, NULL_TREE,
7775                      /*integral_constant_expression_p=*/false);
7776   --function_depth;
7777   pop_deferring_access_checks();
7778
7779   /* Restore the "this" pointer.  */
7780   if (cfun)
7781     {
7782       cp_function_chain->x_current_class_ptr = saved_class_ptr;
7783       cp_function_chain->x_current_class_ref = saved_class_ref;
7784     }
7785
7786   pop_access_scope (fn);
7787
7788   /* Make sure the default argument is reasonable.  */
7789   arg = check_default_argument (type, arg);
7790
7791   return arg;
7792 }
7793
7794 /* Substitute into all the default arguments for FN.  */
7795
7796 static void
7797 tsubst_default_arguments (tree fn)
7798 {
7799   tree arg;
7800   tree tmpl_args;
7801
7802   tmpl_args = DECL_TI_ARGS (fn);
7803
7804   /* If this function is not yet instantiated, we certainly don't need
7805      its default arguments.  */
7806   if (uses_template_parms (tmpl_args))
7807     return;
7808
7809   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
7810        arg;
7811        arg = TREE_CHAIN (arg))
7812     if (TREE_PURPOSE (arg))
7813       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
7814                                                     TREE_VALUE (arg),
7815                                                     TREE_PURPOSE (arg));
7816 }
7817
7818 /* Substitute the ARGS into the T, which is a _DECL.  Return the
7819    result of the substitution.  Issue error and warning messages under
7820    control of COMPLAIN.  */
7821
7822 static tree
7823 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
7824 {
7825   location_t saved_loc;
7826   tree r = NULL_TREE;
7827   tree in_decl = t;
7828
7829   /* Set the filename and linenumber to improve error-reporting.  */
7830   saved_loc = input_location;
7831   input_location = DECL_SOURCE_LOCATION (t);
7832
7833   switch (TREE_CODE (t))
7834     {
7835     case TEMPLATE_DECL:
7836       {
7837         /* We can get here when processing a member function template,
7838            member class template, and template template parameter of
7839            a template class.  */
7840         tree decl = DECL_TEMPLATE_RESULT (t);
7841         tree spec;
7842         tree tmpl_args;
7843         tree full_args;
7844
7845         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
7846           {
7847             /* Template template parameter is treated here.  */
7848             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7849             if (new_type == error_mark_node)
7850               return error_mark_node;
7851
7852             r = copy_decl (t);
7853             TREE_CHAIN (r) = NULL_TREE;
7854             TREE_TYPE (r) = new_type;
7855             DECL_TEMPLATE_RESULT (r)
7856               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
7857             DECL_TEMPLATE_PARMS (r)
7858               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
7859                                        complain);
7860             TYPE_NAME (new_type) = r;
7861             break;
7862           }
7863
7864         /* We might already have an instance of this template.
7865            The ARGS are for the surrounding class type, so the
7866            full args contain the tsubst'd args for the context,
7867            plus the innermost args from the template decl.  */
7868         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
7869           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
7870           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
7871         /* Because this is a template, the arguments will still be
7872            dependent, even after substitution.  If
7873            PROCESSING_TEMPLATE_DECL is not set, the dependency
7874            predicates will short-circuit.  */
7875         ++processing_template_decl;
7876         full_args = tsubst_template_args (tmpl_args, args,
7877                                           complain, in_decl);
7878         --processing_template_decl;
7879         if (full_args == error_mark_node)
7880           return error_mark_node;
7881
7882         /* tsubst_template_args doesn't copy the vector if
7883            nothing changed.  But, *something* should have
7884            changed.  */
7885         gcc_assert (full_args != tmpl_args);
7886
7887         spec = retrieve_specialization (t, full_args,
7888                                         /*class_specializations_p=*/true);
7889         if (spec != NULL_TREE)
7890           {
7891             r = spec;
7892             break;
7893           }
7894
7895         /* Make a new template decl.  It will be similar to the
7896            original, but will record the current template arguments.
7897            We also create a new function declaration, which is just
7898            like the old one, but points to this new template, rather
7899            than the old one.  */
7900         r = copy_decl (t);
7901         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
7902         TREE_CHAIN (r) = NULL_TREE;
7903
7904         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
7905
7906         if (TREE_CODE (decl) == TYPE_DECL)
7907           {
7908             tree new_type;
7909             ++processing_template_decl;
7910             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7911             --processing_template_decl;
7912             if (new_type == error_mark_node)
7913               return error_mark_node;
7914
7915             TREE_TYPE (r) = new_type;
7916             CLASSTYPE_TI_TEMPLATE (new_type) = r;
7917             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
7918             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
7919             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
7920           }
7921         else
7922           {
7923             tree new_decl;
7924             ++processing_template_decl;
7925             new_decl = tsubst (decl, args, complain, in_decl);
7926             --processing_template_decl;
7927             if (new_decl == error_mark_node)
7928               return error_mark_node;
7929
7930             DECL_TEMPLATE_RESULT (r) = new_decl;
7931             DECL_TI_TEMPLATE (new_decl) = r;
7932             TREE_TYPE (r) = TREE_TYPE (new_decl);
7933             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
7934             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
7935           }
7936
7937         SET_DECL_IMPLICIT_INSTANTIATION (r);
7938         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
7939         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
7940
7941         /* The template parameters for this new template are all the
7942            template parameters for the old template, except the
7943            outermost level of parameters.  */
7944         DECL_TEMPLATE_PARMS (r)
7945           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
7946                                    complain);
7947
7948         if (PRIMARY_TEMPLATE_P (t))
7949           DECL_PRIMARY_TEMPLATE (r) = r;
7950
7951         if (TREE_CODE (decl) != TYPE_DECL)
7952           /* Record this non-type partial instantiation.  */
7953           register_specialization (r, t,
7954                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
7955                                    false);
7956       }
7957       break;
7958
7959     case FUNCTION_DECL:
7960       {
7961         tree ctx;
7962         tree argvec = NULL_TREE;
7963         tree *friends;
7964         tree gen_tmpl;
7965         tree type;
7966         int member;
7967         int args_depth;
7968         int parms_depth;
7969
7970         /* Nobody should be tsubst'ing into non-template functions.  */
7971         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
7972
7973         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
7974           {
7975             tree spec;
7976             bool dependent_p;
7977
7978             /* If T is not dependent, just return it.  We have to
7979                increment PROCESSING_TEMPLATE_DECL because
7980                value_dependent_expression_p assumes that nothing is
7981                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
7982             ++processing_template_decl;
7983             dependent_p = value_dependent_expression_p (t);
7984             --processing_template_decl;
7985             if (!dependent_p)
7986               return t;
7987
7988             /* Calculate the most general template of which R is a
7989                specialization, and the complete set of arguments used to
7990                specialize R.  */
7991             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
7992             argvec = tsubst_template_args (DECL_TI_ARGS
7993                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
7994                                            args, complain, in_decl);
7995
7996             /* Check to see if we already have this specialization.  */
7997             spec = retrieve_specialization (gen_tmpl, argvec,
7998                                             /*class_specializations_p=*/false);
7999
8000             if (spec)
8001               {
8002                 r = spec;
8003                 break;
8004               }
8005
8006             /* We can see more levels of arguments than parameters if
8007                there was a specialization of a member template, like
8008                this:
8009
8010                  template <class T> struct S { template <class U> void f(); }
8011                  template <> template <class U> void S<int>::f(U);
8012
8013                Here, we'll be substituting into the specialization,
8014                because that's where we can find the code we actually
8015                want to generate, but we'll have enough arguments for
8016                the most general template.
8017
8018                We also deal with the peculiar case:
8019
8020                  template <class T> struct S {
8021                    template <class U> friend void f();
8022                  };
8023                  template <class U> void f() {}
8024                  template S<int>;
8025                  template void f<double>();
8026
8027                Here, the ARGS for the instantiation of will be {int,
8028                double}.  But, we only need as many ARGS as there are
8029                levels of template parameters in CODE_PATTERN.  We are
8030                careful not to get fooled into reducing the ARGS in
8031                situations like:
8032
8033                  template <class T> struct S { template <class U> void f(U); }
8034                  template <class T> template <> void S<T>::f(int) {}
8035
8036                which we can spot because the pattern will be a
8037                specialization in this case.  */
8038             args_depth = TMPL_ARGS_DEPTH (args);
8039             parms_depth =
8040               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8041             if (args_depth > parms_depth
8042                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8043               args = get_innermost_template_args (args, parms_depth);
8044           }
8045         else
8046           {
8047             /* This special case arises when we have something like this:
8048
8049                  template <class T> struct S {
8050                    friend void f<int>(int, double);
8051                  };
8052
8053                Here, the DECL_TI_TEMPLATE for the friend declaration
8054                will be an IDENTIFIER_NODE.  We are being called from
8055                tsubst_friend_function, and we want only to create a
8056                new decl (R) with appropriate types so that we can call
8057                determine_specialization.  */
8058             gen_tmpl = NULL_TREE;
8059           }
8060
8061         if (DECL_CLASS_SCOPE_P (t))
8062           {
8063             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8064               member = 2;
8065             else
8066               member = 1;
8067             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8068                                     complain, t, /*entering_scope=*/1);
8069           }
8070         else
8071           {
8072             member = 0;
8073             ctx = DECL_CONTEXT (t);
8074           }
8075         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8076         if (type == error_mark_node)
8077           return error_mark_node;
8078
8079         /* We do NOT check for matching decls pushed separately at this
8080            point, as they may not represent instantiations of this
8081            template, and in any case are considered separate under the
8082            discrete model.  */
8083         r = copy_decl (t);
8084         DECL_USE_TEMPLATE (r) = 0;
8085         TREE_TYPE (r) = type;
8086         /* Clear out the mangled name and RTL for the instantiation.  */
8087         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8088         SET_DECL_RTL (r, NULL_RTX);
8089         DECL_INITIAL (r) = NULL_TREE;
8090         DECL_CONTEXT (r) = ctx;
8091
8092         if (member && DECL_CONV_FN_P (r))
8093           /* Type-conversion operator.  Reconstruct the name, in
8094              case it's the name of one of the template's parameters.  */
8095           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8096
8097         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8098                                      complain, t);
8099         DECL_RESULT (r) = NULL_TREE;
8100
8101         TREE_STATIC (r) = 0;
8102         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8103         DECL_EXTERNAL (r) = 1;
8104         /* If this is an instantiation of a function with internal
8105            linkage, we already know what object file linkage will be
8106            assigned to the instantiation.  */
8107         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8108         DECL_DEFER_OUTPUT (r) = 0;
8109         TREE_CHAIN (r) = NULL_TREE;
8110         DECL_PENDING_INLINE_INFO (r) = 0;
8111         DECL_PENDING_INLINE_P (r) = 0;
8112         DECL_SAVED_TREE (r) = NULL_TREE;
8113         TREE_USED (r) = 0;
8114         if (DECL_CLONED_FUNCTION (r))
8115           {
8116             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
8117                                                args, complain, t);
8118             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
8119             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
8120           }
8121
8122         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8123            this in the special friend case mentioned above where
8124            GEN_TMPL is NULL.  */
8125         if (gen_tmpl)
8126           {
8127             DECL_TEMPLATE_INFO (r)
8128               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8129             SET_DECL_IMPLICIT_INSTANTIATION (r);
8130             register_specialization (r, gen_tmpl, argvec, false);
8131
8132             /* We're not supposed to instantiate default arguments
8133                until they are called, for a template.  But, for a
8134                declaration like:
8135
8136                  template <class T> void f ()
8137                  { extern void g(int i = T()); }
8138
8139                we should do the substitution when the template is
8140                instantiated.  We handle the member function case in
8141                instantiate_class_template since the default arguments
8142                might refer to other members of the class.  */
8143             if (!member
8144                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8145                 && !uses_template_parms (argvec))
8146               tsubst_default_arguments (r);
8147           }
8148         else
8149           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8150
8151         /* Copy the list of befriending classes.  */
8152         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8153              *friends;
8154              friends = &TREE_CHAIN (*friends))
8155           {
8156             *friends = copy_node (*friends);
8157             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8158                                             args, complain,
8159                                             in_decl);
8160           }
8161
8162         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8163           {
8164             maybe_retrofit_in_chrg (r);
8165             if (DECL_CONSTRUCTOR_P (r))
8166               grok_ctor_properties (ctx, r);
8167             /* If this is an instantiation of a member template, clone it.
8168                If it isn't, that'll be handled by
8169                clone_constructors_and_destructors.  */
8170             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8171               clone_function_decl (r, /*update_method_vec_p=*/0);
8172           }
8173         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8174                  && !grok_op_properties (r, (complain & tf_error) != 0))
8175           return error_mark_node;
8176
8177         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8178           SET_DECL_FRIEND_CONTEXT (r,
8179                                    tsubst (DECL_FRIEND_CONTEXT (t),
8180                                             args, complain, in_decl));
8181
8182         /* Possibly limit visibility based on template args.  */
8183         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8184         if (DECL_VISIBILITY_SPECIFIED (t))
8185           {
8186             DECL_VISIBILITY_SPECIFIED (r) = 0;
8187             DECL_ATTRIBUTES (r)
8188               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8189           }
8190         determine_visibility (r);
8191
8192         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8193                                         args, complain, in_decl);
8194       }
8195       break;
8196
8197     case PARM_DECL:
8198       {
8199         tree type = NULL_TREE;
8200         int i, len = 1;
8201         tree expanded_types = NULL_TREE;
8202         tree prev_r = NULL_TREE;
8203         tree first_r = NULL_TREE;
8204
8205         if (FUNCTION_PARAMETER_PACK_P (t))
8206           {
8207             /* If there is a local specialization that isn't a
8208                parameter pack, it means that we're doing a "simple"
8209                substitution from inside tsubst_pack_expansion. Just
8210                return the local specialization (which will be a single
8211                parm).  */
8212             tree spec = retrieve_local_specialization (t);
8213             if (spec 
8214                 && TREE_CODE (spec) == PARM_DECL
8215                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8216               return spec;
8217
8218             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8219                the parameters in this function parameter pack.  */
8220             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8221                                                     complain, in_decl);
8222             if (TREE_CODE (expanded_types) == TREE_VEC)
8223               {
8224                 len = TREE_VEC_LENGTH (expanded_types);
8225
8226                 /* Zero-length parameter packs are boring. Just substitute
8227                    into the chain.  */
8228                 if (len == 0)
8229                   return tsubst (TREE_CHAIN (t), args, complain, 
8230                                  TREE_CHAIN (t));
8231               }
8232             else
8233               {
8234                 /* All we did was update the type. Make a note of that.  */
8235                 type = expanded_types;
8236                 expanded_types = NULL_TREE;
8237               }
8238           }
8239
8240         /* Loop through all of the parameter's we'll build. When T is
8241            a function parameter pack, LEN is the number of expanded
8242            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8243         r = NULL_TREE;
8244         for (i = 0; i < len; ++i)
8245           {
8246             prev_r = r;
8247             r = copy_node (t);
8248             if (DECL_TEMPLATE_PARM_P (t))
8249               SET_DECL_TEMPLATE_PARM_P (r);
8250
8251             if (expanded_types)
8252               /* We're on the Ith parameter of the function parameter
8253                  pack.  */
8254               {
8255                 /* Get the Ith type.  */
8256                 type = TREE_VEC_ELT (expanded_types, i);
8257
8258                 if (DECL_NAME (r))
8259                   /* Rename the parameter to include the index.  */
8260                   DECL_NAME (r) =
8261                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8262               }
8263             else if (!type)
8264               /* We're dealing with a normal parameter.  */
8265               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8266
8267             type = type_decays_to (type);
8268             TREE_TYPE (r) = type;
8269             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8270
8271             if (DECL_INITIAL (r))
8272               {
8273                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8274                   DECL_INITIAL (r) = TREE_TYPE (r);
8275                 else
8276                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8277                                              complain, in_decl);
8278               }
8279
8280             DECL_CONTEXT (r) = NULL_TREE;
8281
8282             if (!DECL_TEMPLATE_PARM_P (r))
8283               DECL_ARG_TYPE (r) = type_passed_as (type);
8284
8285             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8286                                             args, complain, in_decl);
8287
8288             /* Keep track of the first new parameter we
8289                generate. That's what will be returned to the
8290                caller.  */
8291             if (!first_r)
8292               first_r = r;
8293
8294             /* Build a proper chain of parameters when substituting
8295                into a function parameter pack.  */
8296             if (prev_r)
8297               TREE_CHAIN (prev_r) = r;
8298           }
8299
8300         if (TREE_CHAIN (t))
8301           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8302                                    complain, TREE_CHAIN (t));
8303
8304         /* FIRST_R contains the start of the chain we've built.  */
8305         r = first_r;
8306       }
8307       break;
8308
8309     case FIELD_DECL:
8310       {
8311         tree type;
8312
8313         r = copy_decl (t);
8314         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8315         if (type == error_mark_node)
8316           return error_mark_node;
8317         TREE_TYPE (r) = type;
8318         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8319
8320         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8321         DECL_INITIAL (r)
8322           = tsubst_expr (DECL_INITIAL (t), args,
8323                          complain, in_decl,
8324                          /*integral_constant_expression_p=*/true);
8325         /* We don't have to set DECL_CONTEXT here; it is set by
8326            finish_member_declaration.  */
8327         TREE_CHAIN (r) = NULL_TREE;
8328         if (VOID_TYPE_P (type))
8329           error ("instantiation of %q+D as type %qT", r, type);
8330
8331         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8332                                         args, complain, in_decl);
8333       }
8334       break;
8335
8336     case USING_DECL:
8337       /* We reach here only for member using decls.  */
8338       if (DECL_DEPENDENT_P (t))
8339         {
8340           r = do_class_using_decl
8341             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8342              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8343           if (!r)
8344             r = error_mark_node;
8345         }
8346       else
8347         {
8348           r = copy_node (t);
8349           TREE_CHAIN (r) = NULL_TREE;
8350         }
8351       break;
8352
8353     case TYPE_DECL:
8354     case VAR_DECL:
8355       {
8356         tree argvec = NULL_TREE;
8357         tree gen_tmpl = NULL_TREE;
8358         tree spec;
8359         tree tmpl = NULL_TREE;
8360         tree ctx;
8361         tree type = NULL_TREE;
8362         bool local_p;
8363
8364         if (TREE_CODE (t) == TYPE_DECL
8365             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8366           {
8367             /* If this is the canonical decl, we don't have to
8368                mess with instantiations, and often we can't (for
8369                typename, template type parms and such).  Note that
8370                TYPE_NAME is not correct for the above test if
8371                we've copied the type for a typedef.  */
8372             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8373             if (type == error_mark_node)
8374               return error_mark_node;
8375             r = TYPE_NAME (type);
8376             break;
8377           }
8378
8379         /* Check to see if we already have the specialization we
8380            need.  */
8381         spec = NULL_TREE;
8382         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8383           {
8384             /* T is a static data member or namespace-scope entity.
8385                We have to substitute into namespace-scope variables
8386                (even though such entities are never templates) because
8387                of cases like:
8388                
8389                  template <class T> void f() { extern T t; }
8390
8391                where the entity referenced is not known until
8392                instantiation time.  */
8393             local_p = false;
8394             ctx = DECL_CONTEXT (t);
8395             if (DECL_CLASS_SCOPE_P (t))
8396               {
8397                 ctx = tsubst_aggr_type (ctx, args,
8398                                         complain,
8399                                         in_decl, /*entering_scope=*/1);
8400                 /* If CTX is unchanged, then T is in fact the
8401                    specialization we want.  That situation occurs when
8402                    referencing a static data member within in its own
8403                    class.  We can use pointer equality, rather than
8404                    same_type_p, because DECL_CONTEXT is always
8405                    canonical.  */
8406                 if (ctx == DECL_CONTEXT (t))
8407                   spec = t;
8408               }
8409
8410             if (!spec)
8411               {
8412                 tmpl = DECL_TI_TEMPLATE (t);
8413                 gen_tmpl = most_general_template (tmpl);
8414                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8415                 spec = (retrieve_specialization 
8416                         (gen_tmpl, argvec,
8417                          /*class_specializations_p=*/false));
8418               }
8419           }
8420         else
8421           {
8422             /* A local variable.  */
8423             local_p = true;
8424             /* Subsequent calls to pushdecl will fill this in.  */
8425             ctx = NULL_TREE;
8426             spec = retrieve_local_specialization (t);
8427           }
8428         /* If we already have the specialization we need, there is
8429            nothing more to do.  */ 
8430         if (spec)
8431           {
8432             r = spec;
8433             break;
8434           }
8435
8436         /* Create a new node for the specialization we need.  */
8437         r = copy_decl (t);
8438         if (type == NULL_TREE)
8439           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8440         if (TREE_CODE (r) == VAR_DECL)
8441           {
8442             /* Even if the original location is out of scope, the
8443                newly substituted one is not.  */
8444             DECL_DEAD_FOR_LOCAL (r) = 0;
8445             DECL_INITIALIZED_P (r) = 0;
8446             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8447             if (type == error_mark_node)
8448               return error_mark_node;
8449             if (TREE_CODE (type) == FUNCTION_TYPE)
8450               {
8451                 /* It may seem that this case cannot occur, since:
8452
8453                      typedef void f();
8454                      void g() { f x; }
8455
8456                    declares a function, not a variable.  However:
8457       
8458                      typedef void f();
8459                      template <typename T> void g() { T t; }
8460                      template void g<f>();
8461
8462                    is an attempt to declare a variable with function
8463                    type.  */
8464                 error ("variable %qD has function type",
8465                        /* R is not yet sufficiently initialized, so we
8466                           just use its name.  */
8467                        DECL_NAME (r));
8468                 return error_mark_node;
8469               }
8470             type = complete_type (type);
8471             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8472               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8473             type = check_var_type (DECL_NAME (r), type);
8474
8475             if (DECL_HAS_VALUE_EXPR_P (t))
8476               {
8477                 tree ve = DECL_VALUE_EXPR (t);
8478                 ve = tsubst_expr (ve, args, complain, in_decl,
8479                                   /*constant_expression_p=*/false);
8480                 SET_DECL_VALUE_EXPR (r, ve);
8481               }
8482           }
8483         else if (DECL_SELF_REFERENCE_P (t))
8484           SET_DECL_SELF_REFERENCE_P (r);
8485         TREE_TYPE (r) = type;
8486         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8487         DECL_CONTEXT (r) = ctx;
8488         /* Clear out the mangled name and RTL for the instantiation.  */
8489         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8490         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8491           SET_DECL_RTL (r, NULL_RTX);
8492         /* The initializer must not be expanded until it is required;
8493            see [temp.inst].  */
8494         DECL_INITIAL (r) = NULL_TREE;
8495         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8496           SET_DECL_RTL (r, NULL_RTX);
8497         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8498         if (TREE_CODE (r) == VAR_DECL)
8499           {
8500             /* Possibly limit visibility based on template args.  */
8501             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8502             if (DECL_VISIBILITY_SPECIFIED (t))
8503               {
8504                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8505                 DECL_ATTRIBUTES (r)
8506                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8507               }
8508             determine_visibility (r);
8509           }
8510         /* Preserve a typedef that names a type.  */
8511         else if (TREE_CODE (r) == TYPE_DECL
8512                  && DECL_ORIGINAL_TYPE (t)
8513                  && type != error_mark_node)
8514           {
8515             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8516                                              args, complain, in_decl);
8517             TREE_TYPE (r) = type = build_variant_type_copy (type);
8518             TYPE_NAME (type) = r;
8519           }
8520
8521         if (!local_p)
8522           {
8523             /* A static data member declaration is always marked
8524                external when it is declared in-class, even if an
8525                initializer is present.  We mimic the non-template
8526                processing here.  */
8527             DECL_EXTERNAL (r) = 1;
8528
8529             register_specialization (r, gen_tmpl, argvec, false);
8530             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8531             SET_DECL_IMPLICIT_INSTANTIATION (r);
8532           }
8533         else
8534           register_local_specialization (r, t);
8535
8536         TREE_CHAIN (r) = NULL_TREE;
8537
8538         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
8539                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
8540                                         args, complain, in_decl);
8541         layout_decl (r, 0);
8542       }
8543       break;
8544
8545     default:
8546       gcc_unreachable ();
8547     }
8548
8549   /* Restore the file and line information.  */
8550   input_location = saved_loc;
8551
8552   return r;
8553 }
8554
8555 /* Substitute into the ARG_TYPES of a function type.  */
8556
8557 static tree
8558 tsubst_arg_types (tree arg_types,
8559                   tree args,
8560                   tsubst_flags_t complain,
8561                   tree in_decl)
8562 {
8563   tree remaining_arg_types;
8564   tree type = NULL_TREE;
8565   int i = 1;
8566   tree expanded_args = NULL_TREE;
8567   tree default_arg;
8568
8569   if (!arg_types || arg_types == void_list_node)
8570     return arg_types;
8571
8572   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8573                                           args, complain, in_decl);
8574   if (remaining_arg_types == error_mark_node)
8575     return error_mark_node;
8576
8577   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8578     {
8579       /* For a pack expansion, perform substitution on the
8580          entire expression. Later on, we'll handle the arguments
8581          one-by-one.  */
8582       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8583                                             args, complain, in_decl);
8584
8585       if (TREE_CODE (expanded_args) == TREE_VEC)
8586         /* So that we'll spin through the parameters, one by one.  */
8587         i = TREE_VEC_LENGTH (expanded_args);
8588       else
8589         {
8590           /* We only partially substituted into the parameter
8591              pack. Our type is TYPE_PACK_EXPANSION.  */
8592           type = expanded_args;
8593           expanded_args = NULL_TREE;
8594         }
8595     }
8596
8597   while (i > 0) {
8598     --i;
8599     
8600     if (expanded_args)
8601       type = TREE_VEC_ELT (expanded_args, i);
8602     else if (!type)
8603       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8604
8605     if (type == error_mark_node)
8606       return error_mark_node;
8607     if (VOID_TYPE_P (type))
8608       {
8609         if (complain & tf_error)
8610           {
8611             error ("invalid parameter type %qT", type);
8612             if (in_decl)
8613               error ("in declaration %q+D", in_decl);
8614           }
8615         return error_mark_node;
8616     }
8617     
8618     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8619        top-level qualifiers as required.  */
8620     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8621
8622     /* We do not substitute into default arguments here.  The standard
8623        mandates that they be instantiated only when needed, which is
8624        done in build_over_call.  */
8625     default_arg = TREE_PURPOSE (arg_types);
8626
8627     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8628       {
8629         /* We've instantiated a template before its default arguments
8630            have been parsed.  This can happen for a nested template
8631            class, and is not an error unless we require the default
8632            argument in a call of this function.  */
8633         remaining_arg_types = 
8634           tree_cons (default_arg, type, remaining_arg_types);
8635         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8636                        remaining_arg_types);
8637       }
8638     else
8639       remaining_arg_types = 
8640         hash_tree_cons (default_arg, type, remaining_arg_types);
8641   }
8642         
8643   return remaining_arg_types;
8644 }
8645
8646 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8647    *not* handle the exception-specification for FNTYPE, because the
8648    initial substitution of explicitly provided template parameters
8649    during argument deduction forbids substitution into the
8650    exception-specification:
8651
8652      [temp.deduct]
8653
8654      All references in the function type of the function template to  the
8655      corresponding template parameters are replaced by the specified tem-
8656      plate argument values.  If a substitution in a template parameter or
8657      in  the function type of the function template results in an invalid
8658      type, type deduction fails.  [Note: The equivalent  substitution  in
8659      exception specifications is done only when the function is instanti-
8660      ated, at which point a program is  ill-formed  if  the  substitution
8661      results in an invalid type.]  */
8662
8663 static tree
8664 tsubst_function_type (tree t,
8665                       tree args,
8666                       tsubst_flags_t complain,
8667                       tree in_decl)
8668 {
8669   tree return_type;
8670   tree arg_types;
8671   tree fntype;
8672
8673   /* The TYPE_CONTEXT is not used for function/method types.  */
8674   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8675
8676   /* Substitute the return type.  */
8677   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8678   if (return_type == error_mark_node)
8679     return error_mark_node;
8680   /* The standard does not presently indicate that creation of a
8681      function type with an invalid return type is a deduction failure.
8682      However, that is clearly analogous to creating an array of "void"
8683      or a reference to a reference.  This is core issue #486.  */
8684   if (TREE_CODE (return_type) == ARRAY_TYPE
8685       || TREE_CODE (return_type) == FUNCTION_TYPE)
8686     {
8687       if (complain & tf_error)
8688         {
8689           if (TREE_CODE (return_type) == ARRAY_TYPE)
8690             error ("function returning an array");
8691           else
8692             error ("function returning a function");
8693         }
8694       return error_mark_node;
8695     }
8696
8697   /* Substitute the argument types.  */
8698   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8699                                 complain, in_decl);
8700   if (arg_types == error_mark_node)
8701     return error_mark_node;
8702
8703   if (TYPE_QUALS (return_type) != TYPE_UNQUALIFIED
8704       && in_decl != NULL_TREE
8705       && !TREE_NO_WARNING (in_decl)
8706       && (SCALAR_TYPE_P (return_type) || VOID_TYPE_P (return_type)))
8707     warning (OPT_Wignored_qualifiers,
8708             "type qualifiers ignored on function return type");
8709
8710   /* Construct a new type node and return it.  */
8711   if (TREE_CODE (t) == FUNCTION_TYPE)
8712     fntype = build_function_type (return_type, arg_types);
8713   else
8714     {
8715       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8716       if (! IS_AGGR_TYPE (r))
8717         {
8718           /* [temp.deduct]
8719
8720              Type deduction may fail for any of the following
8721              reasons:
8722
8723              -- Attempting to create "pointer to member of T" when T
8724              is not a class type.  */
8725           if (complain & tf_error)
8726             error ("creating pointer to member function of non-class type %qT",
8727                       r);
8728           return error_mark_node;
8729         }
8730
8731       fntype = build_method_type_directly (r, return_type,
8732                                            TREE_CHAIN (arg_types));
8733     }
8734   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
8735   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
8736
8737   return fntype;
8738 }
8739
8740 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
8741    ARGS into that specification, and return the substituted
8742    specification.  If there is no specification, return NULL_TREE.  */
8743
8744 static tree
8745 tsubst_exception_specification (tree fntype,
8746                                 tree args,
8747                                 tsubst_flags_t complain,
8748                                 tree in_decl)
8749 {
8750   tree specs;
8751   tree new_specs;
8752
8753   specs = TYPE_RAISES_EXCEPTIONS (fntype);
8754   new_specs = NULL_TREE;
8755   if (specs)
8756     {
8757       if (! TREE_VALUE (specs))
8758         new_specs = specs;
8759       else
8760         while (specs)
8761           {
8762             tree spec;
8763             int i, len = 1;
8764             tree expanded_specs = NULL_TREE;
8765
8766             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
8767               {
8768                 /* Expand the pack expansion type.  */
8769                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
8770                                                        args, complain,
8771                                                        in_decl);
8772
8773                 if (expanded_specs == error_mark_node)
8774                   return error_mark_node;
8775                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
8776                   len = TREE_VEC_LENGTH (expanded_specs);
8777                 else
8778                   {
8779                     /* We're substituting into a member template, so
8780                        we got a TYPE_PACK_EXPANSION back.  Add that
8781                        expansion and move on.  */
8782                     gcc_assert (TREE_CODE (expanded_specs) 
8783                                 == TYPE_PACK_EXPANSION);
8784                     new_specs = add_exception_specifier (new_specs,
8785                                                          expanded_specs,
8786                                                          complain);
8787                     specs = TREE_CHAIN (specs);
8788                     continue;
8789                   }
8790               }
8791
8792             for (i = 0; i < len; ++i)
8793               {
8794                 if (expanded_specs)
8795                   spec = TREE_VEC_ELT (expanded_specs, i);
8796                 else
8797                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
8798                 if (spec == error_mark_node)
8799                   return spec;
8800                 new_specs = add_exception_specifier (new_specs, spec, 
8801                                                      complain);
8802               }
8803
8804             specs = TREE_CHAIN (specs);
8805           }
8806     }
8807   return new_specs;
8808 }
8809
8810 /* Take the tree structure T and replace template parameters used
8811    therein with the argument vector ARGS.  IN_DECL is an associated
8812    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
8813    Issue error and warning messages under control of COMPLAIN.  Note
8814    that we must be relatively non-tolerant of extensions here, in
8815    order to preserve conformance; if we allow substitutions that
8816    should not be allowed, we may allow argument deductions that should
8817    not succeed, and therefore report ambiguous overload situations
8818    where there are none.  In theory, we could allow the substitution,
8819    but indicate that it should have failed, and allow our caller to
8820    make sure that the right thing happens, but we don't try to do this
8821    yet.
8822
8823    This function is used for dealing with types, decls and the like;
8824    for expressions, use tsubst_expr or tsubst_copy.  */
8825
8826 static tree
8827 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8828 {
8829   tree type, r;
8830
8831   if (t == NULL_TREE || t == error_mark_node
8832       || t == integer_type_node
8833       || t == void_type_node
8834       || t == char_type_node
8835       || t == unknown_type_node
8836       || TREE_CODE (t) == NAMESPACE_DECL)
8837     return t;
8838
8839   if (DECL_P (t))
8840     return tsubst_decl (t, args, complain);
8841
8842   if (TREE_CODE (t) == IDENTIFIER_NODE)
8843     type = IDENTIFIER_TYPE_VALUE (t);
8844   else
8845     type = TREE_TYPE (t);
8846
8847   gcc_assert (type != unknown_type_node);
8848
8849   /* Reuse typedefs.  We need to do this to handle dependent attributes,
8850      such as attribute aligned.  */
8851   if (TYPE_P (t)
8852       && TYPE_NAME (t)
8853       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
8854     {
8855       tree decl = TYPE_NAME (t);
8856       
8857       if (DECL_CLASS_SCOPE_P (decl)
8858           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl)))
8859         {
8860           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
8861           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
8862           r = retrieve_specialization (tmpl, gen_args, false);
8863         }
8864       else if (DECL_FUNCTION_SCOPE_P (decl)
8865                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl)))
8866         r = retrieve_local_specialization (decl);
8867       else
8868         /* The typedef is from a non-template context.  */
8869         return t;
8870
8871       if (r)
8872         {
8873           r = TREE_TYPE (r);
8874           r = cp_build_qualified_type_real
8875             (r, cp_type_quals (t) | cp_type_quals (r),
8876              complain | tf_ignore_bad_quals);
8877           return r;
8878         }
8879       /* Else we must be instantiating the typedef, so fall through.  */
8880     }
8881
8882   if (type
8883       && TREE_CODE (t) != TYPENAME_TYPE
8884       && TREE_CODE (t) != IDENTIFIER_NODE
8885       && TREE_CODE (t) != FUNCTION_TYPE
8886       && TREE_CODE (t) != METHOD_TYPE)
8887     type = tsubst (type, args, complain, in_decl);
8888   if (type == error_mark_node)
8889     return error_mark_node;
8890
8891   switch (TREE_CODE (t))
8892     {
8893     case RECORD_TYPE:
8894     case UNION_TYPE:
8895     case ENUMERAL_TYPE:
8896       return tsubst_aggr_type (t, args, complain, in_decl,
8897                                /*entering_scope=*/0);
8898
8899     case ERROR_MARK:
8900     case IDENTIFIER_NODE:
8901     case VOID_TYPE:
8902     case REAL_TYPE:
8903     case COMPLEX_TYPE:
8904     case VECTOR_TYPE:
8905     case BOOLEAN_TYPE:
8906     case INTEGER_CST:
8907     case REAL_CST:
8908     case STRING_CST:
8909       return t;
8910
8911     case INTEGER_TYPE:
8912       if (t == integer_type_node)
8913         return t;
8914
8915       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
8916           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
8917         return t;
8918
8919       {
8920         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
8921
8922         max = tsubst_expr (omax, args, complain, in_decl,
8923                            /*integral_constant_expression_p=*/false);
8924         max = fold_decl_constant_value (max);
8925
8926         if (TREE_CODE (max) != INTEGER_CST 
8927             && TREE_CODE (max) != TEMPLATE_PARM_INDEX
8928             && !at_function_scope_p ())
8929           {
8930             if (complain & tf_error)
8931               error ("array bound is not an integer constant");
8932             return error_mark_node;
8933           }
8934
8935         /* [temp.deduct]
8936
8937            Type deduction may fail for any of the following
8938            reasons:
8939
8940              Attempting to create an array with a size that is
8941              zero or negative.  */
8942         if (integer_zerop (max) && !(complain & tf_error))
8943           /* We must fail if performing argument deduction (as
8944              indicated by the state of complain), so that
8945              another substitution can be found.  */
8946           return error_mark_node;
8947         else if (TREE_CODE (max) == INTEGER_CST
8948                  && INT_CST_LT (max, integer_zero_node))
8949           {
8950             if (complain & tf_error)
8951               error ("creating array with negative size (%qE)", max);
8952
8953             return error_mark_node;
8954           }
8955
8956         return compute_array_index_type (NULL_TREE, max);
8957       }
8958
8959     case TEMPLATE_TYPE_PARM:
8960     case TEMPLATE_TEMPLATE_PARM:
8961     case BOUND_TEMPLATE_TEMPLATE_PARM:
8962     case TEMPLATE_PARM_INDEX:
8963       {
8964         int idx;
8965         int level;
8966         int levels;
8967         tree arg = NULL_TREE;
8968
8969         r = NULL_TREE;
8970
8971         gcc_assert (TREE_VEC_LENGTH (args) > 0);
8972         template_parm_level_and_index (t, &level, &idx); 
8973
8974         levels = TMPL_ARGS_DEPTH (args);
8975         if (level <= levels)
8976           {
8977             arg = TMPL_ARG (args, level, idx);
8978
8979             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
8980               /* See through ARGUMENT_PACK_SELECT arguments. */
8981               arg = ARGUMENT_PACK_SELECT_ARG (arg);
8982           }
8983
8984         if (arg == error_mark_node)
8985           return error_mark_node;
8986         else if (arg != NULL_TREE)
8987           {
8988             if (ARGUMENT_PACK_P (arg))
8989               /* If ARG is an argument pack, we don't actually want to
8990                  perform a substitution here, because substitutions
8991                  for argument packs are only done
8992                  element-by-element. We can get to this point when
8993                  substituting the type of a non-type template
8994                  parameter pack, when that type actually contains
8995                  template parameter packs from an outer template, e.g.,
8996
8997                  template<typename... Types> struct A {
8998                    template<Types... Values> struct B { };
8999                  };  */
9000               return t;
9001
9002             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9003               {
9004                 int quals;
9005                 gcc_assert (TYPE_P (arg));
9006
9007                 /* cv-quals from the template are discarded when
9008                    substituting in a function or reference type.  */
9009                 if (TREE_CODE (arg) == FUNCTION_TYPE
9010                     || TREE_CODE (arg) == METHOD_TYPE
9011                     || TREE_CODE (arg) == REFERENCE_TYPE)
9012                   quals = cp_type_quals (arg);
9013                 else
9014                   quals = cp_type_quals (arg) | cp_type_quals (t);
9015                   
9016                 return cp_build_qualified_type_real
9017                   (arg, quals, complain | tf_ignore_bad_quals);
9018               }
9019             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9020               {
9021                 /* We are processing a type constructed from a
9022                    template template parameter.  */
9023                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9024                                       args, complain, in_decl);
9025                 if (argvec == error_mark_node)
9026                   return error_mark_node;
9027
9028                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9029                    are resolving nested-types in the signature of a
9030                    member function templates.  Otherwise ARG is a
9031                    TEMPLATE_DECL and is the real template to be
9032                    instantiated.  */
9033                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9034                   arg = TYPE_NAME (arg);
9035
9036                 r = lookup_template_class (arg,
9037                                            argvec, in_decl,
9038                                            DECL_CONTEXT (arg),
9039                                             /*entering_scope=*/0,
9040                                            complain);
9041                 return cp_build_qualified_type_real
9042                   (r, TYPE_QUALS (t), complain);
9043               }
9044             else
9045               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9046               return arg;
9047           }
9048
9049         if (level == 1)
9050           /* This can happen during the attempted tsubst'ing in
9051              unify.  This means that we don't yet have any information
9052              about the template parameter in question.  */
9053           return t;
9054
9055         /* If we get here, we must have been looking at a parm for a
9056            more deeply nested template.  Make a new version of this
9057            template parameter, but with a lower level.  */
9058         switch (TREE_CODE (t))
9059           {
9060           case TEMPLATE_TYPE_PARM:
9061           case TEMPLATE_TEMPLATE_PARM:
9062           case BOUND_TEMPLATE_TEMPLATE_PARM:
9063             if (cp_type_quals (t))
9064               {
9065                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9066                 r = cp_build_qualified_type_real
9067                   (r, cp_type_quals (t),
9068                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9069                                ? tf_ignore_bad_quals : 0));
9070               }
9071             else
9072               {
9073                 r = copy_type (t);
9074                 TEMPLATE_TYPE_PARM_INDEX (r)
9075                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9076                                                 r, levels, args, complain);
9077                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9078                 TYPE_MAIN_VARIANT (r) = r;
9079                 TYPE_POINTER_TO (r) = NULL_TREE;
9080                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9081
9082                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9083                   /* We have reduced the level of the template
9084                      template parameter, but not the levels of its
9085                      template parameters, so canonical_type_parameter
9086                      will not be able to find the canonical template
9087                      template parameter for this level. Thus, we
9088                      require structural equality checking to compare
9089                      TEMPLATE_TEMPLATE_PARMs. */
9090                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9091                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9092                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9093                 else
9094                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9095
9096                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9097                   {
9098                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9099                                           complain, in_decl);
9100                     if (argvec == error_mark_node)
9101                       return error_mark_node;
9102
9103                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9104                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9105                   }
9106               }
9107             break;
9108
9109           case TEMPLATE_PARM_INDEX:
9110             r = reduce_template_parm_level (t, type, levels, args, complain);
9111             break;
9112
9113           default:
9114             gcc_unreachable ();
9115           }
9116
9117         return r;
9118       }
9119
9120     case TREE_LIST:
9121       {
9122         tree purpose, value, chain;
9123
9124         if (t == void_list_node)
9125           return t;
9126
9127         purpose = TREE_PURPOSE (t);
9128         if (purpose)
9129           {
9130             purpose = tsubst (purpose, args, complain, in_decl);
9131             if (purpose == error_mark_node)
9132               return error_mark_node;
9133           }
9134         value = TREE_VALUE (t);
9135         if (value)
9136           {
9137             value = tsubst (value, args, complain, in_decl);
9138             if (value == error_mark_node)
9139               return error_mark_node;
9140           }
9141         chain = TREE_CHAIN (t);
9142         if (chain && chain != void_type_node)
9143           {
9144             chain = tsubst (chain, args, complain, in_decl);
9145             if (chain == error_mark_node)
9146               return error_mark_node;
9147           }
9148         if (purpose == TREE_PURPOSE (t)
9149             && value == TREE_VALUE (t)
9150             && chain == TREE_CHAIN (t))
9151           return t;
9152         return hash_tree_cons (purpose, value, chain);
9153       }
9154
9155     case TREE_BINFO:
9156       /* We should never be tsubsting a binfo.  */
9157       gcc_unreachable ();
9158
9159     case TREE_VEC:
9160       /* A vector of template arguments.  */
9161       gcc_assert (!type);
9162       return tsubst_template_args (t, args, complain, in_decl);
9163
9164     case POINTER_TYPE:
9165     case REFERENCE_TYPE:
9166       {
9167         enum tree_code code;
9168
9169         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9170           return t;
9171
9172         code = TREE_CODE (t);
9173
9174
9175         /* [temp.deduct]
9176
9177            Type deduction may fail for any of the following
9178            reasons:
9179
9180            -- Attempting to create a pointer to reference type.
9181            -- Attempting to create a reference to a reference type or
9182               a reference to void.
9183
9184           Core issue 106 says that creating a reference to a reference
9185           during instantiation is no longer a cause for failure. We
9186           only enforce this check in strict C++98 mode.  */
9187         if ((TREE_CODE (type) == REFERENCE_TYPE
9188              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9189             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9190           {
9191             static location_t last_loc;
9192
9193             /* We keep track of the last time we issued this error
9194                message to avoid spewing a ton of messages during a
9195                single bad template instantiation.  */
9196             if (complain & tf_error
9197 #ifdef USE_MAPPED_LOCATION
9198                 && last_loc != input_location
9199 #else
9200                 && (last_loc.line != input_line
9201                     || last_loc.file != input_filename)
9202 #endif
9203                   )
9204               {
9205                 if (TREE_CODE (type) == VOID_TYPE)
9206                   error ("forming reference to void");
9207                 else
9208                   error ("forming %s to reference type %qT",
9209                          (code == POINTER_TYPE) ? "pointer" : "reference",
9210                          type);
9211                 last_loc = input_location;
9212               }
9213
9214             return error_mark_node;
9215           }
9216         else if (code == POINTER_TYPE)
9217           {
9218             r = build_pointer_type (type);
9219             if (TREE_CODE (type) == METHOD_TYPE)
9220               r = build_ptrmemfunc_type (r);
9221           }
9222         else if (TREE_CODE (type) == REFERENCE_TYPE)
9223           /* In C++0x, during template argument substitution, when there is an
9224              attempt to create a reference to a reference type, reference
9225              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9226
9227              "If a template-argument for a template-parameter T names a type
9228              that is a reference to a type A, an attempt to create the type
9229              'lvalue reference to cv T' creates the type 'lvalue reference to
9230              A,' while an attempt to create the type type rvalue reference to
9231              cv T' creates the type T"
9232           */
9233           r = cp_build_reference_type
9234               (TREE_TYPE (type),
9235                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9236         else
9237           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9238         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9239
9240         if (r != error_mark_node)
9241           /* Will this ever be needed for TYPE_..._TO values?  */
9242           layout_type (r);
9243
9244         return r;
9245       }
9246     case OFFSET_TYPE:
9247       {
9248         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9249         if (r == error_mark_node || !IS_AGGR_TYPE (r))
9250           {
9251             /* [temp.deduct]
9252
9253                Type deduction may fail for any of the following
9254                reasons:
9255
9256                -- Attempting to create "pointer to member of T" when T
9257                   is not a class type.  */
9258             if (complain & tf_error)
9259               error ("creating pointer to member of non-class type %qT", r);
9260             return error_mark_node;
9261           }
9262         if (TREE_CODE (type) == REFERENCE_TYPE)
9263           {
9264             if (complain & tf_error)
9265               error ("creating pointer to member reference type %qT", type);
9266             return error_mark_node;
9267           }
9268         if (TREE_CODE (type) == VOID_TYPE)
9269           {
9270             if (complain & tf_error)
9271               error ("creating pointer to member of type void");
9272             return error_mark_node;
9273           }
9274         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9275         if (TREE_CODE (type) == FUNCTION_TYPE)
9276           {
9277             /* The type of the implicit object parameter gets its
9278                cv-qualifiers from the FUNCTION_TYPE. */
9279             tree method_type;
9280             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9281                                                       cp_type_quals (type));
9282             tree memptr;
9283             method_type = build_method_type_directly (this_type,
9284                                                       TREE_TYPE (type),
9285                                                       TYPE_ARG_TYPES (type));
9286             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9287             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9288                                                  complain);
9289           }
9290         else
9291           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9292                                                TYPE_QUALS (t),
9293                                                complain);
9294       }
9295     case FUNCTION_TYPE:
9296     case METHOD_TYPE:
9297       {
9298         tree fntype;
9299         tree specs;
9300         fntype = tsubst_function_type (t, args, complain, in_decl);
9301         if (fntype == error_mark_node)
9302           return error_mark_node;
9303
9304         /* Substitute the exception specification.  */
9305         specs = tsubst_exception_specification (t, args, complain,
9306                                                 in_decl);
9307         if (specs == error_mark_node)
9308           return error_mark_node;
9309         if (specs)
9310           fntype = build_exception_variant (fntype, specs);
9311         return fntype;
9312       }
9313     case ARRAY_TYPE:
9314       {
9315         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9316         if (domain == error_mark_node)
9317           return error_mark_node;
9318
9319         /* As an optimization, we avoid regenerating the array type if
9320            it will obviously be the same as T.  */
9321         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9322           return t;
9323
9324         /* These checks should match the ones in grokdeclarator.
9325
9326            [temp.deduct]
9327
9328            The deduction may fail for any of the following reasons:
9329
9330            -- Attempting to create an array with an element type that
9331               is void, a function type, or a reference type, or [DR337]
9332               an abstract class type.  */
9333         if (TREE_CODE (type) == VOID_TYPE
9334             || TREE_CODE (type) == FUNCTION_TYPE
9335             || TREE_CODE (type) == REFERENCE_TYPE)
9336           {
9337             if (complain & tf_error)
9338               error ("creating array of %qT", type);
9339             return error_mark_node;
9340           }
9341         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9342           {
9343             if (complain & tf_error)
9344               error ("creating array of %qT, which is an abstract class type",
9345                      type);
9346             return error_mark_node;
9347           }
9348
9349         r = build_cplus_array_type (type, domain);
9350
9351         if (TYPE_USER_ALIGN (t))
9352           {
9353             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9354             TYPE_USER_ALIGN (r) = 1;
9355           }
9356
9357         return r;
9358       }
9359
9360     case PLUS_EXPR:
9361     case MINUS_EXPR:
9362       {
9363         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9364         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9365
9366         if (e1 == error_mark_node || e2 == error_mark_node)
9367           return error_mark_node;
9368
9369         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9370       }
9371
9372     case NEGATE_EXPR:
9373     case NOP_EXPR:
9374       {
9375         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9376         if (e == error_mark_node)
9377           return error_mark_node;
9378
9379         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9380       }
9381
9382     case TYPENAME_TYPE:
9383       {
9384         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9385                                      in_decl, /*entering_scope=*/1);
9386         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9387                               complain, in_decl);
9388
9389         if (ctx == error_mark_node || f == error_mark_node)
9390           return error_mark_node;
9391
9392         if (!IS_AGGR_TYPE (ctx))
9393           {
9394             if (complain & tf_error)
9395               error ("%qT is not a class, struct, or union type", ctx);
9396             return error_mark_node;
9397           }
9398         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9399           {
9400             /* Normally, make_typename_type does not require that the CTX
9401                have complete type in order to allow things like:
9402
9403                  template <class T> struct S { typename S<T>::X Y; };
9404
9405                But, such constructs have already been resolved by this
9406                point, so here CTX really should have complete type, unless
9407                it's a partial instantiation.  */
9408             ctx = complete_type (ctx);
9409             if (!COMPLETE_TYPE_P (ctx))
9410               {
9411                 if (complain & tf_error)
9412                   cxx_incomplete_type_error (NULL_TREE, ctx);
9413                 return error_mark_node;
9414               }
9415           }
9416
9417         f = make_typename_type (ctx, f, typename_type,
9418                                 (complain & tf_error) | tf_keep_type_decl);
9419         if (f == error_mark_node)
9420           return f;
9421         if (TREE_CODE (f) == TYPE_DECL)
9422           {
9423             complain |= tf_ignore_bad_quals;
9424             f = TREE_TYPE (f);
9425           }
9426
9427         if (TREE_CODE (f) != TYPENAME_TYPE)
9428           {
9429             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9430               error ("%qT resolves to %qT, which is not an enumeration type",
9431                      t, f);
9432             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9433               error ("%qT resolves to %qT, which is is not a class type",
9434                      t, f);
9435           }
9436
9437         return cp_build_qualified_type_real
9438           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9439       }
9440
9441     case UNBOUND_CLASS_TEMPLATE:
9442       {
9443         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9444                                      in_decl, /*entering_scope=*/1);
9445         tree name = TYPE_IDENTIFIER (t);
9446         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9447
9448         if (ctx == error_mark_node || name == error_mark_node)
9449           return error_mark_node;
9450
9451         if (parm_list)
9452           parm_list = tsubst_template_parms (parm_list, args, complain);
9453         return make_unbound_class_template (ctx, name, parm_list, complain);
9454       }
9455
9456     case INDIRECT_REF:
9457     case ADDR_EXPR:
9458     case CALL_EXPR:
9459       gcc_unreachable ();
9460
9461     case ARRAY_REF:
9462       {
9463         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9464         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9465                                /*integral_constant_expression_p=*/false);
9466         if (e1 == error_mark_node || e2 == error_mark_node)
9467           return error_mark_node;
9468
9469         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9470       }
9471
9472     case SCOPE_REF:
9473       {
9474         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9475         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9476         if (e1 == error_mark_node || e2 == error_mark_node)
9477           return error_mark_node;
9478
9479         return build_qualified_name (/*type=*/NULL_TREE,
9480                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9481       }
9482
9483     case TYPEOF_TYPE:
9484       {
9485         tree type;
9486
9487         type = finish_typeof (tsubst_expr 
9488                               (TYPEOF_TYPE_EXPR (t), args,
9489                                complain, in_decl,
9490                                /*integral_constant_expression_p=*/false));
9491         return cp_build_qualified_type_real (type,
9492                                              cp_type_quals (t)
9493                                              | cp_type_quals (type),
9494                                              complain);
9495       }
9496
9497     case DECLTYPE_TYPE:
9498       {
9499         tree type;
9500
9501         type = 
9502           finish_decltype_type (tsubst_expr 
9503                                 (DECLTYPE_TYPE_EXPR (t), args,
9504                                  complain, in_decl,
9505                                  /*integral_constant_expression_p=*/false),
9506                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9507         return cp_build_qualified_type_real (type,
9508                                              cp_type_quals (t)
9509                                              | cp_type_quals (type),
9510                                              complain);
9511       }
9512
9513     case TYPE_ARGUMENT_PACK:
9514     case NONTYPE_ARGUMENT_PACK:
9515       {
9516         tree r = make_node (TREE_CODE (t));
9517         tree packed_out = 
9518           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9519                                 args,
9520                                 complain,
9521                                 in_decl);
9522         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9523
9524         /* For template nontype argument packs, also substitute into
9525            the type.  */
9526         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9527           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9528
9529         return r;
9530       }
9531       break;
9532
9533     default:
9534       sorry ("use of %qs in template",
9535              tree_code_name [(int) TREE_CODE (t)]);
9536       return error_mark_node;
9537     }
9538 }
9539
9540 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9541    type of the expression on the left-hand side of the "." or "->"
9542    operator.  */
9543
9544 static tree
9545 tsubst_baselink (tree baselink, tree object_type,
9546                  tree args, tsubst_flags_t complain, tree in_decl)
9547 {
9548     tree name;
9549     tree qualifying_scope;
9550     tree fns;
9551     tree optype;
9552     tree template_args = 0;
9553     bool template_id_p = false;
9554
9555     /* A baselink indicates a function from a base class.  Both the
9556        BASELINK_ACCESS_BINFO and the base class referenced may
9557        indicate bases of the template class, rather than the
9558        instantiated class.  In addition, lookups that were not
9559        ambiguous before may be ambiguous now.  Therefore, we perform
9560        the lookup again.  */
9561     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9562     qualifying_scope = tsubst (qualifying_scope, args,
9563                                complain, in_decl);
9564     fns = BASELINK_FUNCTIONS (baselink);
9565     optype = BASELINK_OPTYPE (baselink);
9566     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9567       {
9568         template_id_p = true;
9569         template_args = TREE_OPERAND (fns, 1);
9570         fns = TREE_OPERAND (fns, 0);
9571         if (template_args)
9572           template_args = tsubst_template_args (template_args, args,
9573                                                 complain, in_decl);
9574       }
9575     name = DECL_NAME (get_first_fn (fns));
9576     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9577
9578     /* If lookup found a single function, mark it as used at this
9579        point.  (If it lookup found multiple functions the one selected
9580        later by overload resolution will be marked as used at that
9581        point.)  */
9582     if (BASELINK_P (baselink))
9583       fns = BASELINK_FUNCTIONS (baselink);
9584     if (!template_id_p && !really_overloaded_fn (fns))
9585       mark_used (OVL_CURRENT (fns));
9586
9587     /* Add back the template arguments, if present.  */
9588     if (BASELINK_P (baselink) && template_id_p)
9589       BASELINK_FUNCTIONS (baselink)
9590         = build_nt (TEMPLATE_ID_EXPR,
9591                     BASELINK_FUNCTIONS (baselink),
9592                     template_args);
9593     /* Update the conversion operator type.  */
9594     BASELINK_OPTYPE (baselink) 
9595       = tsubst (optype, args, complain, in_decl);
9596
9597     if (!object_type)
9598       object_type = current_class_type;
9599     return adjust_result_of_qualified_name_lookup (baselink,
9600                                                    qualifying_scope,
9601                                                    object_type);
9602 }
9603
9604 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9605    true if the qualified-id will be a postfix-expression in-and-of
9606    itself; false if more of the postfix-expression follows the
9607    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9608    of "&".  */
9609
9610 static tree
9611 tsubst_qualified_id (tree qualified_id, tree args,
9612                      tsubst_flags_t complain, tree in_decl,
9613                      bool done, bool address_p)
9614 {
9615   tree expr;
9616   tree scope;
9617   tree name;
9618   bool is_template;
9619   tree template_args;
9620
9621   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9622
9623   /* Figure out what name to look up.  */
9624   name = TREE_OPERAND (qualified_id, 1);
9625   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9626     {
9627       is_template = true;
9628       template_args = TREE_OPERAND (name, 1);
9629       if (template_args)
9630         template_args = tsubst_template_args (template_args, args,
9631                                               complain, in_decl);
9632       name = TREE_OPERAND (name, 0);
9633     }
9634   else
9635     {
9636       is_template = false;
9637       template_args = NULL_TREE;
9638     }
9639
9640   /* Substitute into the qualifying scope.  When there are no ARGS, we
9641      are just trying to simplify a non-dependent expression.  In that
9642      case the qualifying scope may be dependent, and, in any case,
9643      substituting will not help.  */
9644   scope = TREE_OPERAND (qualified_id, 0);
9645   if (args)
9646     {
9647       scope = tsubst (scope, args, complain, in_decl);
9648       expr = tsubst_copy (name, args, complain, in_decl);
9649     }
9650   else
9651     expr = name;
9652
9653   if (dependent_type_p (scope))
9654     return build_qualified_name (/*type=*/NULL_TREE,
9655                                  scope, expr,
9656                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9657
9658   if (!BASELINK_P (name) && !DECL_P (expr))
9659     {
9660       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9661         /* If this were actually a destructor call, it would have been
9662            parsed as such by the parser.  */
9663         expr = error_mark_node;
9664       else
9665         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9666       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9667                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9668         {
9669           if (complain & tf_error)
9670             {
9671               error ("dependent-name %qE is parsed as a non-type, but "
9672                      "instantiation yields a type", qualified_id);
9673               inform ("say %<typename %E%> if a type is meant", qualified_id);
9674             }
9675           return error_mark_node;
9676         }
9677     }
9678
9679   if (DECL_P (expr))
9680     {
9681       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9682                                            scope);
9683       /* Remember that there was a reference to this entity.  */
9684       mark_used (expr);
9685     }
9686
9687   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9688     {
9689       if (complain & tf_error)
9690         qualified_name_lookup_error (scope,
9691                                      TREE_OPERAND (qualified_id, 1),
9692                                      expr);
9693       return error_mark_node;
9694     }
9695
9696   if (is_template)
9697     expr = lookup_template_function (expr, template_args);
9698
9699   if (expr == error_mark_node && complain & tf_error)
9700     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
9701                                  expr);
9702   else if (TYPE_P (scope))
9703     {
9704       expr = (adjust_result_of_qualified_name_lookup
9705               (expr, scope, current_class_type));
9706       expr = (finish_qualified_id_expr
9707               (scope, expr, done, address_p,
9708                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
9709                /*template_arg_p=*/false));
9710     }
9711
9712   /* Expressions do not generally have reference type.  */
9713   if (TREE_CODE (expr) != SCOPE_REF
9714       /* However, if we're about to form a pointer-to-member, we just
9715          want the referenced member referenced.  */
9716       && TREE_CODE (expr) != OFFSET_REF)
9717     expr = convert_from_reference (expr);
9718
9719   return expr;
9720 }
9721
9722 /* Like tsubst, but deals with expressions.  This function just replaces
9723    template parms; to finish processing the resultant expression, use
9724    tsubst_expr.  */
9725
9726 static tree
9727 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9728 {
9729   enum tree_code code;
9730   tree r;
9731
9732   if (t == NULL_TREE || t == error_mark_node)
9733     return t;
9734
9735   code = TREE_CODE (t);
9736
9737   switch (code)
9738     {
9739     case PARM_DECL:
9740       r = retrieve_local_specialization (t);
9741       gcc_assert (r != NULL);
9742       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
9743         r = ARGUMENT_PACK_SELECT_ARG (r);
9744       mark_used (r);
9745       return r;
9746
9747     case CONST_DECL:
9748       {
9749         tree enum_type;
9750         tree v;
9751
9752         if (DECL_TEMPLATE_PARM_P (t))
9753           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
9754         /* There is no need to substitute into namespace-scope
9755            enumerators.  */
9756         if (DECL_NAMESPACE_SCOPE_P (t))
9757           return t;
9758         /* If ARGS is NULL, then T is known to be non-dependent.  */
9759         if (args == NULL_TREE)
9760           return integral_constant_value (t);
9761
9762         /* Unfortunately, we cannot just call lookup_name here.
9763            Consider:
9764
9765              template <int I> int f() {
9766              enum E { a = I };
9767              struct S { void g() { E e = a; } };
9768              };
9769
9770            When we instantiate f<7>::S::g(), say, lookup_name is not
9771            clever enough to find f<7>::a.  */
9772         enum_type
9773           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
9774                               /*entering_scope=*/0);
9775
9776         for (v = TYPE_VALUES (enum_type);
9777              v != NULL_TREE;
9778              v = TREE_CHAIN (v))
9779           if (TREE_PURPOSE (v) == DECL_NAME (t))
9780             return TREE_VALUE (v);
9781
9782           /* We didn't find the name.  That should never happen; if
9783              name-lookup found it during preliminary parsing, we
9784              should find it again here during instantiation.  */
9785         gcc_unreachable ();
9786       }
9787       return t;
9788
9789     case FIELD_DECL:
9790       if (DECL_CONTEXT (t))
9791         {
9792           tree ctx;
9793
9794           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
9795                                   /*entering_scope=*/1);
9796           if (ctx != DECL_CONTEXT (t))
9797             {
9798               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
9799               if (!r)
9800                 {
9801                   if (complain & tf_error)
9802                     error ("using invalid field %qD", t);
9803                   return error_mark_node;
9804                 }
9805               return r;
9806             }
9807         }
9808
9809       return t;
9810
9811     case VAR_DECL:
9812     case FUNCTION_DECL:
9813       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9814           || local_variable_p (t))
9815         t = tsubst (t, args, complain, in_decl);
9816       mark_used (t);
9817       return t;
9818
9819     case BASELINK:
9820       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
9821
9822     case TEMPLATE_DECL:
9823       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9824         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
9825                        args, complain, in_decl);
9826       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
9827         return tsubst (t, args, complain, in_decl);
9828       else if (DECL_CLASS_SCOPE_P (t)
9829                && uses_template_parms (DECL_CONTEXT (t)))
9830         {
9831           /* Template template argument like the following example need
9832              special treatment:
9833
9834                template <template <class> class TT> struct C {};
9835                template <class T> struct D {
9836                  template <class U> struct E {};
9837                  C<E> c;                                // #1
9838                };
9839                D<int> d;                                // #2
9840
9841              We are processing the template argument `E' in #1 for
9842              the template instantiation #2.  Originally, `E' is a
9843              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
9844              have to substitute this with one having context `D<int>'.  */
9845
9846           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
9847           return lookup_field (context, DECL_NAME(t), 0, false);
9848         }
9849       else
9850         /* Ordinary template template argument.  */
9851         return t;
9852
9853     case CAST_EXPR:
9854     case REINTERPRET_CAST_EXPR:
9855     case CONST_CAST_EXPR:
9856     case STATIC_CAST_EXPR:
9857     case DYNAMIC_CAST_EXPR:
9858     case NOP_EXPR:
9859       return build1
9860         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9861          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9862
9863     case SIZEOF_EXPR:
9864       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
9865         {
9866           /* We only want to compute the number of arguments.  */
9867           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
9868                                                 complain, in_decl);
9869           if (expanded == error_mark_node)
9870             return error_mark_node;
9871           return build_int_cst (size_type_node, TREE_VEC_LENGTH (expanded));
9872         }
9873       /* Fall through */
9874
9875     case INDIRECT_REF:
9876     case NEGATE_EXPR:
9877     case TRUTH_NOT_EXPR:
9878     case BIT_NOT_EXPR:
9879     case ADDR_EXPR:
9880     case UNARY_PLUS_EXPR:      /* Unary + */
9881     case ALIGNOF_EXPR:
9882     case ARROW_EXPR:
9883     case THROW_EXPR:
9884     case TYPEID_EXPR:
9885     case REALPART_EXPR:
9886     case IMAGPART_EXPR:
9887       return build1
9888         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9889          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9890
9891     case COMPONENT_REF:
9892       {
9893         tree object;
9894         tree name;
9895
9896         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
9897         name = TREE_OPERAND (t, 1);
9898         if (TREE_CODE (name) == BIT_NOT_EXPR)
9899           {
9900             name = tsubst_copy (TREE_OPERAND (name, 0), args,
9901                                 complain, in_decl);
9902             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
9903           }
9904         else if (TREE_CODE (name) == SCOPE_REF
9905                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
9906           {
9907             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
9908                                      complain, in_decl);
9909             name = TREE_OPERAND (name, 1);
9910             name = tsubst_copy (TREE_OPERAND (name, 0), args,
9911                                 complain, in_decl);
9912             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
9913             name = build_qualified_name (/*type=*/NULL_TREE,
9914                                          base, name,
9915                                          /*template_p=*/false);
9916           }
9917         else if (TREE_CODE (name) == BASELINK)
9918           name = tsubst_baselink (name,
9919                                   non_reference (TREE_TYPE (object)),
9920                                   args, complain,
9921                                   in_decl);
9922         else
9923           name = tsubst_copy (name, args, complain, in_decl);
9924         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
9925       }
9926
9927     case PLUS_EXPR:
9928     case MINUS_EXPR:
9929     case MULT_EXPR:
9930     case TRUNC_DIV_EXPR:
9931     case CEIL_DIV_EXPR:
9932     case FLOOR_DIV_EXPR:
9933     case ROUND_DIV_EXPR:
9934     case EXACT_DIV_EXPR:
9935     case BIT_AND_EXPR:
9936     case BIT_IOR_EXPR:
9937     case BIT_XOR_EXPR:
9938     case TRUNC_MOD_EXPR:
9939     case FLOOR_MOD_EXPR:
9940     case TRUTH_ANDIF_EXPR:
9941     case TRUTH_ORIF_EXPR:
9942     case TRUTH_AND_EXPR:
9943     case TRUTH_OR_EXPR:
9944     case RSHIFT_EXPR:
9945     case LSHIFT_EXPR:
9946     case RROTATE_EXPR:
9947     case LROTATE_EXPR:
9948     case EQ_EXPR:
9949     case NE_EXPR:
9950     case MAX_EXPR:
9951     case MIN_EXPR:
9952     case LE_EXPR:
9953     case GE_EXPR:
9954     case LT_EXPR:
9955     case GT_EXPR:
9956     case COMPOUND_EXPR:
9957     case DOTSTAR_EXPR:
9958     case MEMBER_REF:
9959     case PREDECREMENT_EXPR:
9960     case PREINCREMENT_EXPR:
9961     case POSTDECREMENT_EXPR:
9962     case POSTINCREMENT_EXPR:
9963       return build_nt
9964         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9965          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
9966
9967     case SCOPE_REF:
9968       return build_qualified_name (/*type=*/NULL_TREE,
9969                                    tsubst_copy (TREE_OPERAND (t, 0),
9970                                                 args, complain, in_decl),
9971                                    tsubst_copy (TREE_OPERAND (t, 1),
9972                                                 args, complain, in_decl),
9973                                    QUALIFIED_NAME_IS_TEMPLATE (t));
9974
9975     case ARRAY_REF:
9976       return build_nt
9977         (ARRAY_REF,
9978          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9979          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
9980          NULL_TREE, NULL_TREE);
9981
9982     case CALL_EXPR:
9983       {
9984         int n = VL_EXP_OPERAND_LENGTH (t);
9985         tree result = build_vl_exp (CALL_EXPR, n);
9986         int i;
9987         for (i = 0; i < n; i++)
9988           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
9989                                              complain, in_decl);
9990         return result;
9991       }
9992
9993     case COND_EXPR:
9994     case MODOP_EXPR:
9995     case PSEUDO_DTOR_EXPR:
9996       {
9997         r = build_nt
9998           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9999            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10000            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10001         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10002         return r;
10003       }
10004
10005     case NEW_EXPR:
10006       {
10007         r = build_nt
10008         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10009          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10010          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10011         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10012         return r;
10013       }
10014
10015     case DELETE_EXPR:
10016       {
10017         r = build_nt
10018         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10019          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10020         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10021         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10022         return r;
10023       }
10024
10025     case TEMPLATE_ID_EXPR:
10026       {
10027         /* Substituted template arguments */
10028         tree fn = TREE_OPERAND (t, 0);
10029         tree targs = TREE_OPERAND (t, 1);
10030
10031         fn = tsubst_copy (fn, args, complain, in_decl);
10032         if (targs)
10033           targs = tsubst_template_args (targs, args, complain, in_decl);
10034
10035         return lookup_template_function (fn, targs);
10036       }
10037
10038     case TREE_LIST:
10039       {
10040         tree purpose, value, chain;
10041
10042         if (t == void_list_node)
10043           return t;
10044
10045         purpose = TREE_PURPOSE (t);
10046         if (purpose)
10047           purpose = tsubst_copy (purpose, args, complain, in_decl);
10048         value = TREE_VALUE (t);
10049         if (value)
10050           value = tsubst_copy (value, args, complain, in_decl);
10051         chain = TREE_CHAIN (t);
10052         if (chain && chain != void_type_node)
10053           chain = tsubst_copy (chain, args, complain, in_decl);
10054         if (purpose == TREE_PURPOSE (t)
10055             && value == TREE_VALUE (t)
10056             && chain == TREE_CHAIN (t))
10057           return t;
10058         return tree_cons (purpose, value, chain);
10059       }
10060
10061     case RECORD_TYPE:
10062     case UNION_TYPE:
10063     case ENUMERAL_TYPE:
10064     case INTEGER_TYPE:
10065     case TEMPLATE_TYPE_PARM:
10066     case TEMPLATE_TEMPLATE_PARM:
10067     case BOUND_TEMPLATE_TEMPLATE_PARM:
10068     case TEMPLATE_PARM_INDEX:
10069     case POINTER_TYPE:
10070     case REFERENCE_TYPE:
10071     case OFFSET_TYPE:
10072     case FUNCTION_TYPE:
10073     case METHOD_TYPE:
10074     case ARRAY_TYPE:
10075     case TYPENAME_TYPE:
10076     case UNBOUND_CLASS_TEMPLATE:
10077     case TYPEOF_TYPE:
10078     case DECLTYPE_TYPE:
10079     case TYPE_DECL:
10080       return tsubst (t, args, complain, in_decl);
10081
10082     case IDENTIFIER_NODE:
10083       if (IDENTIFIER_TYPENAME_P (t))
10084         {
10085           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10086           return mangle_conv_op_name_for_type (new_type);
10087         }
10088       else
10089         return t;
10090
10091     case CONSTRUCTOR:
10092       /* This is handled by tsubst_copy_and_build.  */
10093       gcc_unreachable ();
10094
10095     case VA_ARG_EXPR:
10096       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10097                                           in_decl),
10098                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10099
10100     case CLEANUP_POINT_EXPR:
10101       /* We shouldn't have built any of these during initial template
10102          generation.  Instead, they should be built during instantiation
10103          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10104       gcc_unreachable ();
10105
10106     case OFFSET_REF:
10107       mark_used (TREE_OPERAND (t, 1));
10108       return t;
10109
10110     case EXPR_PACK_EXPANSION:
10111       error ("invalid use of pack expansion expression");
10112       return error_mark_node;
10113
10114     case NONTYPE_ARGUMENT_PACK:
10115       error ("use %<...%> to expand argument pack");
10116       return error_mark_node;
10117
10118     default:
10119       return t;
10120     }
10121 }
10122
10123 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10124
10125 static tree
10126 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10127                     tree in_decl)
10128 {
10129   tree new_clauses = NULL, nc, oc;
10130
10131   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10132     {
10133       nc = copy_node (oc);
10134       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10135       new_clauses = nc;
10136
10137       switch (OMP_CLAUSE_CODE (nc))
10138         {
10139         case OMP_CLAUSE_PRIVATE:
10140         case OMP_CLAUSE_SHARED:
10141         case OMP_CLAUSE_FIRSTPRIVATE:
10142         case OMP_CLAUSE_LASTPRIVATE:
10143         case OMP_CLAUSE_REDUCTION:
10144         case OMP_CLAUSE_COPYIN:
10145         case OMP_CLAUSE_COPYPRIVATE:
10146         case OMP_CLAUSE_IF:
10147         case OMP_CLAUSE_NUM_THREADS:
10148         case OMP_CLAUSE_SCHEDULE:
10149           OMP_CLAUSE_OPERAND (nc, 0)
10150             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10151                            in_decl, /*integral_constant_expression_p=*/false);
10152           break;
10153         case OMP_CLAUSE_NOWAIT:
10154         case OMP_CLAUSE_ORDERED:
10155         case OMP_CLAUSE_DEFAULT:
10156           break;
10157         default:
10158           gcc_unreachable ();
10159         }
10160     }
10161
10162   return finish_omp_clauses (nreverse (new_clauses));
10163 }
10164
10165 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10166
10167 static tree
10168 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10169                           tree in_decl)
10170 {
10171 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10172
10173   tree purpose, value, chain;
10174
10175   if (t == NULL)
10176     return t;
10177
10178   if (TREE_CODE (t) != TREE_LIST)
10179     return tsubst_copy_and_build (t, args, complain, in_decl,
10180                                   /*function_p=*/false,
10181                                   /*integral_constant_expression_p=*/false);
10182
10183   if (t == void_list_node)
10184     return t;
10185
10186   purpose = TREE_PURPOSE (t);
10187   if (purpose)
10188     purpose = RECUR (purpose);
10189   value = TREE_VALUE (t);
10190   if (value)
10191     value = RECUR (value);
10192   chain = TREE_CHAIN (t);
10193   if (chain && chain != void_type_node)
10194     chain = RECUR (chain);
10195   return tree_cons (purpose, value, chain);
10196 #undef RECUR
10197 }
10198
10199 /* Like tsubst_copy for expressions, etc. but also does semantic
10200    processing.  */
10201
10202 static tree
10203 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10204              bool integral_constant_expression_p)
10205 {
10206 #define RECUR(NODE)                             \
10207   tsubst_expr ((NODE), args, complain, in_decl, \
10208                integral_constant_expression_p)
10209
10210   tree stmt, tmp;
10211
10212   if (t == NULL_TREE || t == error_mark_node)
10213     return t;
10214
10215   if (EXPR_HAS_LOCATION (t))
10216     input_location = EXPR_LOCATION (t);
10217   if (STATEMENT_CODE_P (TREE_CODE (t)))
10218     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10219
10220   switch (TREE_CODE (t))
10221     {
10222     case STATEMENT_LIST:
10223       {
10224         tree_stmt_iterator i;
10225         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10226           RECUR (tsi_stmt (i));
10227         break;
10228       }
10229
10230     case CTOR_INITIALIZER:
10231       finish_mem_initializers (tsubst_initializer_list
10232                                (TREE_OPERAND (t, 0), args));
10233       break;
10234
10235     case RETURN_EXPR:
10236       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10237       break;
10238
10239     case EXPR_STMT:
10240       tmp = RECUR (EXPR_STMT_EXPR (t));
10241       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10242         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10243       else
10244         finish_expr_stmt (tmp);
10245       break;
10246
10247     case USING_STMT:
10248       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10249       break;
10250
10251     case DECL_EXPR:
10252       {
10253         tree decl;
10254         tree init;
10255
10256         decl = DECL_EXPR_DECL (t);
10257         if (TREE_CODE (decl) == LABEL_DECL)
10258           finish_label_decl (DECL_NAME (decl));
10259         else if (TREE_CODE (decl) == USING_DECL)
10260           {
10261             tree scope = USING_DECL_SCOPE (decl);
10262             tree name = DECL_NAME (decl);
10263             tree decl;
10264
10265             scope = RECUR (scope);
10266             decl = lookup_qualified_name (scope, name,
10267                                           /*is_type_p=*/false,
10268                                           /*complain=*/false);
10269             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10270               qualified_name_lookup_error (scope, name, decl);
10271             else
10272               do_local_using_decl (decl, scope, name);
10273           }
10274         else
10275           {
10276             init = DECL_INITIAL (decl);
10277             decl = tsubst (decl, args, complain, in_decl);
10278             if (decl != error_mark_node)
10279               {
10280                 /* By marking the declaration as instantiated, we avoid
10281                    trying to instantiate it.  Since instantiate_decl can't
10282                    handle local variables, and since we've already done
10283                    all that needs to be done, that's the right thing to
10284                    do.  */
10285                 if (TREE_CODE (decl) == VAR_DECL)
10286                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10287                 if (TREE_CODE (decl) == VAR_DECL
10288                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10289                   /* Anonymous aggregates are a special case.  */
10290                   finish_anon_union (decl);
10291                 else
10292                   {
10293                     maybe_push_decl (decl);
10294                     if (TREE_CODE (decl) == VAR_DECL
10295                         && DECL_PRETTY_FUNCTION_P (decl))
10296                       {
10297                         /* For __PRETTY_FUNCTION__ we have to adjust the
10298                            initializer.  */
10299                         const char *const name
10300                           = cxx_printable_name (current_function_decl, 2);
10301                         init = cp_fname_init (name, &TREE_TYPE (decl));
10302                       }
10303                     else
10304                       {
10305                         tree t = RECUR (init);
10306
10307                         if (init && !t)
10308                           /* If we had an initializer but it
10309                              instantiated to nothing,
10310                              value-initialize the object.  This will
10311                              only occur when the initializer was a
10312                              pack expansion where the parameter packs
10313                              used in that expansion were of length
10314                              zero.  */
10315                           init = build_default_init (TREE_TYPE (decl),
10316                                                      NULL_TREE);
10317                         else
10318                           init = t;
10319                       }
10320
10321                     finish_decl (decl, init, NULL_TREE);
10322                   }
10323               }
10324           }
10325
10326         /* A DECL_EXPR can also be used as an expression, in the condition
10327            clause of an if/for/while construct.  */
10328         return decl;
10329       }
10330
10331     case FOR_STMT:
10332       stmt = begin_for_stmt ();
10333                           RECUR (FOR_INIT_STMT (t));
10334       finish_for_init_stmt (stmt);
10335       tmp = RECUR (FOR_COND (t));
10336       finish_for_cond (tmp, stmt);
10337       tmp = RECUR (FOR_EXPR (t));
10338       finish_for_expr (tmp, stmt);
10339       RECUR (FOR_BODY (t));
10340       finish_for_stmt (stmt);
10341       break;
10342
10343     case WHILE_STMT:
10344       stmt = begin_while_stmt ();
10345       tmp = RECUR (WHILE_COND (t));
10346       finish_while_stmt_cond (tmp, stmt);
10347       RECUR (WHILE_BODY (t));
10348       finish_while_stmt (stmt);
10349       break;
10350
10351     case DO_STMT:
10352       stmt = begin_do_stmt ();
10353       RECUR (DO_BODY (t));
10354       finish_do_body (stmt);
10355       tmp = RECUR (DO_COND (t));
10356       finish_do_stmt (tmp, stmt);
10357       break;
10358
10359     case IF_STMT:
10360       stmt = begin_if_stmt ();
10361       tmp = RECUR (IF_COND (t));
10362       finish_if_stmt_cond (tmp, stmt);
10363       RECUR (THEN_CLAUSE (t));
10364       finish_then_clause (stmt);
10365
10366       if (ELSE_CLAUSE (t))
10367         {
10368           begin_else_clause (stmt);
10369           RECUR (ELSE_CLAUSE (t));
10370           finish_else_clause (stmt);
10371         }
10372
10373       finish_if_stmt (stmt);
10374       break;
10375
10376     case BIND_EXPR:
10377       if (BIND_EXPR_BODY_BLOCK (t))
10378         stmt = begin_function_body ();
10379       else
10380         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10381                                     ? BCS_TRY_BLOCK : 0);
10382
10383       RECUR (BIND_EXPR_BODY (t));
10384
10385       if (BIND_EXPR_BODY_BLOCK (t))
10386         finish_function_body (stmt);
10387       else
10388         finish_compound_stmt (stmt);
10389       break;
10390
10391     case BREAK_STMT:
10392       finish_break_stmt ();
10393       break;
10394
10395     case CONTINUE_STMT:
10396       finish_continue_stmt ();
10397       break;
10398
10399     case SWITCH_STMT:
10400       stmt = begin_switch_stmt ();
10401       tmp = RECUR (SWITCH_STMT_COND (t));
10402       finish_switch_cond (tmp, stmt);
10403       RECUR (SWITCH_STMT_BODY (t));
10404       finish_switch_stmt (stmt);
10405       break;
10406
10407     case CASE_LABEL_EXPR:
10408       finish_case_label (RECUR (CASE_LOW (t)),
10409                          RECUR (CASE_HIGH (t)));
10410       break;
10411
10412     case LABEL_EXPR:
10413       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10414       break;
10415
10416     case GOTO_EXPR:
10417       tmp = GOTO_DESTINATION (t);
10418       if (TREE_CODE (tmp) != LABEL_DECL)
10419         /* Computed goto's must be tsubst'd into.  On the other hand,
10420            non-computed gotos must not be; the identifier in question
10421            will have no binding.  */
10422         tmp = RECUR (tmp);
10423       else
10424         tmp = DECL_NAME (tmp);
10425       finish_goto_stmt (tmp);
10426       break;
10427
10428     case ASM_EXPR:
10429       tmp = finish_asm_stmt
10430         (ASM_VOLATILE_P (t),
10431          RECUR (ASM_STRING (t)),
10432          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10433          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10434          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10435       {
10436         tree asm_expr = tmp;
10437         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10438           asm_expr = TREE_OPERAND (asm_expr, 0);
10439         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10440       }
10441       break;
10442
10443     case TRY_BLOCK:
10444       if (CLEANUP_P (t))
10445         {
10446           stmt = begin_try_block ();
10447           RECUR (TRY_STMTS (t));
10448           finish_cleanup_try_block (stmt);
10449           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10450         }
10451       else
10452         {
10453           tree compound_stmt = NULL_TREE;
10454
10455           if (FN_TRY_BLOCK_P (t))
10456             stmt = begin_function_try_block (&compound_stmt);
10457           else
10458             stmt = begin_try_block ();
10459
10460           RECUR (TRY_STMTS (t));
10461
10462           if (FN_TRY_BLOCK_P (t))
10463             finish_function_try_block (stmt);
10464           else
10465             finish_try_block (stmt);
10466
10467           RECUR (TRY_HANDLERS (t));
10468           if (FN_TRY_BLOCK_P (t))
10469             finish_function_handler_sequence (stmt, compound_stmt);
10470           else
10471             finish_handler_sequence (stmt);
10472         }
10473       break;
10474
10475     case HANDLER:
10476       {
10477         tree decl = HANDLER_PARMS (t);
10478
10479         if (decl)
10480           {
10481             decl = tsubst (decl, args, complain, in_decl);
10482             /* Prevent instantiate_decl from trying to instantiate
10483                this variable.  We've already done all that needs to be
10484                done.  */
10485             if (decl != error_mark_node)
10486               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10487           }
10488         stmt = begin_handler ();
10489         finish_handler_parms (decl, stmt);
10490         RECUR (HANDLER_BODY (t));
10491         finish_handler (stmt);
10492       }
10493       break;
10494
10495     case TAG_DEFN:
10496       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10497       break;
10498
10499     case STATIC_ASSERT:
10500       {
10501         tree condition = 
10502           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10503                        args,
10504                        complain, in_decl,
10505                        /*integral_constant_expression_p=*/true);
10506         finish_static_assert (condition,
10507                               STATIC_ASSERT_MESSAGE (t),
10508                               STATIC_ASSERT_SOURCE_LOCATION (t),
10509                               /*member_p=*/false);
10510       }
10511       break;
10512
10513     case OMP_PARALLEL:
10514       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
10515                                 args, complain, in_decl);
10516       stmt = begin_omp_parallel ();
10517       RECUR (OMP_PARALLEL_BODY (t));
10518       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
10519         = OMP_PARALLEL_COMBINED (t);
10520       break;
10521
10522     case OMP_FOR:
10523       {
10524         tree clauses, decl, init, cond, incr, body, pre_body;
10525
10526         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
10527                                       args, complain, in_decl);
10528         init = OMP_FOR_INIT (t);
10529         gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10530         decl = RECUR (TREE_OPERAND (init, 0));
10531         init = RECUR (TREE_OPERAND (init, 1));
10532         cond = RECUR (OMP_FOR_COND (t));
10533         incr = RECUR (OMP_FOR_INCR (t));
10534
10535         stmt = begin_omp_structured_block ();
10536
10537         pre_body = push_stmt_list ();
10538         RECUR (OMP_FOR_PRE_BODY (t));
10539         pre_body = pop_stmt_list (pre_body);
10540
10541         body = push_stmt_list ();
10542         RECUR (OMP_FOR_BODY (t));
10543         body = pop_stmt_list (body);
10544
10545         t = finish_omp_for (EXPR_LOCATION (t), decl, init, cond, incr, body,
10546                             pre_body);
10547         if (t)
10548           OMP_FOR_CLAUSES (t) = clauses;
10549
10550         add_stmt (finish_omp_structured_block (stmt));
10551       }
10552       break;
10553
10554     case OMP_SECTIONS:
10555     case OMP_SINGLE:
10556       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
10557       stmt = push_stmt_list ();
10558       RECUR (OMP_BODY (t));
10559       stmt = pop_stmt_list (stmt);
10560
10561       t = copy_node (t);
10562       OMP_BODY (t) = stmt;
10563       OMP_CLAUSES (t) = tmp;
10564       add_stmt (t);
10565       break;
10566
10567     case OMP_SECTION:
10568     case OMP_CRITICAL:
10569     case OMP_MASTER:
10570     case OMP_ORDERED:
10571       stmt = push_stmt_list ();
10572       RECUR (OMP_BODY (t));
10573       stmt = pop_stmt_list (stmt);
10574
10575       t = copy_node (t);
10576       OMP_BODY (t) = stmt;
10577       add_stmt (t);
10578       break;
10579
10580     case OMP_ATOMIC:
10581       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
10582       {
10583         tree op1 = TREE_OPERAND (t, 1);
10584         tree lhs = RECUR (TREE_OPERAND (op1, 0));
10585         tree rhs = RECUR (TREE_OPERAND (op1, 1));
10586         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
10587       }
10588       break;
10589
10590     case EXPR_PACK_EXPANSION:
10591       error ("invalid use of pack expansion expression");
10592       return error_mark_node;
10593
10594     case NONTYPE_ARGUMENT_PACK:
10595       error ("use %<...%> to expand argument pack");
10596       return error_mark_node;
10597
10598     default:
10599       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
10600
10601       return tsubst_copy_and_build (t, args, complain, in_decl,
10602                                     /*function_p=*/false,
10603                                     integral_constant_expression_p);
10604     }
10605
10606   return NULL_TREE;
10607 #undef RECUR
10608 }
10609
10610 /* T is a postfix-expression that is not being used in a function
10611    call.  Return the substituted version of T.  */
10612
10613 static tree
10614 tsubst_non_call_postfix_expression (tree t, tree args,
10615                                     tsubst_flags_t complain,
10616                                     tree in_decl)
10617 {
10618   if (TREE_CODE (t) == SCOPE_REF)
10619     t = tsubst_qualified_id (t, args, complain, in_decl,
10620                              /*done=*/false, /*address_p=*/false);
10621   else
10622     t = tsubst_copy_and_build (t, args, complain, in_decl,
10623                                /*function_p=*/false,
10624                                /*integral_constant_expression_p=*/false);
10625
10626   return t;
10627 }
10628
10629 /* Like tsubst but deals with expressions and performs semantic
10630    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
10631
10632 tree
10633 tsubst_copy_and_build (tree t,
10634                        tree args,
10635                        tsubst_flags_t complain,
10636                        tree in_decl,
10637                        bool function_p,
10638                        bool integral_constant_expression_p)
10639 {
10640 #define RECUR(NODE)                                             \
10641   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
10642                          /*function_p=*/false,                  \
10643                          integral_constant_expression_p)
10644
10645   tree op1;
10646
10647   if (t == NULL_TREE || t == error_mark_node)
10648     return t;
10649
10650   switch (TREE_CODE (t))
10651     {
10652     case USING_DECL:
10653       t = DECL_NAME (t);
10654       /* Fall through.  */
10655     case IDENTIFIER_NODE:
10656       {
10657         tree decl;
10658         cp_id_kind idk;
10659         bool non_integral_constant_expression_p;
10660         const char *error_msg;
10661
10662         if (IDENTIFIER_TYPENAME_P (t))
10663           {
10664             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10665             t = mangle_conv_op_name_for_type (new_type);
10666           }
10667
10668         /* Look up the name.  */
10669         decl = lookup_name (t);
10670
10671         /* By convention, expressions use ERROR_MARK_NODE to indicate
10672            failure, not NULL_TREE.  */
10673         if (decl == NULL_TREE)
10674           decl = error_mark_node;
10675
10676         decl = finish_id_expression (t, decl, NULL_TREE,
10677                                      &idk,
10678                                      integral_constant_expression_p,
10679                                      /*allow_non_integral_constant_expression_p=*/false,
10680                                      &non_integral_constant_expression_p,
10681                                      /*template_p=*/false,
10682                                      /*done=*/true,
10683                                      /*address_p=*/false,
10684                                      /*template_arg_p=*/false,
10685                                      &error_msg);
10686         if (error_msg)
10687           error (error_msg);
10688         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
10689           decl = unqualified_name_lookup_error (decl);
10690         return decl;
10691       }
10692
10693     case TEMPLATE_ID_EXPR:
10694       {
10695         tree object;
10696         tree template = RECUR (TREE_OPERAND (t, 0));
10697         tree targs = TREE_OPERAND (t, 1);
10698
10699         if (targs)
10700           targs = tsubst_template_args (targs, args, complain, in_decl);
10701
10702         if (TREE_CODE (template) == COMPONENT_REF)
10703           {
10704             object = TREE_OPERAND (template, 0);
10705             template = TREE_OPERAND (template, 1);
10706           }
10707         else
10708           object = NULL_TREE;
10709         template = lookup_template_function (template, targs);
10710
10711         if (object)
10712           return build3 (COMPONENT_REF, TREE_TYPE (template),
10713                          object, template, NULL_TREE);
10714         else
10715           return baselink_for_fns (template);
10716       }
10717
10718     case INDIRECT_REF:
10719       {
10720         tree r = RECUR (TREE_OPERAND (t, 0));
10721
10722         if (REFERENCE_REF_P (t))
10723           {
10724             /* A type conversion to reference type will be enclosed in
10725                such an indirect ref, but the substitution of the cast
10726                will have also added such an indirect ref.  */
10727             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
10728               r = convert_from_reference (r);
10729           }
10730         else
10731           r = build_x_indirect_ref (r, "unary *");
10732         return r;
10733       }
10734
10735     case NOP_EXPR:
10736       return build_nop
10737         (tsubst (TREE_TYPE (t), args, complain, in_decl),
10738          RECUR (TREE_OPERAND (t, 0)));
10739
10740     case CAST_EXPR:
10741     case REINTERPRET_CAST_EXPR:
10742     case CONST_CAST_EXPR:
10743     case DYNAMIC_CAST_EXPR:
10744     case STATIC_CAST_EXPR:
10745       {
10746         tree type;
10747         tree op;
10748
10749         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10750         if (integral_constant_expression_p
10751             && !cast_valid_in_integral_constant_expression_p (type))
10752           {
10753             error ("a cast to a type other than an integral or "
10754                    "enumeration type cannot appear in a constant-expression");
10755             return error_mark_node; 
10756           }
10757
10758         op = RECUR (TREE_OPERAND (t, 0));
10759
10760         switch (TREE_CODE (t))
10761           {
10762           case CAST_EXPR:
10763             return build_functional_cast (type, op);
10764           case REINTERPRET_CAST_EXPR:
10765             return build_reinterpret_cast (type, op);
10766           case CONST_CAST_EXPR:
10767             return build_const_cast (type, op);
10768           case DYNAMIC_CAST_EXPR:
10769             return build_dynamic_cast (type, op);
10770           case STATIC_CAST_EXPR:
10771             return build_static_cast (type, op);
10772           default:
10773             gcc_unreachable ();
10774           }
10775       }
10776
10777     case POSTDECREMENT_EXPR:
10778     case POSTINCREMENT_EXPR:
10779       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10780                                                 args, complain, in_decl);
10781       return build_x_unary_op (TREE_CODE (t), op1);
10782
10783     case PREDECREMENT_EXPR:
10784     case PREINCREMENT_EXPR:
10785     case NEGATE_EXPR:
10786     case BIT_NOT_EXPR:
10787     case ABS_EXPR:
10788     case TRUTH_NOT_EXPR:
10789     case UNARY_PLUS_EXPR:  /* Unary + */
10790     case REALPART_EXPR:
10791     case IMAGPART_EXPR:
10792       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)));
10793
10794     case ADDR_EXPR:
10795       op1 = TREE_OPERAND (t, 0);
10796       if (TREE_CODE (op1) == SCOPE_REF)
10797         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
10798                                    /*done=*/true, /*address_p=*/true);
10799       else
10800         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
10801                                                   in_decl);
10802       if (TREE_CODE (op1) == LABEL_DECL)
10803         return finish_label_address_expr (DECL_NAME (op1));
10804       return build_x_unary_op (ADDR_EXPR, op1);
10805
10806     case PLUS_EXPR:
10807     case MINUS_EXPR:
10808     case MULT_EXPR:
10809     case TRUNC_DIV_EXPR:
10810     case CEIL_DIV_EXPR:
10811     case FLOOR_DIV_EXPR:
10812     case ROUND_DIV_EXPR:
10813     case EXACT_DIV_EXPR:
10814     case BIT_AND_EXPR:
10815     case BIT_IOR_EXPR:
10816     case BIT_XOR_EXPR:
10817     case TRUNC_MOD_EXPR:
10818     case FLOOR_MOD_EXPR:
10819     case TRUTH_ANDIF_EXPR:
10820     case TRUTH_ORIF_EXPR:
10821     case TRUTH_AND_EXPR:
10822     case TRUTH_OR_EXPR:
10823     case RSHIFT_EXPR:
10824     case LSHIFT_EXPR:
10825     case RROTATE_EXPR:
10826     case LROTATE_EXPR:
10827     case EQ_EXPR:
10828     case NE_EXPR:
10829     case MAX_EXPR:
10830     case MIN_EXPR:
10831     case LE_EXPR:
10832     case GE_EXPR:
10833     case LT_EXPR:
10834     case GT_EXPR:
10835     case MEMBER_REF:
10836     case DOTSTAR_EXPR:
10837       return build_x_binary_op
10838         (TREE_CODE (t),
10839          RECUR (TREE_OPERAND (t, 0)),
10840          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
10841           ? ERROR_MARK
10842           : TREE_CODE (TREE_OPERAND (t, 0))),
10843          RECUR (TREE_OPERAND (t, 1)),
10844          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
10845           ? ERROR_MARK
10846           : TREE_CODE (TREE_OPERAND (t, 1))),
10847          /*overloaded_p=*/NULL);
10848
10849     case SCOPE_REF:
10850       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
10851                                   /*address_p=*/false);
10852     case ARRAY_REF:
10853       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10854                                                 args, complain, in_decl);
10855       return build_x_binary_op (ARRAY_REF, op1,
10856                                 (TREE_NO_WARNING (TREE_OPERAND (t, 0))
10857                                  ? ERROR_MARK
10858                                  : TREE_CODE (TREE_OPERAND (t, 0))),
10859                                 RECUR (TREE_OPERAND (t, 1)),
10860                                 (TREE_NO_WARNING (TREE_OPERAND (t, 1))
10861                                  ? ERROR_MARK
10862                                  : TREE_CODE (TREE_OPERAND (t, 1))),
10863                                 /*overloaded_p=*/NULL);
10864
10865     case SIZEOF_EXPR:
10866       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10867         {
10868           /* We only want to compute the number of arguments.  */
10869           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10870                                                 complain, in_decl);
10871           if (expanded == error_mark_node)
10872             return error_mark_node;
10873           return build_int_cst (size_type_node, TREE_VEC_LENGTH (expanded));
10874         }
10875       /* Fall through */
10876       
10877     case ALIGNOF_EXPR:
10878       op1 = TREE_OPERAND (t, 0);
10879       if (!args)
10880         {
10881           /* When there are no ARGS, we are trying to evaluate a
10882              non-dependent expression from the parser.  Trying to do
10883              the substitutions may not work.  */
10884           if (!TYPE_P (op1))
10885             op1 = TREE_TYPE (op1);
10886         }
10887       else
10888         {
10889           ++skip_evaluation;
10890           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
10891                                        /*function_p=*/false,
10892                                        /*integral_constant_expression_p=*/false);
10893           --skip_evaluation;
10894         }
10895       if (TYPE_P (op1))
10896         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), true);
10897       else
10898         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t));
10899
10900     case MODOP_EXPR:
10901       {
10902         tree r = build_x_modify_expr
10903           (RECUR (TREE_OPERAND (t, 0)),
10904            TREE_CODE (TREE_OPERAND (t, 1)),
10905            RECUR (TREE_OPERAND (t, 2)));
10906         /* TREE_NO_WARNING must be set if either the expression was
10907            parenthesized or it uses an operator such as >>= rather
10908            than plain assignment.  In the former case, it was already
10909            set and must be copied.  In the latter case,
10910            build_x_modify_expr sets it and it must not be reset
10911            here.  */
10912         if (TREE_NO_WARNING (t))
10913           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10914         return r;
10915       }
10916
10917     case ARROW_EXPR:
10918       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10919                                                 args, complain, in_decl);
10920       /* Remember that there was a reference to this entity.  */
10921       if (DECL_P (op1))
10922         mark_used (op1);
10923       return build_x_arrow (op1);
10924
10925     case NEW_EXPR:
10926       {
10927         tree init = RECUR (TREE_OPERAND (t, 3));
10928
10929         if (TREE_OPERAND (t, 3) && !init)
10930           /* If there was an initializer in the the original tree, but
10931              it instantiated to an empty list, then we should pass on
10932              VOID_ZERO_NODE to tell build_new that it was an empty
10933              initializer () rather than no initializer.  This can only
10934              happen when the initializer is a pack expansion whose
10935              parameter packs are of length zero.  */
10936           init = void_zero_node;
10937
10938         return build_new
10939           (RECUR (TREE_OPERAND (t, 0)),
10940            RECUR (TREE_OPERAND (t, 1)),
10941            RECUR (TREE_OPERAND (t, 2)),
10942            init,
10943            NEW_EXPR_USE_GLOBAL (t));
10944       }
10945
10946     case DELETE_EXPR:
10947      return delete_sanity
10948        (RECUR (TREE_OPERAND (t, 0)),
10949         RECUR (TREE_OPERAND (t, 1)),
10950         DELETE_EXPR_USE_VEC (t),
10951         DELETE_EXPR_USE_GLOBAL (t));
10952
10953     case COMPOUND_EXPR:
10954       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
10955                                     RECUR (TREE_OPERAND (t, 1)));
10956
10957     case CALL_EXPR:
10958       {
10959         tree function;
10960         tree call_args;
10961         bool qualified_p;
10962         bool koenig_p;
10963
10964         function = CALL_EXPR_FN (t);
10965         /* When we parsed the expression,  we determined whether or
10966            not Koenig lookup should be performed.  */
10967         koenig_p = KOENIG_LOOKUP_P (t);
10968         if (TREE_CODE (function) == SCOPE_REF)
10969           {
10970             qualified_p = true;
10971             function = tsubst_qualified_id (function, args, complain, in_decl,
10972                                             /*done=*/false,
10973                                             /*address_p=*/false);
10974           }
10975         else
10976           {
10977             if (TREE_CODE (function) == COMPONENT_REF)
10978               {
10979                 tree op = TREE_OPERAND (function, 1);
10980
10981                 qualified_p = (TREE_CODE (op) == SCOPE_REF
10982                                || (BASELINK_P (op)
10983                                    && BASELINK_QUALIFIED_P (op)));
10984               }
10985             else
10986               qualified_p = false;
10987
10988             function = tsubst_copy_and_build (function, args, complain,
10989                                               in_decl,
10990                                               !qualified_p,
10991                                               integral_constant_expression_p);
10992
10993             if (BASELINK_P (function))
10994               qualified_p = true;
10995           }
10996
10997         /* FIXME:  Rewrite this so as not to construct an arglist.  */
10998         call_args = RECUR (CALL_EXPR_ARGS (t));
10999
11000         /* We do not perform argument-dependent lookup if normal
11001            lookup finds a non-function, in accordance with the
11002            expected resolution of DR 218.  */
11003         if (koenig_p
11004             && ((is_overloaded_fn (function)
11005                  /* If lookup found a member function, the Koenig lookup is
11006                     not appropriate, even if an unqualified-name was used
11007                     to denote the function.  */
11008                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11009                 || TREE_CODE (function) == IDENTIFIER_NODE))
11010           function = perform_koenig_lookup (function, call_args);
11011
11012         if (TREE_CODE (function) == IDENTIFIER_NODE)
11013           {
11014             unqualified_name_lookup_error (function);
11015             return error_mark_node;
11016           }
11017
11018         /* Remember that there was a reference to this entity.  */
11019         if (DECL_P (function))
11020           mark_used (function);
11021
11022         if (TREE_CODE (function) == OFFSET_REF)
11023           return build_offset_ref_call_from_tree (function, call_args);
11024         if (TREE_CODE (function) == COMPONENT_REF)
11025           {
11026             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11027               return finish_call_expr (function, call_args,
11028                                        /*disallow_virtual=*/false,
11029                                        /*koenig_p=*/false);
11030             else
11031               return (build_new_method_call
11032                       (TREE_OPERAND (function, 0),
11033                        TREE_OPERAND (function, 1),
11034                        call_args, NULL_TREE,
11035                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11036                        /*fn_p=*/NULL));
11037           }
11038         return finish_call_expr (function, call_args,
11039                                  /*disallow_virtual=*/qualified_p,
11040                                  koenig_p);
11041       }
11042
11043     case COND_EXPR:
11044       return build_x_conditional_expr
11045         (RECUR (TREE_OPERAND (t, 0)),
11046          RECUR (TREE_OPERAND (t, 1)),
11047          RECUR (TREE_OPERAND (t, 2)));
11048
11049     case PSEUDO_DTOR_EXPR:
11050       return finish_pseudo_destructor_expr
11051         (RECUR (TREE_OPERAND (t, 0)),
11052          RECUR (TREE_OPERAND (t, 1)),
11053          RECUR (TREE_OPERAND (t, 2)));
11054
11055     case TREE_LIST:
11056       {
11057         tree purpose, value, chain;
11058
11059         if (t == void_list_node)
11060           return t;
11061
11062         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11063             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11064           {
11065             /* We have pack expansions, so expand those and
11066                create a new list out of it.  */
11067             tree purposevec = NULL_TREE;
11068             tree valuevec = NULL_TREE;
11069             tree chain;
11070             int i, len = -1;
11071
11072             /* Expand the argument expressions.  */
11073             if (TREE_PURPOSE (t))
11074               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11075                                                  complain, in_decl);
11076             if (TREE_VALUE (t))
11077               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11078                                                complain, in_decl);
11079
11080             /* Build the rest of the list.  */
11081             chain = TREE_CHAIN (t);
11082             if (chain && chain != void_type_node)
11083               chain = RECUR (chain);
11084
11085             /* Determine the number of arguments.  */
11086             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11087               {
11088                 len = TREE_VEC_LENGTH (purposevec);
11089                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11090               }
11091             else if (TREE_CODE (valuevec) == TREE_VEC)
11092               len = TREE_VEC_LENGTH (valuevec);
11093             else
11094               {
11095                 /* Since we only performed a partial substitution into
11096                    the argument pack, we only return a single list
11097                    node.  */
11098                 if (purposevec == TREE_PURPOSE (t)
11099                     && valuevec == TREE_VALUE (t)
11100                     && chain == TREE_CHAIN (t))
11101                   return t;
11102
11103                 return tree_cons (purposevec, valuevec, chain);
11104               }
11105             
11106             /* Convert the argument vectors into a TREE_LIST */
11107             i = len;
11108             while (i > 0)
11109               {
11110                 /* Grab the Ith values.  */
11111                 i--;
11112                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11113                                      : NULL_TREE;
11114                 value 
11115                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11116                              : NULL_TREE;
11117
11118                 /* Build the list (backwards).  */
11119                 chain = tree_cons (purpose, value, chain);
11120               }
11121
11122             return chain;
11123           }
11124
11125         purpose = TREE_PURPOSE (t);
11126         if (purpose)
11127           purpose = RECUR (purpose);
11128         value = TREE_VALUE (t);
11129         if (value)
11130           value = RECUR (value);
11131         chain = TREE_CHAIN (t);
11132         if (chain && chain != void_type_node)
11133           chain = RECUR (chain);
11134         if (purpose == TREE_PURPOSE (t)
11135             && value == TREE_VALUE (t)
11136             && chain == TREE_CHAIN (t))
11137           return t;
11138         return tree_cons (purpose, value, chain);
11139       }
11140
11141     case COMPONENT_REF:
11142       {
11143         tree object;
11144         tree object_type;
11145         tree member;
11146
11147         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11148                                                      args, complain, in_decl);
11149         /* Remember that there was a reference to this entity.  */
11150         if (DECL_P (object))
11151           mark_used (object);
11152         object_type = TREE_TYPE (object);
11153
11154         member = TREE_OPERAND (t, 1);
11155         if (BASELINK_P (member))
11156           member = tsubst_baselink (member,
11157                                     non_reference (TREE_TYPE (object)),
11158                                     args, complain, in_decl);
11159         else
11160           member = tsubst_copy (member, args, complain, in_decl);
11161         if (member == error_mark_node)
11162           return error_mark_node;
11163
11164         if (object_type && !CLASS_TYPE_P (object_type))
11165           {
11166             if (SCALAR_TYPE_P (object_type))
11167               {
11168                 tree s = NULL_TREE;
11169                 tree dtor = member;
11170
11171                 if (TREE_CODE (dtor) == SCOPE_REF)
11172                   {
11173                     s = TREE_OPERAND (dtor, 0);
11174                     dtor = TREE_OPERAND (dtor, 1);
11175                   }
11176                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11177                   {
11178                     dtor = TREE_OPERAND (dtor, 0);
11179                     if (TYPE_P (dtor))
11180                       return finish_pseudo_destructor_expr (object, s, dtor);
11181                   }
11182               }
11183           }
11184         else if (TREE_CODE (member) == SCOPE_REF
11185                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11186           {
11187             tree tmpl;
11188             tree args;
11189
11190             /* Lookup the template functions now that we know what the
11191                scope is.  */
11192             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11193             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11194             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11195                                             /*is_type_p=*/false,
11196                                             /*complain=*/false);
11197             if (BASELINK_P (member))
11198               {
11199                 BASELINK_FUNCTIONS (member)
11200                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11201                               args);
11202                 member = (adjust_result_of_qualified_name_lookup
11203                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11204                            object_type));
11205               }
11206             else
11207               {
11208                 qualified_name_lookup_error (object_type, tmpl, member);
11209                 return error_mark_node;
11210               }
11211           }
11212         else if (TREE_CODE (member) == SCOPE_REF
11213                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11214                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11215           {
11216             if (complain & tf_error)
11217               {
11218                 if (TYPE_P (TREE_OPERAND (member, 0)))
11219                   error ("%qT is not a class or namespace",
11220                          TREE_OPERAND (member, 0));
11221                 else
11222                   error ("%qD is not a class or namespace",
11223                          TREE_OPERAND (member, 0));
11224               }
11225             return error_mark_node;
11226           }
11227         else if (TREE_CODE (member) == FIELD_DECL)
11228           return finish_non_static_data_member (member, object, NULL_TREE);
11229
11230         return finish_class_member_access_expr (object, member,
11231                                                 /*template_p=*/false);
11232       }
11233
11234     case THROW_EXPR:
11235       return build_throw
11236         (RECUR (TREE_OPERAND (t, 0)));
11237
11238     case CONSTRUCTOR:
11239       {
11240         VEC(constructor_elt,gc) *n;
11241         constructor_elt *ce;
11242         unsigned HOST_WIDE_INT idx;
11243         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11244         bool process_index_p;
11245         int newlen;
11246         bool need_copy_p = false;
11247
11248         if (type == error_mark_node)
11249           return error_mark_node;
11250
11251         /* digest_init will do the wrong thing if we let it.  */
11252         if (type && TYPE_PTRMEMFUNC_P (type))
11253           return t;
11254
11255         /* We do not want to process the index of aggregate
11256            initializers as they are identifier nodes which will be
11257            looked up by digest_init.  */
11258         process_index_p = !(type && IS_AGGR_TYPE (type));
11259
11260         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11261         newlen = VEC_length (constructor_elt, n);
11262         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11263           {
11264             if (ce->index && process_index_p)
11265               ce->index = RECUR (ce->index);
11266
11267             if (PACK_EXPANSION_P (ce->value))
11268               {
11269                 /* Substitute into the pack expansion.  */
11270                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11271                                                   in_decl);
11272
11273                 if (ce->value == error_mark_node)
11274                   ;
11275                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11276                   /* Just move the argument into place.  */
11277                   ce->value = TREE_VEC_ELT (ce->value, 0);
11278                 else
11279                   {
11280                     /* Update the length of the final CONSTRUCTOR
11281                        arguments vector, and note that we will need to
11282                        copy.*/
11283                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11284                     need_copy_p = true;
11285                   }
11286               }
11287             else
11288               ce->value = RECUR (ce->value);
11289           }
11290
11291         if (need_copy_p)
11292           {
11293             VEC(constructor_elt,gc) *old_n = n;
11294
11295             n = VEC_alloc (constructor_elt, gc, newlen);
11296             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11297                  idx++)
11298               {
11299                 if (TREE_CODE (ce->value) == TREE_VEC)
11300                   {
11301                     int i, len = TREE_VEC_LENGTH (ce->value);
11302                     for (i = 0; i < len; ++i)
11303                       CONSTRUCTOR_APPEND_ELT (n, 0,
11304                                               TREE_VEC_ELT (ce->value, i));
11305                   }
11306                 else
11307                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11308               }
11309           }
11310
11311         if (TREE_HAS_CONSTRUCTOR (t))
11312           return finish_compound_literal (type, n);
11313
11314         return build_constructor (NULL_TREE, n);
11315       }
11316
11317     case TYPEID_EXPR:
11318       {
11319         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11320         if (TYPE_P (operand_0))
11321           return get_typeid (operand_0);
11322         return build_typeid (operand_0);
11323       }
11324
11325     case VAR_DECL:
11326       if (!args)
11327         return t;
11328       /* Fall through */
11329
11330     case PARM_DECL:
11331       {
11332         tree r = tsubst_copy (t, args, complain, in_decl);
11333
11334         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11335           /* If the original type was a reference, we'll be wrapped in
11336              the appropriate INDIRECT_REF.  */
11337           r = convert_from_reference (r);
11338         return r;
11339       }
11340
11341     case VA_ARG_EXPR:
11342       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11343                              tsubst_copy (TREE_TYPE (t), args, complain,
11344                                           in_decl));
11345
11346     case OFFSETOF_EXPR:
11347       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11348
11349     case TRAIT_EXPR:
11350       {
11351         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11352                                   complain, in_decl);
11353
11354         tree type2 = TRAIT_EXPR_TYPE2 (t);
11355         if (type2)
11356           type2 = tsubst_copy (type2, args, complain, in_decl);
11357         
11358         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11359       }
11360
11361     case STMT_EXPR:
11362       {
11363         tree old_stmt_expr = cur_stmt_expr;
11364         tree stmt_expr = begin_stmt_expr ();
11365
11366         cur_stmt_expr = stmt_expr;
11367         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11368                      integral_constant_expression_p);
11369         stmt_expr = finish_stmt_expr (stmt_expr, false);
11370         cur_stmt_expr = old_stmt_expr;
11371
11372         return stmt_expr;
11373       }
11374
11375     case CONST_DECL:
11376       t = tsubst_copy (t, args, complain, in_decl);
11377       /* As in finish_id_expression, we resolve enumeration constants
11378          to their underlying values.  */
11379       if (TREE_CODE (t) == CONST_DECL)
11380         {
11381           used_types_insert (TREE_TYPE (t));
11382           return DECL_INITIAL (t);
11383         }
11384       return t;
11385
11386     default:
11387       /* Handle Objective-C++ constructs, if appropriate.  */
11388       {
11389         tree subst
11390           = objcp_tsubst_copy_and_build (t, args, complain,
11391                                          in_decl, /*function_p=*/false);
11392         if (subst)
11393           return subst;
11394       }
11395       return tsubst_copy (t, args, complain, in_decl);
11396     }
11397
11398 #undef RECUR
11399 }
11400
11401 /* Verify that the instantiated ARGS are valid. For type arguments,
11402    make sure that the type's linkage is ok. For non-type arguments,
11403    make sure they are constants if they are integral or enumerations.
11404    Emit an error under control of COMPLAIN, and return TRUE on error.  */
11405
11406 static bool
11407 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
11408 {
11409   int ix, len = DECL_NTPARMS (tmpl);
11410   bool result = false;
11411
11412   for (ix = 0; ix != len; ix++)
11413     {
11414       tree t = TREE_VEC_ELT (args, ix);
11415
11416       if (TYPE_P (t))
11417         {
11418           /* [basic.link]: A name with no linkage (notably, the name
11419              of a class or enumeration declared in a local scope)
11420              shall not be used to declare an entity with linkage.
11421              This implies that names with no linkage cannot be used as
11422              template arguments.  */
11423           tree nt = no_linkage_check (t, /*relaxed_p=*/false);
11424
11425           if (nt)
11426             {
11427               /* DR 488 makes use of a type with no linkage cause
11428                  type deduction to fail.  */
11429               if (complain & tf_error)
11430                 {
11431                   if (TYPE_ANONYMOUS_P (nt))
11432                     error ("%qT is/uses anonymous type", t);
11433                   else
11434                     error ("template argument for %qD uses local type %qT",
11435                            tmpl, t);
11436                 }
11437               result = true;
11438             }
11439           /* In order to avoid all sorts of complications, we do not
11440              allow variably-modified types as template arguments.  */
11441           else if (variably_modified_type_p (t, NULL_TREE))
11442             {
11443               if (complain & tf_error)
11444                 error ("%qT is a variably modified type", t);
11445               result = true;
11446             }
11447         }
11448       /* A non-type argument of integral or enumerated type must be a
11449          constant.  */
11450       else if (TREE_TYPE (t)
11451                && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
11452                && !TREE_CONSTANT (t))
11453         {
11454           if (complain & tf_error)
11455             error ("integral expression %qE is not constant", t);
11456           result = true;
11457         }
11458     }
11459   if (result && (complain & tf_error))
11460     error ("  trying to instantiate %qD", tmpl);
11461   return result;
11462 }
11463
11464 /* Instantiate the indicated variable or function template TMPL with
11465    the template arguments in TARG_PTR.  */
11466
11467 tree
11468 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
11469 {
11470   tree fndecl;
11471   tree gen_tmpl;
11472   tree spec;
11473   HOST_WIDE_INT saved_processing_template_decl;
11474
11475   if (tmpl == error_mark_node)
11476     return error_mark_node;
11477
11478   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
11479
11480   /* If this function is a clone, handle it specially.  */
11481   if (DECL_CLONED_FUNCTION_P (tmpl))
11482     {
11483       tree spec;
11484       tree clone;
11485
11486       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
11487                                    complain);
11488       if (spec == error_mark_node)
11489         return error_mark_node;
11490
11491       /* Look for the clone.  */
11492       FOR_EACH_CLONE (clone, spec)
11493         if (DECL_NAME (clone) == DECL_NAME (tmpl))
11494           return clone;
11495       /* We should always have found the clone by now.  */
11496       gcc_unreachable ();
11497       return NULL_TREE;
11498     }
11499
11500   /* Check to see if we already have this specialization.  */
11501   spec = retrieve_specialization (tmpl, targ_ptr,
11502                                   /*class_specializations_p=*/false);
11503   if (spec != NULL_TREE)
11504     return spec;
11505
11506   gen_tmpl = most_general_template (tmpl);
11507   if (tmpl != gen_tmpl)
11508     {
11509       /* The TMPL is a partial instantiation.  To get a full set of
11510          arguments we must add the arguments used to perform the
11511          partial instantiation.  */
11512       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
11513                                               targ_ptr);
11514
11515       /* Check to see if we already have this specialization.  */
11516       spec = retrieve_specialization (gen_tmpl, targ_ptr,
11517                                       /*class_specializations_p=*/false);
11518       if (spec != NULL_TREE)
11519         return spec;
11520     }
11521
11522   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
11523                                complain))
11524     return error_mark_node;
11525
11526   /* We are building a FUNCTION_DECL, during which the access of its
11527      parameters and return types have to be checked.  However this
11528      FUNCTION_DECL which is the desired context for access checking
11529      is not built yet.  We solve this chicken-and-egg problem by
11530      deferring all checks until we have the FUNCTION_DECL.  */
11531   push_deferring_access_checks (dk_deferred);
11532
11533   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
11534      (because, for example, we have encountered a non-dependent
11535      function call in the body of a template function and must now
11536      determine which of several overloaded functions will be called),
11537      within the instantiation itself we are not processing a
11538      template.  */  
11539   saved_processing_template_decl = processing_template_decl;
11540   processing_template_decl = 0;
11541   /* Substitute template parameters to obtain the specialization.  */
11542   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
11543                    targ_ptr, complain, gen_tmpl);
11544   processing_template_decl = saved_processing_template_decl;
11545   if (fndecl == error_mark_node)
11546     return error_mark_node;
11547
11548   /* Now we know the specialization, compute access previously
11549      deferred.  */
11550   push_access_scope (fndecl);
11551   perform_deferred_access_checks ();
11552   pop_access_scope (fndecl);
11553   pop_deferring_access_checks ();
11554
11555   /* The DECL_TI_TEMPLATE should always be the immediate parent
11556      template, not the most general template.  */
11557   DECL_TI_TEMPLATE (fndecl) = tmpl;
11558
11559   /* If we've just instantiated the main entry point for a function,
11560      instantiate all the alternate entry points as well.  We do this
11561      by cloning the instantiation of the main entry point, not by
11562      instantiating the template clones.  */
11563   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
11564     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
11565
11566   return fndecl;
11567 }
11568
11569 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
11570    arguments that are being used when calling it.  TARGS is a vector
11571    into which the deduced template arguments are placed.
11572
11573    Return zero for success, 2 for an incomplete match that doesn't resolve
11574    all the types, and 1 for complete failure.  An error message will be
11575    printed only for an incomplete match.
11576
11577    If FN is a conversion operator, or we are trying to produce a specific
11578    specialization, RETURN_TYPE is the return type desired.
11579
11580    The EXPLICIT_TARGS are explicit template arguments provided via a
11581    template-id.
11582
11583    The parameter STRICT is one of:
11584
11585    DEDUCE_CALL:
11586      We are deducing arguments for a function call, as in
11587      [temp.deduct.call].
11588
11589    DEDUCE_CONV:
11590      We are deducing arguments for a conversion function, as in
11591      [temp.deduct.conv].
11592
11593    DEDUCE_EXACT:
11594      We are deducing arguments when doing an explicit instantiation
11595      as in [temp.explicit], when determining an explicit specialization
11596      as in [temp.expl.spec], or when taking the address of a function
11597      template, as in [temp.deduct.funcaddr].  */
11598
11599 int
11600 fn_type_unification (tree fn,
11601                      tree explicit_targs,
11602                      tree targs,
11603                      tree args,
11604                      tree return_type,
11605                      unification_kind_t strict,
11606                      int flags)
11607 {
11608   tree parms;
11609   tree fntype;
11610   int result;
11611   bool incomplete_argument_packs_p = false;
11612
11613   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
11614
11615   fntype = TREE_TYPE (fn);
11616   if (explicit_targs)
11617     {
11618       /* [temp.deduct]
11619
11620          The specified template arguments must match the template
11621          parameters in kind (i.e., type, nontype, template), and there
11622          must not be more arguments than there are parameters;
11623          otherwise type deduction fails.
11624
11625          Nontype arguments must match the types of the corresponding
11626          nontype template parameters, or must be convertible to the
11627          types of the corresponding nontype parameters as specified in
11628          _temp.arg.nontype_, otherwise type deduction fails.
11629
11630          All references in the function type of the function template
11631          to the corresponding template parameters are replaced by the
11632          specified template argument values.  If a substitution in a
11633          template parameter or in the function type of the function
11634          template results in an invalid type, type deduction fails.  */
11635       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
11636       int i, len = TREE_VEC_LENGTH (tparms);
11637       tree converted_args;
11638       bool incomplete = false;
11639
11640       if (explicit_targs == error_mark_node)
11641         return 1;
11642
11643       converted_args
11644         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
11645                                   /*require_all_args=*/false,
11646                                   /*use_default_args=*/false));
11647       if (converted_args == error_mark_node)
11648         return 1;
11649
11650       /* Substitute the explicit args into the function type.  This is
11651          necessary so that, for instance, explicitly declared function
11652          arguments can match null pointed constants.  If we were given
11653          an incomplete set of explicit args, we must not do semantic
11654          processing during substitution as we could create partial
11655          instantiations.  */
11656       for (i = 0; i < len; i++)
11657         {
11658           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
11659           bool parameter_pack = false;
11660
11661           /* Dig out the actual parm.  */
11662           if (TREE_CODE (parm) == TYPE_DECL
11663               || TREE_CODE (parm) == TEMPLATE_DECL)
11664             {
11665               parm = TREE_TYPE (parm);
11666               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
11667             }
11668           else if (TREE_CODE (parm) == PARM_DECL)
11669             {
11670               parm = DECL_INITIAL (parm);
11671               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
11672             }
11673
11674           if (parameter_pack)
11675             {
11676               int level, idx;
11677               tree targ;
11678               template_parm_level_and_index (parm, &level, &idx);
11679
11680               /* Mark the argument pack as "incomplete". We could
11681                  still deduce more arguments during unification.  */
11682               targ = TMPL_ARG (converted_args, level, idx);
11683               if (targ)
11684                 {
11685                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
11686                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
11687                     = ARGUMENT_PACK_ARGS (targ);
11688                 }
11689
11690               /* We have some incomplete argument packs.  */
11691               incomplete_argument_packs_p = true;
11692             }
11693         }
11694
11695       if (incomplete_argument_packs_p)
11696         /* Any substitution is guaranteed to be incomplete if there
11697            are incomplete argument packs, because we can still deduce
11698            more arguments.  */
11699         incomplete = 1;
11700       else
11701         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
11702
11703       processing_template_decl += incomplete;
11704       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
11705       processing_template_decl -= incomplete;
11706
11707       if (fntype == error_mark_node)
11708         return 1;
11709
11710       /* Place the explicitly specified arguments in TARGS.  */
11711       for (i = NUM_TMPL_ARGS (converted_args); i--;)
11712         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
11713     }
11714
11715   /* Never do unification on the 'this' parameter.  */
11716   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
11717
11718   if (return_type)
11719     {
11720       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
11721       args = tree_cons (NULL_TREE, return_type, args);
11722     }
11723
11724   /* We allow incomplete unification without an error message here
11725      because the standard doesn't seem to explicitly prohibit it.  Our
11726      callers must be ready to deal with unification failures in any
11727      event.  */
11728   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
11729                                   targs, parms, args, /*subr=*/0,
11730                                   strict, flags);
11731
11732   if (result == 0 && incomplete_argument_packs_p)
11733     {
11734       int i, len = NUM_TMPL_ARGS (targs);
11735
11736       /* Clear the "incomplete" flags on all argument packs.  */
11737       for (i = 0; i < len; i++)
11738         {
11739           tree arg = TREE_VEC_ELT (targs, i);
11740           if (ARGUMENT_PACK_P (arg))
11741             {
11742               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
11743               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
11744             }
11745         }
11746     }
11747
11748   /* Now that we have bindings for all of the template arguments,
11749      ensure that the arguments deduced for the template template
11750      parameters have compatible template parameter lists.  We cannot
11751      check this property before we have deduced all template
11752      arguments, because the template parameter types of a template
11753      template parameter might depend on prior template parameters
11754      deduced after the template template parameter.  The following
11755      ill-formed example illustrates this issue:
11756
11757        template<typename T, template<T> class C> void f(C<5>, T);
11758
11759        template<int N> struct X {};
11760
11761        void g() {
11762          f(X<5>(), 5l); // error: template argument deduction fails
11763        }
11764
11765      The template parameter list of 'C' depends on the template type
11766      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
11767      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
11768      time that we deduce 'C'.  */
11769   if (result == 0
11770       && !template_template_parm_bindings_ok_p 
11771            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
11772     return 1;
11773
11774   if (result == 0)
11775     /* All is well so far.  Now, check:
11776
11777        [temp.deduct]
11778
11779        When all template arguments have been deduced, all uses of
11780        template parameters in nondeduced contexts are replaced with
11781        the corresponding deduced argument values.  If the
11782        substitution results in an invalid type, as described above,
11783        type deduction fails.  */
11784     if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
11785         == error_mark_node)
11786       return 1;
11787
11788   return result;
11789 }
11790
11791 /* Adjust types before performing type deduction, as described in
11792    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
11793    sections are symmetric.  PARM is the type of a function parameter
11794    or the return type of the conversion function.  ARG is the type of
11795    the argument passed to the call, or the type of the value
11796    initialized with the result of the conversion function.
11797    ARG_EXPR is the original argument expression, which may be null.  */
11798
11799 static int
11800 maybe_adjust_types_for_deduction (unification_kind_t strict,
11801                                   tree* parm,
11802                                   tree* arg,
11803                                   tree arg_expr)
11804 {
11805   int result = 0;
11806
11807   switch (strict)
11808     {
11809     case DEDUCE_CALL:
11810       break;
11811
11812     case DEDUCE_CONV:
11813       {
11814         /* Swap PARM and ARG throughout the remainder of this
11815            function; the handling is precisely symmetric since PARM
11816            will initialize ARG rather than vice versa.  */
11817         tree* temp = parm;
11818         parm = arg;
11819         arg = temp;
11820         break;
11821       }
11822
11823     case DEDUCE_EXACT:
11824       /* There is nothing to do in this case.  */
11825       return 0;
11826
11827     default:
11828       gcc_unreachable ();
11829     }
11830
11831   if (TREE_CODE (*parm) != REFERENCE_TYPE)
11832     {
11833       /* [temp.deduct.call]
11834
11835          If P is not a reference type:
11836
11837          --If A is an array type, the pointer type produced by the
11838          array-to-pointer standard conversion (_conv.array_) is
11839          used in place of A for type deduction; otherwise,
11840
11841          --If A is a function type, the pointer type produced by
11842          the function-to-pointer standard conversion
11843          (_conv.func_) is used in place of A for type deduction;
11844          otherwise,
11845
11846          --If A is a cv-qualified type, the top level
11847          cv-qualifiers of A's type are ignored for type
11848          deduction.  */
11849       if (TREE_CODE (*arg) == ARRAY_TYPE)
11850         *arg = build_pointer_type (TREE_TYPE (*arg));
11851       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
11852         *arg = build_pointer_type (*arg);
11853       else
11854         *arg = TYPE_MAIN_VARIANT (*arg);
11855     }
11856
11857   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
11858      of the form T&&, where T is a template parameter, and the argument
11859      is an lvalue, T is deduced as A& */
11860   if (TREE_CODE (*parm) == REFERENCE_TYPE
11861       && TYPE_REF_IS_RVALUE (*parm)
11862       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
11863       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
11864       && arg_expr && real_lvalue_p (arg_expr))
11865     *arg = build_reference_type (*arg);
11866
11867   /* [temp.deduct.call]
11868
11869      If P is a cv-qualified type, the top level cv-qualifiers
11870      of P's type are ignored for type deduction.  If P is a
11871      reference type, the type referred to by P is used for
11872      type deduction.  */
11873   *parm = TYPE_MAIN_VARIANT (*parm);
11874   if (TREE_CODE (*parm) == REFERENCE_TYPE)
11875     {
11876       *parm = TREE_TYPE (*parm);
11877       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
11878     }
11879
11880   /* DR 322. For conversion deduction, remove a reference type on parm
11881      too (which has been swapped into ARG).  */
11882   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
11883     *arg = TREE_TYPE (*arg);
11884
11885   return result;
11886 }
11887
11888 /* Most parms like fn_type_unification.
11889
11890    If SUBR is 1, we're being called recursively (to unify the
11891    arguments of a function or method parameter of a function
11892    template). */
11893
11894 static int
11895 type_unification_real (tree tparms,
11896                        tree targs,
11897                        tree xparms,
11898                        tree xargs,
11899                        int subr,
11900                        unification_kind_t strict,
11901                        int flags)
11902 {
11903   tree parm, arg, arg_expr;
11904   int i;
11905   int ntparms = TREE_VEC_LENGTH (tparms);
11906   int sub_strict;
11907   int saw_undeduced = 0;
11908   tree parms, args;
11909
11910   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
11911   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
11912   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
11913   gcc_assert (ntparms > 0);
11914
11915   switch (strict)
11916     {
11917     case DEDUCE_CALL:
11918       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
11919                     | UNIFY_ALLOW_DERIVED);
11920       break;
11921
11922     case DEDUCE_CONV:
11923       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
11924       break;
11925
11926     case DEDUCE_EXACT:
11927       sub_strict = UNIFY_ALLOW_NONE;
11928       break;
11929
11930     default:
11931       gcc_unreachable ();
11932     }
11933
11934  again:
11935   parms = xparms;
11936   args = xargs;
11937
11938   while (parms && parms != void_list_node
11939          && args && args != void_list_node)
11940     {
11941       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
11942         break;
11943
11944       parm = TREE_VALUE (parms);
11945       parms = TREE_CHAIN (parms);
11946       arg = TREE_VALUE (args);
11947       args = TREE_CHAIN (args);
11948       arg_expr = NULL;
11949
11950       if (arg == error_mark_node)
11951         return 1;
11952       if (arg == unknown_type_node)
11953         /* We can't deduce anything from this, but we might get all the
11954            template args from other function args.  */
11955         continue;
11956
11957       /* Conversions will be performed on a function argument that
11958          corresponds with a function parameter that contains only
11959          non-deducible template parameters and explicitly specified
11960          template parameters.  */
11961       if (!uses_template_parms (parm))
11962         {
11963           tree type;
11964
11965           if (!TYPE_P (arg))
11966             type = TREE_TYPE (arg);
11967           else
11968             type = arg;
11969
11970           if (same_type_p (parm, type))
11971             continue;
11972           if (strict != DEDUCE_EXACT
11973               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
11974                                   flags))
11975             continue;
11976
11977           return 1;
11978         }
11979
11980       if (!TYPE_P (arg))
11981         {
11982           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
11983           if (type_unknown_p (arg))
11984             {
11985               /* [temp.deduct.type] 
11986
11987                  A template-argument can be deduced from a pointer to
11988                  function or pointer to member function argument if
11989                  the set of overloaded functions does not contain
11990                  function templates and at most one of a set of
11991                  overloaded functions provides a unique match.  */
11992               if (resolve_overloaded_unification
11993                   (tparms, targs, parm, arg, strict, sub_strict))
11994                 continue;
11995
11996               return 1;
11997             }
11998           arg_expr = arg;
11999           arg = unlowered_expr_type (arg);
12000           if (arg == error_mark_node)
12001             return 1;
12002         }
12003
12004       {
12005         int arg_strict = sub_strict;
12006
12007         if (!subr)
12008           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12009                                                           arg_expr);
12010
12011         if (unify (tparms, targs, parm, arg, arg_strict))
12012           return 1;
12013       }
12014     }
12015
12016
12017   if (parms 
12018       && parms != void_list_node
12019       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12020     {
12021       /* Unify the remaining arguments with the pack expansion type.  */
12022       tree argvec;
12023       tree parmvec = make_tree_vec (1);
12024       int len = 0;
12025       tree t;
12026
12027       /* Count the number of arguments that remain.  */
12028       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
12029         len++;
12030         
12031       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12032       argvec = make_tree_vec (len);
12033       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
12034         {
12035           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
12036           ++i;
12037         }
12038
12039       /* Copy the parameter into parmvec.  */
12040       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12041       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12042                                 /*call_args_p=*/true, /*subr=*/subr))
12043         return 1;
12044
12045       /* Advance to the end of the list of parameters.  */
12046       parms = TREE_CHAIN (parms);
12047     }
12048
12049   /* Fail if we've reached the end of the parm list, and more args
12050      are present, and the parm list isn't variadic.  */
12051   if (args && args != void_list_node && parms == void_list_node)
12052     return 1;
12053   /* Fail if parms are left and they don't have default values.  */
12054   if (parms && parms != void_list_node
12055       && TREE_PURPOSE (parms) == NULL_TREE)
12056     return 1;
12057
12058   if (!subr)
12059     for (i = 0; i < ntparms; i++)
12060       if (!TREE_VEC_ELT (targs, i))
12061         {
12062           tree tparm;
12063
12064           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12065             continue;
12066
12067           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12068
12069           /* If this is an undeduced nontype parameter that depends on
12070              a type parameter, try another pass; its type may have been
12071              deduced from a later argument than the one from which
12072              this parameter can be deduced.  */
12073           if (TREE_CODE (tparm) == PARM_DECL
12074               && uses_template_parms (TREE_TYPE (tparm))
12075               && !saw_undeduced++)
12076             goto again;
12077
12078           /* Core issue #226 (C++0x) [temp.deduct]:
12079
12080                If a template argument has not been deduced, its
12081                default template argument, if any, is used. 
12082
12083              When we are in C++98 mode, TREE_PURPOSE will either
12084              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12085              to explicitly check cxx_dialect here.  */
12086           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12087             {
12088               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
12089                                  targs, tf_none, NULL_TREE);
12090               if (arg == error_mark_node)
12091                 return 1;
12092               else
12093                 {
12094                   TREE_VEC_ELT (targs, i) = arg;
12095                   continue;
12096                 }
12097             }
12098
12099           /* If the type parameter is a parameter pack, then it will
12100              be deduced to an empty parameter pack.  */
12101           if (template_parameter_pack_p (tparm))
12102             {
12103               tree arg;
12104
12105               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12106                 {
12107                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12108                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12109                   TREE_CONSTANT (arg) = 1;
12110                 }
12111               else
12112                 arg = make_node (TYPE_ARGUMENT_PACK);
12113
12114               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12115
12116               TREE_VEC_ELT (targs, i) = arg;
12117               continue;
12118             }
12119
12120           return 2;
12121         }
12122
12123   return 0;
12124 }
12125
12126 /* Subroutine of type_unification_real.  Args are like the variables
12127    at the call site.  ARG is an overloaded function (or template-id);
12128    we try deducing template args from each of the overloads, and if
12129    only one succeeds, we go with that.  Modifies TARGS and returns
12130    true on success.  */
12131
12132 static bool
12133 resolve_overloaded_unification (tree tparms,
12134                                 tree targs,
12135                                 tree parm,
12136                                 tree arg,
12137                                 unification_kind_t strict,
12138                                 int sub_strict)
12139 {
12140   tree tempargs = copy_node (targs);
12141   int good = 0;
12142   bool addr_p;
12143
12144   if (TREE_CODE (arg) == ADDR_EXPR)
12145     {
12146       arg = TREE_OPERAND (arg, 0);
12147       addr_p = true;
12148     }
12149   else
12150     addr_p = false;
12151
12152   if (TREE_CODE (arg) == COMPONENT_REF)
12153     /* Handle `&x' where `x' is some static or non-static member
12154        function name.  */
12155     arg = TREE_OPERAND (arg, 1);
12156
12157   if (TREE_CODE (arg) == OFFSET_REF)
12158     arg = TREE_OPERAND (arg, 1);
12159
12160   /* Strip baselink information.  */
12161   if (BASELINK_P (arg))
12162     arg = BASELINK_FUNCTIONS (arg);
12163
12164   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12165     {
12166       /* If we got some explicit template args, we need to plug them into
12167          the affected templates before we try to unify, in case the
12168          explicit args will completely resolve the templates in question.  */
12169
12170       tree expl_subargs = TREE_OPERAND (arg, 1);
12171       arg = TREE_OPERAND (arg, 0);
12172
12173       for (; arg; arg = OVL_NEXT (arg))
12174         {
12175           tree fn = OVL_CURRENT (arg);
12176           tree subargs, elem;
12177
12178           if (TREE_CODE (fn) != TEMPLATE_DECL)
12179             continue;
12180
12181           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12182                                   expl_subargs, /*check_ret=*/false);
12183           if (subargs)
12184             {
12185               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12186               good += try_one_overload (tparms, targs, tempargs, parm,
12187                                         elem, strict, sub_strict, addr_p);
12188             }
12189         }
12190     }
12191   else if (TREE_CODE (arg) != OVERLOAD
12192            && TREE_CODE (arg) != FUNCTION_DECL)
12193     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12194        -- but the deduction does not succeed because the expression is
12195        not just the function on its own.  */
12196     return false;
12197   else
12198     for (; arg; arg = OVL_NEXT (arg))
12199       good += try_one_overload (tparms, targs, tempargs, parm,
12200                                 TREE_TYPE (OVL_CURRENT (arg)),
12201                                 strict, sub_strict, addr_p);
12202
12203   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12204      to function or pointer to member function argument if the set of
12205      overloaded functions does not contain function templates and at most
12206      one of a set of overloaded functions provides a unique match.
12207
12208      So if we found multiple possibilities, we return success but don't
12209      deduce anything.  */
12210
12211   if (good == 1)
12212     {
12213       int i = TREE_VEC_LENGTH (targs);
12214       for (; i--; )
12215         if (TREE_VEC_ELT (tempargs, i))
12216           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12217     }
12218   if (good)
12219     return true;
12220
12221   return false;
12222 }
12223
12224 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12225    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12226    different overloads deduce different arguments for a given parm.
12227    ADDR_P is true if the expression for which deduction is being
12228    performed was of the form "& fn" rather than simply "fn".
12229
12230    Returns 1 on success.  */
12231
12232 static int
12233 try_one_overload (tree tparms,
12234                   tree orig_targs,
12235                   tree targs,
12236                   tree parm,
12237                   tree arg,
12238                   unification_kind_t strict,
12239                   int sub_strict,
12240                   bool addr_p)
12241 {
12242   int nargs;
12243   tree tempargs;
12244   int i;
12245
12246   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12247      to function or pointer to member function argument if the set of
12248      overloaded functions does not contain function templates and at most
12249      one of a set of overloaded functions provides a unique match.
12250
12251      So if this is a template, just return success.  */
12252
12253   if (uses_template_parms (arg))
12254     return 1;
12255
12256   if (TREE_CODE (arg) == METHOD_TYPE)
12257     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12258   else if (addr_p)
12259     arg = build_pointer_type (arg);
12260
12261   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12262
12263   /* We don't copy orig_targs for this because if we have already deduced
12264      some template args from previous args, unify would complain when we
12265      try to deduce a template parameter for the same argument, even though
12266      there isn't really a conflict.  */
12267   nargs = TREE_VEC_LENGTH (targs);
12268   tempargs = make_tree_vec (nargs);
12269
12270   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12271     return 0;
12272
12273   /* First make sure we didn't deduce anything that conflicts with
12274      explicitly specified args.  */
12275   for (i = nargs; i--; )
12276     {
12277       tree elt = TREE_VEC_ELT (tempargs, i);
12278       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12279
12280       if (!elt)
12281         /*NOP*/;
12282       else if (uses_template_parms (elt))
12283         /* Since we're unifying against ourselves, we will fill in
12284            template args used in the function parm list with our own
12285            template parms.  Discard them.  */
12286         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12287       else if (oldelt && !template_args_equal (oldelt, elt))
12288         return 0;
12289     }
12290
12291   for (i = nargs; i--; )
12292     {
12293       tree elt = TREE_VEC_ELT (tempargs, i);
12294
12295       if (elt)
12296         TREE_VEC_ELT (targs, i) = elt;
12297     }
12298
12299   return 1;
12300 }
12301
12302 /* PARM is a template class (perhaps with unbound template
12303    parameters).  ARG is a fully instantiated type.  If ARG can be
12304    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12305    TARGS are as for unify.  */
12306
12307 static tree
12308 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12309 {
12310   tree copy_of_targs;
12311
12312   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12313       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12314           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12315     return NULL_TREE;
12316
12317   /* We need to make a new template argument vector for the call to
12318      unify.  If we used TARGS, we'd clutter it up with the result of
12319      the attempted unification, even if this class didn't work out.
12320      We also don't want to commit ourselves to all the unifications
12321      we've already done, since unification is supposed to be done on
12322      an argument-by-argument basis.  In other words, consider the
12323      following pathological case:
12324
12325        template <int I, int J, int K>
12326        struct S {};
12327
12328        template <int I, int J>
12329        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12330
12331        template <int I, int J, int K>
12332        void f(S<I, J, K>, S<I, I, I>);
12333
12334        void g() {
12335          S<0, 0, 0> s0;
12336          S<0, 1, 2> s2;
12337
12338          f(s0, s2);
12339        }
12340
12341      Now, by the time we consider the unification involving `s2', we
12342      already know that we must have `f<0, 0, 0>'.  But, even though
12343      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
12344      because there are two ways to unify base classes of S<0, 1, 2>
12345      with S<I, I, I>.  If we kept the already deduced knowledge, we
12346      would reject the possibility I=1.  */
12347   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
12348
12349   /* If unification failed, we're done.  */
12350   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
12351              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
12352     return NULL_TREE;
12353
12354   return arg;
12355 }
12356
12357 /* Given a template type PARM and a class type ARG, find the unique
12358    base type in ARG that is an instance of PARM.  We do not examine
12359    ARG itself; only its base-classes.  If there is not exactly one
12360    appropriate base class, return NULL_TREE.  PARM may be the type of
12361    a partial specialization, as well as a plain template type.  Used
12362    by unify.  */
12363
12364 static tree
12365 get_template_base (tree tparms, tree targs, tree parm, tree arg)
12366 {
12367   tree rval = NULL_TREE;
12368   tree binfo;
12369
12370   gcc_assert (IS_AGGR_TYPE_CODE (TREE_CODE (arg)));
12371
12372   binfo = TYPE_BINFO (complete_type (arg));
12373   if (!binfo)
12374     /* The type could not be completed.  */
12375     return NULL_TREE;
12376
12377   /* Walk in inheritance graph order.  The search order is not
12378      important, and this avoids multiple walks of virtual bases.  */
12379   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
12380     {
12381       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
12382
12383       if (r)
12384         {
12385           /* If there is more than one satisfactory baseclass, then:
12386
12387                [temp.deduct.call]
12388
12389               If they yield more than one possible deduced A, the type
12390               deduction fails.
12391
12392              applies.  */
12393           if (rval && !same_type_p (r, rval))
12394             return NULL_TREE;
12395
12396           rval = r;
12397         }
12398     }
12399
12400   return rval;
12401 }
12402
12403 /* Returns the level of DECL, which declares a template parameter.  */
12404
12405 static int
12406 template_decl_level (tree decl)
12407 {
12408   switch (TREE_CODE (decl))
12409     {
12410     case TYPE_DECL:
12411     case TEMPLATE_DECL:
12412       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
12413
12414     case PARM_DECL:
12415       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
12416
12417     default:
12418       gcc_unreachable ();
12419     }
12420   return 0;
12421 }
12422
12423 /* Decide whether ARG can be unified with PARM, considering only the
12424    cv-qualifiers of each type, given STRICT as documented for unify.
12425    Returns nonzero iff the unification is OK on that basis.  */
12426
12427 static int
12428 check_cv_quals_for_unify (int strict, tree arg, tree parm)
12429 {
12430   int arg_quals = cp_type_quals (arg);
12431   int parm_quals = cp_type_quals (parm);
12432
12433   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12434       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12435     {
12436       /*  Although a CVR qualifier is ignored when being applied to a
12437           substituted template parameter ([8.3.2]/1 for example), that
12438           does not apply during deduction [14.8.2.4]/1, (even though
12439           that is not explicitly mentioned, [14.8.2.4]/9 indicates
12440           this).  Except when we're allowing additional CV qualifiers
12441           at the outer level [14.8.2.1]/3,1st bullet.  */
12442       if ((TREE_CODE (arg) == REFERENCE_TYPE
12443            || TREE_CODE (arg) == FUNCTION_TYPE
12444            || TREE_CODE (arg) == METHOD_TYPE)
12445           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
12446         return 0;
12447
12448       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
12449           && (parm_quals & TYPE_QUAL_RESTRICT))
12450         return 0;
12451     }
12452
12453   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12454       && (arg_quals & parm_quals) != parm_quals)
12455     return 0;
12456
12457   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
12458       && (parm_quals & arg_quals) != arg_quals)
12459     return 0;
12460
12461   return 1;
12462 }
12463
12464 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
12465 void 
12466 template_parm_level_and_index (tree parm, int* level, int* index)
12467 {
12468   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12469       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12470       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12471     {
12472       *index = TEMPLATE_TYPE_IDX (parm);
12473       *level = TEMPLATE_TYPE_LEVEL (parm);
12474     }
12475   else
12476     {
12477       *index = TEMPLATE_PARM_IDX (parm);
12478       *level = TEMPLATE_PARM_LEVEL (parm);
12479     }
12480 }
12481
12482 /* Unifies the remaining arguments in PACKED_ARGS with the pack
12483    expansion at the end of PACKED_PARMS. Returns 0 if the type
12484    deduction succeeds, 1 otherwise. STRICT is the same as in
12485    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
12486    call argument list. We'll need to adjust the arguments to make them
12487    types. SUBR tells us if this is from a recursive call to
12488    type_unification_real.  */
12489 int
12490 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
12491                       tree packed_args, int strict, bool call_args_p,
12492                       bool subr)
12493 {
12494   tree parm 
12495     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
12496   tree pattern = PACK_EXPANSION_PATTERN (parm);
12497   tree pack, packs = NULL_TREE;
12498   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
12499   int len = TREE_VEC_LENGTH (packed_args);
12500
12501   /* Determine the parameter packs we will be deducing from the
12502      pattern, and record their current deductions.  */
12503   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
12504        pack; pack = TREE_CHAIN (pack))
12505     {
12506       tree parm_pack = TREE_VALUE (pack);
12507       int idx, level;
12508
12509       /* Determine the index and level of this parameter pack.  */
12510       template_parm_level_and_index (parm_pack, &level, &idx);
12511
12512       /* Keep track of the parameter packs and their corresponding
12513          argument packs.  */
12514       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
12515       TREE_TYPE (packs) = make_tree_vec (len - start);
12516     }
12517   
12518   /* Loop through all of the arguments that have not yet been
12519      unified and unify each with the pattern.  */
12520   for (i = start; i < len; i++)
12521     {
12522       tree parm = pattern;
12523
12524       /* For each parameter pack, clear out the deduced value so that
12525          we can deduce it again.  */
12526       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12527         {
12528           int idx, level;
12529           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12530
12531           TMPL_ARG (targs, level, idx) = NULL_TREE;
12532         }
12533
12534       /* Unify the pattern with the current argument.  */
12535       {
12536         tree arg = TREE_VEC_ELT (packed_args, i);
12537         tree arg_expr = NULL_TREE;
12538         int arg_strict = strict;
12539         bool skip_arg_p = false;
12540
12541         if (call_args_p)
12542           {
12543             int sub_strict;
12544
12545             /* This mirrors what we do in type_unification_real.  */
12546             switch (strict)
12547               {
12548               case DEDUCE_CALL:
12549                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
12550                               | UNIFY_ALLOW_MORE_CV_QUAL
12551                               | UNIFY_ALLOW_DERIVED);
12552                 break;
12553                 
12554               case DEDUCE_CONV:
12555                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12556                 break;
12557                 
12558               case DEDUCE_EXACT:
12559                 sub_strict = UNIFY_ALLOW_NONE;
12560                 break;
12561                 
12562               default:
12563                 gcc_unreachable ();
12564               }
12565
12566             if (!TYPE_P (arg))
12567               {
12568                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12569                 if (type_unknown_p (arg))
12570                   {
12571                     /* [temp.deduct.type] A template-argument can be
12572                        deduced from a pointer to function or pointer
12573                        to member function argument if the set of
12574                        overloaded functions does not contain function
12575                        templates and at most one of a set of
12576                        overloaded functions provides a unique
12577                        match.  */
12578
12579                     if (resolve_overloaded_unification
12580                         (tparms, targs, parm, arg, strict, sub_strict)
12581                         != 0)
12582                       return 1;
12583                     skip_arg_p = true;
12584                   }
12585
12586                 if (!skip_arg_p)
12587                   {
12588                     arg_expr = arg;
12589                     arg = unlowered_expr_type (arg);
12590                     if (arg == error_mark_node)
12591                       return 1;
12592                   }
12593               }
12594       
12595             arg_strict = sub_strict;
12596
12597             if (!subr)
12598               arg_strict |= 
12599                 maybe_adjust_types_for_deduction (strict, &parm, &arg, 
12600                                                   arg_expr);
12601           }
12602
12603         if (!skip_arg_p)
12604           {
12605             if (unify (tparms, targs, parm, arg, arg_strict))
12606               return 1;
12607           }
12608       }
12609
12610       /* For each parameter pack, collect the deduced value.  */
12611       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12612         {
12613           int idx, level;
12614           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12615
12616           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
12617             TMPL_ARG (targs, level, idx);
12618         }
12619     }
12620
12621   /* Verify that the results of unification with the parameter packs
12622      produce results consistent with what we've seen before, and make
12623      the deduced argument packs available.  */
12624   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12625     {
12626       tree old_pack = TREE_VALUE (pack);
12627       tree new_args = TREE_TYPE (pack);
12628       int i, len = TREE_VEC_LENGTH (new_args);
12629       bool nondeduced_p = false;
12630
12631       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
12632          actually deduce anything.  */
12633       for (i = 0; i < len && !nondeduced_p; ++i)
12634         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
12635           nondeduced_p = true;
12636       if (nondeduced_p)
12637         continue;
12638
12639       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
12640         {
12641           /* Prepend the explicit arguments onto NEW_ARGS.  */
12642           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12643           tree old_args = new_args;
12644           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
12645           int len = explicit_len + TREE_VEC_LENGTH (old_args);
12646
12647           /* Copy the explicit arguments.  */
12648           new_args = make_tree_vec (len);
12649           for (i = 0; i < explicit_len; i++)
12650             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
12651
12652           /* Copy the deduced arguments.  */
12653           for (; i < len; i++)
12654             TREE_VEC_ELT (new_args, i) =
12655               TREE_VEC_ELT (old_args, i - explicit_len);
12656         }
12657
12658       if (!old_pack)
12659         {
12660           tree result;
12661           int idx, level;
12662           
12663           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12664
12665           /* Build the deduced *_ARGUMENT_PACK.  */
12666           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
12667             {
12668               result = make_node (NONTYPE_ARGUMENT_PACK);
12669               TREE_TYPE (result) = 
12670                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
12671               TREE_CONSTANT (result) = 1;
12672             }
12673           else
12674             result = make_node (TYPE_ARGUMENT_PACK);
12675
12676           SET_ARGUMENT_PACK_ARGS (result, new_args);
12677
12678           /* Note the deduced argument packs for this parameter
12679              pack.  */
12680           TMPL_ARG (targs, level, idx) = result;
12681         }
12682       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
12683                && (ARGUMENT_PACK_ARGS (old_pack) 
12684                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
12685         {
12686           /* We only had the explicitly-provided arguments before, but
12687              now we have a complete set of arguments.  */
12688           int idx, level;
12689           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12690           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12691
12692           /* Keep the original deduced argument pack.  */
12693           TMPL_ARG (targs, level, idx) = old_pack;
12694
12695           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
12696           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
12697           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
12698         }
12699       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
12700                                     new_args))
12701         /* Inconsistent unification of this parameter pack.  */
12702         return 1;
12703       else
12704         {
12705           int idx, level;
12706           
12707           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12708
12709           /* Keep the original deduced argument pack.  */
12710           TMPL_ARG (targs, level, idx) = old_pack;
12711         }
12712     }
12713
12714   return 0;
12715 }
12716
12717 /* Deduce the value of template parameters.  TPARMS is the (innermost)
12718    set of template parameters to a template.  TARGS is the bindings
12719    for those template parameters, as determined thus far; TARGS may
12720    include template arguments for outer levels of template parameters
12721    as well.  PARM is a parameter to a template function, or a
12722    subcomponent of that parameter; ARG is the corresponding argument.
12723    This function attempts to match PARM with ARG in a manner
12724    consistent with the existing assignments in TARGS.  If more values
12725    are deduced, then TARGS is updated.
12726
12727    Returns 0 if the type deduction succeeds, 1 otherwise.  The
12728    parameter STRICT is a bitwise or of the following flags:
12729
12730      UNIFY_ALLOW_NONE:
12731        Require an exact match between PARM and ARG.
12732      UNIFY_ALLOW_MORE_CV_QUAL:
12733        Allow the deduced ARG to be more cv-qualified (by qualification
12734        conversion) than ARG.
12735      UNIFY_ALLOW_LESS_CV_QUAL:
12736        Allow the deduced ARG to be less cv-qualified than ARG.
12737      UNIFY_ALLOW_DERIVED:
12738        Allow the deduced ARG to be a template base class of ARG,
12739        or a pointer to a template base class of the type pointed to by
12740        ARG.
12741      UNIFY_ALLOW_INTEGER:
12742        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
12743        case for more information.
12744      UNIFY_ALLOW_OUTER_LEVEL:
12745        This is the outermost level of a deduction. Used to determine validity
12746        of qualification conversions. A valid qualification conversion must
12747        have const qualified pointers leading up to the inner type which
12748        requires additional CV quals, except at the outer level, where const
12749        is not required [conv.qual]. It would be normal to set this flag in
12750        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
12751      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
12752        This is the outermost level of a deduction, and PARM can be more CV
12753        qualified at this point.
12754      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
12755        This is the outermost level of a deduction, and PARM can be less CV
12756        qualified at this point.  */
12757
12758 static int
12759 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
12760 {
12761   int idx;
12762   tree targ;
12763   tree tparm;
12764   int strict_in = strict;
12765
12766   /* I don't think this will do the right thing with respect to types.
12767      But the only case I've seen it in so far has been array bounds, where
12768      signedness is the only information lost, and I think that will be
12769      okay.  */
12770   while (TREE_CODE (parm) == NOP_EXPR)
12771     parm = TREE_OPERAND (parm, 0);
12772
12773   if (arg == error_mark_node)
12774     return 1;
12775   if (arg == unknown_type_node)
12776     /* We can't deduce anything from this, but we might get all the
12777        template args from other function args.  */
12778     return 0;
12779
12780   /* If PARM uses template parameters, then we can't bail out here,
12781      even if ARG == PARM, since we won't record unifications for the
12782      template parameters.  We might need them if we're trying to
12783      figure out which of two things is more specialized.  */
12784   if (arg == parm && !uses_template_parms (parm))
12785     return 0;
12786
12787   /* Immediately reject some pairs that won't unify because of
12788      cv-qualification mismatches.  */
12789   if (TREE_CODE (arg) == TREE_CODE (parm)
12790       && TYPE_P (arg)
12791       /* It is the elements of the array which hold the cv quals of an array
12792          type, and the elements might be template type parms. We'll check
12793          when we recurse.  */
12794       && TREE_CODE (arg) != ARRAY_TYPE
12795       /* We check the cv-qualifiers when unifying with template type
12796          parameters below.  We want to allow ARG `const T' to unify with
12797          PARM `T' for example, when computing which of two templates
12798          is more specialized, for example.  */
12799       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
12800       && !check_cv_quals_for_unify (strict_in, arg, parm))
12801     return 1;
12802
12803   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
12804       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
12805     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
12806   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
12807   strict &= ~UNIFY_ALLOW_DERIVED;
12808   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12809   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
12810
12811   switch (TREE_CODE (parm))
12812     {
12813     case TYPENAME_TYPE:
12814     case SCOPE_REF:
12815     case UNBOUND_CLASS_TEMPLATE:
12816       /* In a type which contains a nested-name-specifier, template
12817          argument values cannot be deduced for template parameters used
12818          within the nested-name-specifier.  */
12819       return 0;
12820
12821     case TEMPLATE_TYPE_PARM:
12822     case TEMPLATE_TEMPLATE_PARM:
12823     case BOUND_TEMPLATE_TEMPLATE_PARM:
12824       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
12825       if (tparm == error_mark_node)
12826         return 1;
12827
12828       if (TEMPLATE_TYPE_LEVEL (parm)
12829           != template_decl_level (tparm))
12830         /* The PARM is not one we're trying to unify.  Just check
12831            to see if it matches ARG.  */
12832         return (TREE_CODE (arg) == TREE_CODE (parm)
12833                 && same_type_p (parm, arg)) ? 0 : 1;
12834       idx = TEMPLATE_TYPE_IDX (parm);
12835       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
12836       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
12837
12838       /* Check for mixed types and values.  */
12839       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12840            && TREE_CODE (tparm) != TYPE_DECL)
12841           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12842               && TREE_CODE (tparm) != TEMPLATE_DECL))
12843         return 1;
12844
12845       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12846         {
12847           /* ARG must be constructed from a template class or a template
12848              template parameter.  */
12849           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
12850               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
12851             return 1;
12852
12853           {
12854             tree parmvec = TYPE_TI_ARGS (parm);
12855             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
12856             tree argtmplvec
12857               = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_TI_TEMPLATE (arg));
12858             int i, len;
12859             int parm_variadic_p = 0;
12860
12861             /* The resolution to DR150 makes clear that default
12862                arguments for an N-argument may not be used to bind T
12863                to a template template parameter with fewer than N
12864                parameters.  It is not safe to permit the binding of
12865                default arguments as an extension, as that may change
12866                the meaning of a conforming program.  Consider:
12867
12868                   struct Dense { static const unsigned int dim = 1; };
12869
12870                   template <template <typename> class View,
12871                             typename Block>
12872                   void operator+(float, View<Block> const&);
12873
12874                   template <typename Block,
12875                             unsigned int Dim = Block::dim>
12876                   struct Lvalue_proxy { operator float() const; };
12877
12878                   void
12879                   test_1d (void) {
12880                     Lvalue_proxy<Dense> p;
12881                     float b;
12882                     b + p;
12883                   }
12884
12885               Here, if Lvalue_proxy is permitted to bind to View, then
12886               the global operator+ will be used; if they are not, the
12887               Lvalue_proxy will be converted to float.  */
12888             if (coerce_template_parms (argtmplvec, parmvec,
12889                                        TYPE_TI_TEMPLATE (parm),
12890                                        tf_none,
12891                                        /*require_all_args=*/true,
12892                                        /*use_default_args=*/false)
12893                 == error_mark_node)
12894               return 1;
12895
12896             /* Deduce arguments T, i from TT<T> or TT<i>.
12897                We check each element of PARMVEC and ARGVEC individually
12898                rather than the whole TREE_VEC since they can have
12899                different number of elements.  */
12900
12901             parmvec = expand_template_argument_pack (parmvec);
12902             argvec = expand_template_argument_pack (argvec);
12903
12904             len = TREE_VEC_LENGTH (parmvec);
12905
12906             /* Check if the parameters end in a pack, making them
12907                variadic.  */
12908             if (len > 0
12909                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
12910               parm_variadic_p = 1;
12911             
12912             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
12913               return 1;
12914
12915              for (i = 0; i < len - parm_variadic_p; ++i)
12916               {
12917                 if (unify (tparms, targs,
12918                            TREE_VEC_ELT (parmvec, i),
12919                            TREE_VEC_ELT (argvec, i),
12920                            UNIFY_ALLOW_NONE))
12921                   return 1;
12922               }
12923
12924             if (parm_variadic_p
12925                 && unify_pack_expansion (tparms, targs,
12926                                          parmvec, argvec,
12927                                          UNIFY_ALLOW_NONE,
12928                                          /*call_args_p=*/false,
12929                                          /*subr=*/false))
12930               return 1;
12931           }
12932           arg = TYPE_TI_TEMPLATE (arg);
12933
12934           /* Fall through to deduce template name.  */
12935         }
12936
12937       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12938           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12939         {
12940           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
12941
12942           /* Simple cases: Value already set, does match or doesn't.  */
12943           if (targ != NULL_TREE && template_args_equal (targ, arg))
12944             return 0;
12945           else if (targ)
12946             return 1;
12947         }
12948       else
12949         {
12950           /* If PARM is `const T' and ARG is only `int', we don't have
12951              a match unless we are allowing additional qualification.
12952              If ARG is `const int' and PARM is just `T' that's OK;
12953              that binds `const int' to `T'.  */
12954           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
12955                                          arg, parm))
12956             return 1;
12957
12958           /* Consider the case where ARG is `const volatile int' and
12959              PARM is `const T'.  Then, T should be `volatile int'.  */
12960           arg = cp_build_qualified_type_real
12961             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
12962           if (arg == error_mark_node)
12963             return 1;
12964
12965           /* Simple cases: Value already set, does match or doesn't.  */
12966           if (targ != NULL_TREE && same_type_p (targ, arg))
12967             return 0;
12968           else if (targ)
12969             return 1;
12970
12971           /* Make sure that ARG is not a variable-sized array.  (Note
12972              that were talking about variable-sized arrays (like
12973              `int[n]'), rather than arrays of unknown size (like
12974              `int[]').)  We'll get very confused by such a type since
12975              the bound of the array will not be computable in an
12976              instantiation.  Besides, such types are not allowed in
12977              ISO C++, so we can do as we please here.  */
12978           if (variably_modified_type_p (arg, NULL_TREE))
12979             return 1;
12980         }
12981
12982       /* If ARG is a parameter pack or an expansion, we cannot unify
12983          against it unless PARM is also a parameter pack.  */
12984       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
12985           && !template_parameter_pack_p (parm))
12986         return 1;
12987
12988       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
12989       return 0;
12990
12991     case TEMPLATE_PARM_INDEX:
12992       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
12993       if (tparm == error_mark_node)
12994         return 1;
12995
12996       if (TEMPLATE_PARM_LEVEL (parm)
12997           != template_decl_level (tparm))
12998         /* The PARM is not one we're trying to unify.  Just check
12999            to see if it matches ARG.  */
13000         return !(TREE_CODE (arg) == TREE_CODE (parm)
13001                  && cp_tree_equal (parm, arg));
13002
13003       idx = TEMPLATE_PARM_IDX (parm);
13004       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13005
13006       if (targ)
13007         return !cp_tree_equal (targ, arg);
13008
13009       /* [temp.deduct.type] If, in the declaration of a function template
13010          with a non-type template-parameter, the non-type
13011          template-parameter is used in an expression in the function
13012          parameter-list and, if the corresponding template-argument is
13013          deduced, the template-argument type shall match the type of the
13014          template-parameter exactly, except that a template-argument
13015          deduced from an array bound may be of any integral type.
13016          The non-type parameter might use already deduced type parameters.  */
13017       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13018       if (!TREE_TYPE (arg))
13019         /* Template-parameter dependent expression.  Just accept it for now.
13020            It will later be processed in convert_template_argument.  */
13021         ;
13022       else if (same_type_p (TREE_TYPE (arg), tparm))
13023         /* OK */;
13024       else if ((strict & UNIFY_ALLOW_INTEGER)
13025                && (TREE_CODE (tparm) == INTEGER_TYPE
13026                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13027         /* Convert the ARG to the type of PARM; the deduced non-type
13028            template argument must exactly match the types of the
13029            corresponding parameter.  */
13030         arg = fold (build_nop (TREE_TYPE (parm), arg));
13031       else if (uses_template_parms (tparm))
13032         /* We haven't deduced the type of this parameter yet.  Try again
13033            later.  */
13034         return 0;
13035       else
13036         return 1;
13037
13038       /* If ARG is a parameter pack or an expansion, we cannot unify
13039          against it unless PARM is also a parameter pack.  */
13040       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13041           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13042         return 1;
13043
13044       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13045       return 0;
13046
13047     case PTRMEM_CST:
13048      {
13049         /* A pointer-to-member constant can be unified only with
13050          another constant.  */
13051       if (TREE_CODE (arg) != PTRMEM_CST)
13052         return 1;
13053
13054       /* Just unify the class member. It would be useless (and possibly
13055          wrong, depending on the strict flags) to unify also
13056          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13057          arg refer to the same variable, even if through different
13058          classes. For instance:
13059
13060          struct A { int x; };
13061          struct B : A { };
13062
13063          Unification of &A::x and &B::x must succeed.  */
13064       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13065                     PTRMEM_CST_MEMBER (arg), strict);
13066      }
13067
13068     case POINTER_TYPE:
13069       {
13070         if (TREE_CODE (arg) != POINTER_TYPE)
13071           return 1;
13072
13073         /* [temp.deduct.call]
13074
13075            A can be another pointer or pointer to member type that can
13076            be converted to the deduced A via a qualification
13077            conversion (_conv.qual_).
13078
13079            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13080            This will allow for additional cv-qualification of the
13081            pointed-to types if appropriate.  */
13082
13083         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13084           /* The derived-to-base conversion only persists through one
13085              level of pointers.  */
13086           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13087
13088         return unify (tparms, targs, TREE_TYPE (parm),
13089                       TREE_TYPE (arg), strict);
13090       }
13091
13092     case REFERENCE_TYPE:
13093       if (TREE_CODE (arg) != REFERENCE_TYPE)
13094         return 1;
13095       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13096                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13097
13098     case ARRAY_TYPE:
13099       if (TREE_CODE (arg) != ARRAY_TYPE)
13100         return 1;
13101       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13102           != (TYPE_DOMAIN (arg) == NULL_TREE))
13103         return 1;
13104       if (TYPE_DOMAIN (parm) != NULL_TREE)
13105         {
13106           tree parm_max;
13107           tree arg_max;
13108           bool parm_cst;
13109           bool arg_cst;
13110
13111           /* Our representation of array types uses "N - 1" as the
13112              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13113              not an integer constant.  We cannot unify arbitrarily
13114              complex expressions, so we eliminate the MINUS_EXPRs
13115              here.  */
13116           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13117           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13118           if (!parm_cst)
13119             {
13120               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13121               parm_max = TREE_OPERAND (parm_max, 0);
13122             }
13123           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13124           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13125           if (!arg_cst)
13126             {
13127               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13128                  trying to unify the type of a variable with the type
13129                  of a template parameter.  For example:
13130
13131                    template <unsigned int N>
13132                    void f (char (&) [N]);
13133                    int g(); 
13134                    void h(int i) {
13135                      char a[g(i)];
13136                      f(a); 
13137                    }
13138
13139                 Here, the type of the ARG will be "int [g(i)]", and
13140                 may be a SAVE_EXPR, etc.  */
13141               if (TREE_CODE (arg_max) != MINUS_EXPR)
13142                 return 1;
13143               arg_max = TREE_OPERAND (arg_max, 0);
13144             }
13145
13146           /* If only one of the bounds used a MINUS_EXPR, compensate
13147              by adding one to the other bound.  */
13148           if (parm_cst && !arg_cst)
13149             parm_max = fold_build2 (PLUS_EXPR,
13150                                     integer_type_node,
13151                                     parm_max,
13152                                     integer_one_node);
13153           else if (arg_cst && !parm_cst)
13154             arg_max = fold_build2 (PLUS_EXPR,
13155                                    integer_type_node,
13156                                    arg_max,
13157                                    integer_one_node);
13158
13159           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13160             return 1;
13161         }
13162       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13163                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13164
13165     case REAL_TYPE:
13166     case COMPLEX_TYPE:
13167     case VECTOR_TYPE:
13168     case INTEGER_TYPE:
13169     case BOOLEAN_TYPE:
13170     case ENUMERAL_TYPE:
13171     case VOID_TYPE:
13172       if (TREE_CODE (arg) != TREE_CODE (parm))
13173         return 1;
13174
13175       /* We have already checked cv-qualification at the top of the
13176          function.  */
13177       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13178         return 1;
13179
13180       /* As far as unification is concerned, this wins.  Later checks
13181          will invalidate it if necessary.  */
13182       return 0;
13183
13184       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13185       /* Type INTEGER_CST can come from ordinary constant template args.  */
13186     case INTEGER_CST:
13187       while (TREE_CODE (arg) == NOP_EXPR)
13188         arg = TREE_OPERAND (arg, 0);
13189
13190       if (TREE_CODE (arg) != INTEGER_CST)
13191         return 1;
13192       return !tree_int_cst_equal (parm, arg);
13193
13194     case TREE_VEC:
13195       {
13196         int i;
13197         if (TREE_CODE (arg) != TREE_VEC)
13198           return 1;
13199         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13200           return 1;
13201         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13202           if (unify (tparms, targs,
13203                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13204                      UNIFY_ALLOW_NONE))
13205             return 1;
13206         return 0;
13207       }
13208
13209     case RECORD_TYPE:
13210     case UNION_TYPE:
13211       if (TREE_CODE (arg) != TREE_CODE (parm))
13212         return 1;
13213
13214       if (TYPE_PTRMEMFUNC_P (parm))
13215         {
13216           if (!TYPE_PTRMEMFUNC_P (arg))
13217             return 1;
13218
13219           return unify (tparms, targs,
13220                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13221                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13222                         strict);
13223         }
13224
13225       if (CLASSTYPE_TEMPLATE_INFO (parm))
13226         {
13227           tree t = NULL_TREE;
13228
13229           if (strict_in & UNIFY_ALLOW_DERIVED)
13230             {
13231               /* First, we try to unify the PARM and ARG directly.  */
13232               t = try_class_unification (tparms, targs,
13233                                          parm, arg);
13234
13235               if (!t)
13236                 {
13237                   /* Fallback to the special case allowed in
13238                      [temp.deduct.call]:
13239
13240                        If P is a class, and P has the form
13241                        template-id, then A can be a derived class of
13242                        the deduced A.  Likewise, if P is a pointer to
13243                        a class of the form template-id, A can be a
13244                        pointer to a derived class pointed to by the
13245                        deduced A.  */
13246                   t = get_template_base (tparms, targs, parm, arg);
13247
13248                   if (!t)
13249                     return 1;
13250                 }
13251             }
13252           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13253                    && (CLASSTYPE_TI_TEMPLATE (parm)
13254                        == CLASSTYPE_TI_TEMPLATE (arg)))
13255             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13256                Then, we should unify `int' and `U'.  */
13257             t = arg;
13258           else
13259             /* There's no chance of unification succeeding.  */
13260             return 1;
13261
13262           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13263                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13264         }
13265       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13266         return 1;
13267       return 0;
13268
13269     case METHOD_TYPE:
13270     case FUNCTION_TYPE:
13271       if (TREE_CODE (arg) != TREE_CODE (parm))
13272         return 1;
13273
13274       /* CV qualifications for methods can never be deduced, they must
13275          match exactly.  We need to check them explicitly here,
13276          because type_unification_real treats them as any other
13277          cvqualified parameter.  */
13278       if (TREE_CODE (parm) == METHOD_TYPE
13279           && (!check_cv_quals_for_unify
13280               (UNIFY_ALLOW_NONE,
13281                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
13282                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
13283         return 1;
13284
13285       if (unify (tparms, targs, TREE_TYPE (parm),
13286                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
13287         return 1;
13288       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
13289                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
13290                                     LOOKUP_NORMAL);
13291
13292     case OFFSET_TYPE:
13293       /* Unify a pointer to member with a pointer to member function, which
13294          deduces the type of the member as a function type. */
13295       if (TYPE_PTRMEMFUNC_P (arg))
13296         {
13297           tree method_type;
13298           tree fntype;
13299           cp_cv_quals cv_quals;
13300
13301           /* Check top-level cv qualifiers */
13302           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
13303             return 1;
13304
13305           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13306                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
13307             return 1;
13308
13309           /* Determine the type of the function we are unifying against. */
13310           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
13311           fntype =
13312             build_function_type (TREE_TYPE (method_type),
13313                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
13314
13315           /* Extract the cv-qualifiers of the member function from the
13316              implicit object parameter and place them on the function
13317              type to be restored later. */
13318           cv_quals =
13319             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
13320           fntype = build_qualified_type (fntype, cv_quals);
13321           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
13322         }
13323
13324       if (TREE_CODE (arg) != OFFSET_TYPE)
13325         return 1;
13326       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13327                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
13328         return 1;
13329       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13330                     strict);
13331
13332     case CONST_DECL:
13333       if (DECL_TEMPLATE_PARM_P (parm))
13334         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
13335       if (arg != integral_constant_value (parm))
13336         return 1;
13337       return 0;
13338
13339     case FIELD_DECL:
13340     case TEMPLATE_DECL:
13341       /* Matched cases are handled by the ARG == PARM test above.  */
13342       return 1;
13343
13344     case TYPE_ARGUMENT_PACK:
13345     case NONTYPE_ARGUMENT_PACK:
13346       {
13347         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
13348         tree packed_args = ARGUMENT_PACK_ARGS (arg);
13349         int i, len = TREE_VEC_LENGTH (packed_parms);
13350         int argslen = TREE_VEC_LENGTH (packed_args);
13351         int parm_variadic_p = 0;
13352
13353         for (i = 0; i < len; ++i)
13354           {
13355             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
13356               {
13357                 if (i == len - 1)
13358                   /* We can unify against something with a trailing
13359                      parameter pack.  */
13360                   parm_variadic_p = 1;
13361                 else
13362                   /* Since there is something following the pack
13363                      expansion, we cannot unify this template argument
13364                      list.  */
13365                   return 0;
13366               }
13367           }
13368           
13369
13370         /* If we don't have enough arguments to satisfy the parameters
13371            (not counting the pack expression at the end), or we have
13372            too many arguments for a parameter list that doesn't end in
13373            a pack expression, we can't unify.  */
13374         if (argslen < (len - parm_variadic_p)
13375             || (argslen > len && !parm_variadic_p))
13376           return 1;
13377
13378         /* Unify all of the parameters that precede the (optional)
13379            pack expression.  */
13380         for (i = 0; i < len - parm_variadic_p; ++i)
13381           {
13382             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
13383                        TREE_VEC_ELT (packed_args, i), strict))
13384               return 1;
13385           }
13386
13387         if (parm_variadic_p)
13388           return unify_pack_expansion (tparms, targs, 
13389                                        packed_parms, packed_args,
13390                                        strict, /*call_args_p=*/false,
13391                                        /*subr=*/false);
13392         return 0;
13393       }
13394
13395       break;
13396
13397     case TYPEOF_TYPE:
13398     case DECLTYPE_TYPE:
13399       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
13400          nodes.  */
13401       return 0;
13402
13403     case ERROR_MARK:
13404       /* Unification fails if we hit an error node.  */
13405       return 1;
13406
13407     default:
13408       gcc_assert (EXPR_P (parm));
13409
13410       /* We must be looking at an expression.  This can happen with
13411          something like:
13412
13413            template <int I>
13414            void foo(S<I>, S<I + 2>);
13415
13416          This is a "nondeduced context":
13417
13418            [deduct.type]
13419
13420            The nondeduced contexts are:
13421
13422            --A type that is a template-id in which one or more of
13423              the template-arguments is an expression that references
13424              a template-parameter.
13425
13426          In these cases, we assume deduction succeeded, but don't
13427          actually infer any unifications.  */
13428
13429       if (!uses_template_parms (parm)
13430           && !template_args_equal (parm, arg))
13431         return 1;
13432       else
13433         return 0;
13434     }
13435 }
13436 \f
13437 /* Note that DECL can be defined in this translation unit, if
13438    required.  */
13439
13440 static void
13441 mark_definable (tree decl)
13442 {
13443   tree clone;
13444   DECL_NOT_REALLY_EXTERN (decl) = 1;
13445   FOR_EACH_CLONE (clone, decl)
13446     DECL_NOT_REALLY_EXTERN (clone) = 1;
13447 }
13448
13449 /* Called if RESULT is explicitly instantiated, or is a member of an
13450    explicitly instantiated class.  */
13451
13452 void
13453 mark_decl_instantiated (tree result, int extern_p)
13454 {
13455   SET_DECL_EXPLICIT_INSTANTIATION (result);
13456
13457   /* If this entity has already been written out, it's too late to
13458      make any modifications.  */
13459   if (TREE_ASM_WRITTEN (result))
13460     return;
13461
13462   if (TREE_CODE (result) != FUNCTION_DECL)
13463     /* The TREE_PUBLIC flag for function declarations will have been
13464        set correctly by tsubst.  */
13465     TREE_PUBLIC (result) = 1;
13466
13467   /* This might have been set by an earlier implicit instantiation.  */
13468   DECL_COMDAT (result) = 0;
13469
13470   if (extern_p)
13471     DECL_NOT_REALLY_EXTERN (result) = 0;
13472   else
13473     {
13474       mark_definable (result);
13475       /* Always make artificials weak.  */
13476       if (DECL_ARTIFICIAL (result) && flag_weak)
13477         comdat_linkage (result);
13478       /* For WIN32 we also want to put explicit instantiations in
13479          linkonce sections.  */
13480       else if (TREE_PUBLIC (result))
13481         maybe_make_one_only (result);
13482     }
13483
13484   /* If EXTERN_P, then this function will not be emitted -- unless
13485      followed by an explicit instantiation, at which point its linkage
13486      will be adjusted.  If !EXTERN_P, then this function will be
13487      emitted here.  In neither circumstance do we want
13488      import_export_decl to adjust the linkage.  */
13489   DECL_INTERFACE_KNOWN (result) = 1;
13490 }
13491
13492 /* Given two function templates PAT1 and PAT2, return:
13493
13494    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
13495    -1 if PAT2 is more specialized than PAT1.
13496    0 if neither is more specialized.
13497
13498    LEN indicates the number of parameters we should consider
13499    (defaulted parameters should not be considered).
13500
13501    The 1998 std underspecified function template partial ordering, and
13502    DR214 addresses the issue.  We take pairs of arguments, one from
13503    each of the templates, and deduce them against each other.  One of
13504    the templates will be more specialized if all the *other*
13505    template's arguments deduce against its arguments and at least one
13506    of its arguments *does* *not* deduce against the other template's
13507    corresponding argument.  Deduction is done as for class templates.
13508    The arguments used in deduction have reference and top level cv
13509    qualifiers removed.  Iff both arguments were originally reference
13510    types *and* deduction succeeds in both directions, the template
13511    with the more cv-qualified argument wins for that pairing (if
13512    neither is more cv-qualified, they both are equal).  Unlike regular
13513    deduction, after all the arguments have been deduced in this way,
13514    we do *not* verify the deduced template argument values can be
13515    substituted into non-deduced contexts, nor do we have to verify
13516    that all template arguments have been deduced.  */
13517
13518 int
13519 more_specialized_fn (tree pat1, tree pat2, int len)
13520 {
13521   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
13522   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
13523   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
13524   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
13525   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
13526   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
13527   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
13528   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
13529   int better1 = 0;
13530   int better2 = 0;
13531
13532   /* Remove the this parameter from non-static member functions.  If
13533      one is a non-static member function and the other is not a static
13534      member function, remove the first parameter from that function
13535      also.  This situation occurs for operator functions where we
13536      locate both a member function (with this pointer) and non-member
13537      operator (with explicit first operand).  */
13538   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
13539     {
13540       len--; /* LEN is the number of significant arguments for DECL1 */
13541       args1 = TREE_CHAIN (args1);
13542       if (!DECL_STATIC_FUNCTION_P (decl2))
13543         args2 = TREE_CHAIN (args2);
13544     }
13545   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
13546     {
13547       args2 = TREE_CHAIN (args2);
13548       if (!DECL_STATIC_FUNCTION_P (decl1))
13549         {
13550           len--;
13551           args1 = TREE_CHAIN (args1);
13552         }
13553     }
13554
13555   /* If only one is a conversion operator, they are unordered.  */
13556   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
13557     return 0;
13558
13559   /* Consider the return type for a conversion function */
13560   if (DECL_CONV_FN_P (decl1))
13561     {
13562       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
13563       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
13564       len++;
13565     }
13566
13567   processing_template_decl++;
13568
13569   while (len--)
13570     {
13571       tree arg1 = TREE_VALUE (args1);
13572       tree arg2 = TREE_VALUE (args2);
13573       int deduce1, deduce2;
13574       int quals1 = -1;
13575       int quals2 = -1;
13576
13577       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13578           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13579         {
13580           /* When both arguments are pack expansions, we need only
13581              unify the patterns themselves.  */
13582           arg1 = PACK_EXPANSION_PATTERN (arg1);
13583           arg2 = PACK_EXPANSION_PATTERN (arg2);
13584
13585           /* This is the last comparison we need to do.  */
13586           len = 0;
13587         }
13588
13589       if (TREE_CODE (arg1) == REFERENCE_TYPE)
13590         {
13591           arg1 = TREE_TYPE (arg1);
13592           quals1 = cp_type_quals (arg1);
13593         }
13594
13595       if (TREE_CODE (arg2) == REFERENCE_TYPE)
13596         {
13597           arg2 = TREE_TYPE (arg2);
13598           quals2 = cp_type_quals (arg2);
13599         }
13600
13601       if ((quals1 < 0) != (quals2 < 0))
13602         {
13603           /* Only of the args is a reference, see if we should apply
13604              array/function pointer decay to it.  This is not part of
13605              DR214, but is, IMHO, consistent with the deduction rules
13606              for the function call itself, and with our earlier
13607              implementation of the underspecified partial ordering
13608              rules.  (nathan).  */
13609           if (quals1 >= 0)
13610             {
13611               switch (TREE_CODE (arg1))
13612                 {
13613                 case ARRAY_TYPE:
13614                   arg1 = TREE_TYPE (arg1);
13615                   /* FALLTHROUGH. */
13616                 case FUNCTION_TYPE:
13617                   arg1 = build_pointer_type (arg1);
13618                   break;
13619
13620                 default:
13621                   break;
13622                 }
13623             }
13624           else
13625             {
13626               switch (TREE_CODE (arg2))
13627                 {
13628                 case ARRAY_TYPE:
13629                   arg2 = TREE_TYPE (arg2);
13630                   /* FALLTHROUGH. */
13631                 case FUNCTION_TYPE:
13632                   arg2 = build_pointer_type (arg2);
13633                   break;
13634
13635                 default:
13636                   break;
13637                 }
13638             }
13639         }
13640
13641       arg1 = TYPE_MAIN_VARIANT (arg1);
13642       arg2 = TYPE_MAIN_VARIANT (arg2);
13643
13644       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
13645         {
13646           int i, len2 = list_length (args2);
13647           tree parmvec = make_tree_vec (1);
13648           tree argvec = make_tree_vec (len2);
13649           tree ta = args2;
13650
13651           /* Setup the parameter vector, which contains only ARG1.  */
13652           TREE_VEC_ELT (parmvec, 0) = arg1;
13653
13654           /* Setup the argument vector, which contains the remaining
13655              arguments.  */
13656           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
13657             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13658
13659           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
13660                                            argvec, UNIFY_ALLOW_NONE, 
13661                                            /*call_args_p=*/false, 
13662                                            /*subr=*/0);
13663
13664           /* We cannot deduce in the other direction, because ARG1 is
13665              a pack expansion but ARG2 is not.  */
13666           deduce2 = 0;
13667         }
13668       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13669         {
13670           int i, len1 = list_length (args1);
13671           tree parmvec = make_tree_vec (1);
13672           tree argvec = make_tree_vec (len1);
13673           tree ta = args1;
13674
13675           /* Setup the parameter vector, which contains only ARG1.  */
13676           TREE_VEC_ELT (parmvec, 0) = arg2;
13677
13678           /* Setup the argument vector, which contains the remaining
13679              arguments.  */
13680           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
13681             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13682
13683           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
13684                                            argvec, UNIFY_ALLOW_NONE, 
13685                                            /*call_args_p=*/false, 
13686                                            /*subr=*/0);
13687
13688           /* We cannot deduce in the other direction, because ARG2 is
13689              a pack expansion but ARG1 is not.*/
13690           deduce1 = 0;
13691         }
13692
13693       else
13694         {
13695           /* The normal case, where neither argument is a pack
13696              expansion.  */
13697           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
13698           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
13699         }
13700
13701       if (!deduce1)
13702         better2 = -1;
13703       if (!deduce2)
13704         better1 = -1;
13705       if (better1 < 0 && better2 < 0)
13706         /* We've failed to deduce something in either direction.
13707            These must be unordered.  */
13708         break;
13709
13710       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
13711         {
13712           /* Deduces in both directions, see if quals can
13713              disambiguate.  Pretend the worse one failed to deduce. */
13714           if ((quals1 & quals2) == quals2)
13715             deduce1 = 0;
13716           if ((quals1 & quals2) == quals1)
13717             deduce2 = 0;
13718         }
13719       if (deduce1 && !deduce2 && !better2)
13720         better2 = 1;
13721       if (deduce2 && !deduce1 && !better1)
13722         better1 = 1;
13723
13724       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13725           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13726         /* We have already processed all of the arguments in our
13727            handing of the pack expansion type.  */
13728         len = 0;
13729
13730       args1 = TREE_CHAIN (args1);
13731       args2 = TREE_CHAIN (args2);
13732
13733       /* Stop when an ellipsis is seen.  */
13734       if (args1 == NULL_TREE || args2 == NULL_TREE)
13735         break;
13736     }
13737
13738   processing_template_decl--;
13739
13740   /* All things being equal, if the next argument is a pack expansion
13741      for one function but not for the other, prefer the
13742      non-variadic function.  */
13743   if ((better1 > 0) - (better2 > 0) == 0
13744       && args1 && TREE_VALUE (args1)
13745       && args2 && TREE_VALUE (args2))
13746     {
13747       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
13748         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
13749       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
13750         return 1;
13751     }
13752
13753   return (better1 > 0) - (better2 > 0);
13754 }
13755
13756 /* Determine which of two partial specializations is more specialized.
13757
13758    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
13759    to the first partial specialization.  The TREE_VALUE is the
13760    innermost set of template parameters for the partial
13761    specialization.  PAT2 is similar, but for the second template.
13762
13763    Return 1 if the first partial specialization is more specialized;
13764    -1 if the second is more specialized; 0 if neither is more
13765    specialized.
13766
13767    See [temp.class.order] for information about determining which of
13768    two templates is more specialized.  */
13769
13770 static int
13771 more_specialized_class (tree pat1, tree pat2)
13772 {
13773   tree targs;
13774   tree tmpl1, tmpl2;
13775   int winner = 0;
13776   bool any_deductions = false;
13777
13778   tmpl1 = TREE_TYPE (pat1);
13779   tmpl2 = TREE_TYPE (pat2);
13780
13781   /* Just like what happens for functions, if we are ordering between
13782      different class template specializations, we may encounter dependent
13783      types in the arguments, and we need our dependency check functions
13784      to behave correctly.  */
13785   ++processing_template_decl;
13786   targs = get_class_bindings (TREE_VALUE (pat1),
13787                               CLASSTYPE_TI_ARGS (tmpl1),
13788                               CLASSTYPE_TI_ARGS (tmpl2));
13789   if (targs)
13790     {
13791       --winner;
13792       any_deductions = true;
13793     }
13794
13795   targs = get_class_bindings (TREE_VALUE (pat2),
13796                               CLASSTYPE_TI_ARGS (tmpl2),
13797                               CLASSTYPE_TI_ARGS (tmpl1));
13798   if (targs)
13799     {
13800       ++winner;
13801       any_deductions = true;
13802     }
13803   --processing_template_decl;
13804
13805   /* In the case of a tie where at least one of the class templates
13806      has a parameter pack at the end, the template with the most
13807      non-packed parameters wins.  */
13808   if (winner == 0
13809       && any_deductions
13810       && (template_args_variadic_p (TREE_PURPOSE (pat1))
13811           || template_args_variadic_p (TREE_PURPOSE (pat2))))
13812     {
13813       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
13814       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
13815       int len1 = TREE_VEC_LENGTH (args1);
13816       int len2 = TREE_VEC_LENGTH (args2);
13817
13818       /* We don't count the pack expansion at the end.  */
13819       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
13820         --len1;
13821       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
13822         --len2;
13823
13824       if (len1 > len2)
13825         return 1;
13826       else if (len1 < len2)
13827         return -1;
13828     }
13829
13830   return winner;
13831 }
13832
13833 /* Return the template arguments that will produce the function signature
13834    DECL from the function template FN, with the explicit template
13835    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
13836    also match.  Return NULL_TREE if no satisfactory arguments could be
13837    found.  */
13838
13839 static tree
13840 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
13841 {
13842   int ntparms = DECL_NTPARMS (fn);
13843   tree targs = make_tree_vec (ntparms);
13844   tree decl_type;
13845   tree decl_arg_types;
13846
13847   /* Substitute the explicit template arguments into the type of DECL.
13848      The call to fn_type_unification will handle substitution into the
13849      FN.  */
13850   decl_type = TREE_TYPE (decl);
13851   if (explicit_args && uses_template_parms (decl_type))
13852     {
13853       tree tmpl;
13854       tree converted_args;
13855
13856       if (DECL_TEMPLATE_INFO (decl))
13857         tmpl = DECL_TI_TEMPLATE (decl);
13858       else
13859         /* We can get here for some invalid specializations.  */
13860         return NULL_TREE;
13861
13862       converted_args
13863         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
13864                                  explicit_args, NULL_TREE,
13865                                  tf_none,
13866                                  /*require_all_args=*/false,
13867                                  /*use_default_args=*/false);
13868       if (converted_args == error_mark_node)
13869         return NULL_TREE;
13870
13871       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
13872       if (decl_type == error_mark_node)
13873         return NULL_TREE;
13874     }
13875
13876   /* Never do unification on the 'this' parameter.  */
13877   decl_arg_types = skip_artificial_parms_for (decl, 
13878                                               TYPE_ARG_TYPES (decl_type));
13879
13880   if (fn_type_unification (fn, explicit_args, targs,
13881                            decl_arg_types,
13882                            (check_rettype || DECL_CONV_FN_P (fn)
13883                             ? TREE_TYPE (decl_type) : NULL_TREE),
13884                            DEDUCE_EXACT, LOOKUP_NORMAL))
13885     return NULL_TREE;
13886
13887   return targs;
13888 }
13889
13890 /* Return the innermost template arguments that, when applied to a
13891    template specialization whose innermost template parameters are
13892    TPARMS, and whose specialization arguments are PARMS, yield the
13893    ARGS.
13894
13895    For example, suppose we have:
13896
13897      template <class T, class U> struct S {};
13898      template <class T> struct S<T*, int> {};
13899
13900    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
13901    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
13902    int}.  The resulting vector will be {double}, indicating that `T'
13903    is bound to `double'.  */
13904
13905 static tree
13906 get_class_bindings (tree tparms, tree spec_args, tree args)
13907 {
13908   int i, ntparms = TREE_VEC_LENGTH (tparms);
13909   tree deduced_args;
13910   tree innermost_deduced_args;
13911
13912   innermost_deduced_args = make_tree_vec (ntparms);
13913   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13914     {
13915       deduced_args = copy_node (args);
13916       SET_TMPL_ARGS_LEVEL (deduced_args,
13917                            TMPL_ARGS_DEPTH (deduced_args),
13918                            innermost_deduced_args);
13919     }
13920   else
13921     deduced_args = innermost_deduced_args;
13922
13923   if (unify (tparms, deduced_args,
13924              INNERMOST_TEMPLATE_ARGS (spec_args),
13925              INNERMOST_TEMPLATE_ARGS (args),
13926              UNIFY_ALLOW_NONE))
13927     return NULL_TREE;
13928
13929   for (i =  0; i < ntparms; ++i)
13930     if (! TREE_VEC_ELT (innermost_deduced_args, i))
13931       return NULL_TREE;
13932
13933   /* Verify that nondeduced template arguments agree with the type
13934      obtained from argument deduction.
13935
13936      For example:
13937
13938        struct A { typedef int X; };
13939        template <class T, class U> struct C {};
13940        template <class T> struct C<T, typename T::X> {};
13941
13942      Then with the instantiation `C<A, int>', we can deduce that
13943      `T' is `A' but unify () does not check whether `typename T::X'
13944      is `int'.  */
13945   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
13946   if (spec_args == error_mark_node
13947       /* We only need to check the innermost arguments; the other
13948          arguments will always agree.  */
13949       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
13950                               INNERMOST_TEMPLATE_ARGS (args)))
13951     return NULL_TREE;
13952
13953   /* Now that we have bindings for all of the template arguments,
13954      ensure that the arguments deduced for the template template
13955      parameters have compatible template parameter lists.  See the use
13956      of template_template_parm_bindings_ok_p in fn_type_unification
13957      for more information.  */
13958   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
13959     return NULL_TREE;
13960
13961   return deduced_args;
13962 }
13963
13964 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
13965    Return the TREE_LIST node with the most specialized template, if
13966    any.  If there is no most specialized template, the error_mark_node
13967    is returned.
13968
13969    Note that this function does not look at, or modify, the
13970    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
13971    returned is one of the elements of INSTANTIATIONS, callers may
13972    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
13973    and retrieve it from the value returned.  */
13974
13975 tree
13976 most_specialized_instantiation (tree templates)
13977 {
13978   tree fn, champ;
13979
13980   ++processing_template_decl;
13981
13982   champ = templates;
13983   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
13984     {
13985       int fate = 0;
13986
13987       if (get_bindings (TREE_VALUE (champ),
13988                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
13989                         NULL_TREE, /*check_ret=*/false))
13990         fate--;
13991
13992       if (get_bindings (TREE_VALUE (fn),
13993                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
13994                         NULL_TREE, /*check_ret=*/false))
13995         fate++;
13996
13997       if (fate == -1)
13998         champ = fn;
13999       else if (!fate)
14000         {
14001           /* Equally specialized, move to next function.  If there
14002              is no next function, nothing's most specialized.  */
14003           fn = TREE_CHAIN (fn);
14004           champ = fn;
14005           if (!fn)
14006             break;
14007         }
14008     }
14009
14010   if (champ)
14011     /* Now verify that champ is better than everything earlier in the
14012        instantiation list.  */
14013     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14014       if (get_bindings (TREE_VALUE (champ),
14015                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14016                         NULL_TREE, /*check_ret=*/false)
14017           || !get_bindings (TREE_VALUE (fn),
14018                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14019                             NULL_TREE, /*check_ret=*/false))
14020         {
14021           champ = NULL_TREE;
14022           break;
14023         }
14024
14025   processing_template_decl--;
14026
14027   if (!champ)
14028     return error_mark_node;
14029
14030   return champ;
14031 }
14032
14033 /* If DECL is a specialization of some template, return the most
14034    general such template.  Otherwise, returns NULL_TREE.
14035
14036    For example, given:
14037
14038      template <class T> struct S { template <class U> void f(U); };
14039
14040    if TMPL is `template <class U> void S<int>::f(U)' this will return
14041    the full template.  This function will not trace past partial
14042    specializations, however.  For example, given in addition:
14043
14044      template <class T> struct S<T*> { template <class U> void f(U); };
14045
14046    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14047    `template <class T> template <class U> S<T*>::f(U)'.  */
14048
14049 tree
14050 most_general_template (tree decl)
14051 {
14052   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14053      an immediate specialization.  */
14054   if (TREE_CODE (decl) == FUNCTION_DECL)
14055     {
14056       if (DECL_TEMPLATE_INFO (decl)) {
14057         decl = DECL_TI_TEMPLATE (decl);
14058
14059         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14060            template friend.  */
14061         if (TREE_CODE (decl) != TEMPLATE_DECL)
14062           return NULL_TREE;
14063       } else
14064         return NULL_TREE;
14065     }
14066
14067   /* Look for more and more general templates.  */
14068   while (DECL_TEMPLATE_INFO (decl))
14069     {
14070       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14071          (See cp-tree.h for details.)  */
14072       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14073         break;
14074
14075       if (CLASS_TYPE_P (TREE_TYPE (decl))
14076           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14077         break;
14078
14079       /* Stop if we run into an explicitly specialized class template.  */
14080       if (!DECL_NAMESPACE_SCOPE_P (decl)
14081           && DECL_CONTEXT (decl)
14082           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14083         break;
14084
14085       decl = DECL_TI_TEMPLATE (decl);
14086     }
14087
14088   return decl;
14089 }
14090
14091 /* Return the most specialized of the class template partial
14092    specializations of TMPL which can produce TYPE, a specialization of
14093    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14094    a _TYPE node corresponding to the partial specialization, while the
14095    TREE_PURPOSE is the set of template arguments that must be
14096    substituted into the TREE_TYPE in order to generate TYPE.
14097
14098    If the choice of partial specialization is ambiguous, a diagnostic
14099    is issued, and the error_mark_node is returned.  If there are no
14100    partial specializations of TMPL matching TYPE, then NULL_TREE is
14101    returned.  */
14102
14103 static tree
14104 most_specialized_class (tree type, tree tmpl)
14105 {
14106   tree list = NULL_TREE;
14107   tree t;
14108   tree champ;
14109   int fate;
14110   bool ambiguous_p;
14111   tree args;
14112   tree outer_args = NULL_TREE;
14113
14114   tmpl = most_general_template (tmpl);
14115   args = CLASSTYPE_TI_ARGS (type);
14116
14117   /* For determining which partial specialization to use, only the
14118      innermost args are interesting.  */
14119   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14120     {
14121       outer_args = strip_innermost_template_args (args, 1);
14122       args = INNERMOST_TEMPLATE_ARGS (args);
14123     }
14124
14125   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14126     {
14127       tree partial_spec_args;
14128       tree spec_args;
14129       tree parms = TREE_VALUE (t);
14130
14131       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14132       if (outer_args)
14133         {
14134           int i;
14135
14136           ++processing_template_decl;
14137
14138           /* Discard the outer levels of args, and then substitute in the
14139              template args from the enclosing class.  */
14140           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14141           partial_spec_args = tsubst_template_args
14142             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14143
14144           /* PARMS already refers to just the innermost parms, but the
14145              template parms in partial_spec_args had their levels lowered
14146              by tsubst, so we need to do the same for the parm list.  We
14147              can't just tsubst the TREE_VEC itself, as tsubst wants to
14148              treat a TREE_VEC as an argument vector.  */
14149           parms = copy_node (parms);
14150           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14151             TREE_VEC_ELT (parms, i) =
14152               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14153
14154           --processing_template_decl;
14155         }
14156       spec_args = get_class_bindings (parms,
14157                                       partial_spec_args,
14158                                       args);
14159       if (spec_args)
14160         {
14161           if (outer_args)
14162             spec_args = add_to_template_args (outer_args, spec_args);
14163           list = tree_cons (spec_args, TREE_VALUE (t), list);
14164           TREE_TYPE (list) = TREE_TYPE (t);
14165         }
14166     }
14167
14168   if (! list)
14169     return NULL_TREE;
14170
14171   ambiguous_p = false;
14172   t = list;
14173   champ = t;
14174   t = TREE_CHAIN (t);
14175   for (; t; t = TREE_CHAIN (t))
14176     {
14177       fate = more_specialized_class (champ, t);
14178       if (fate == 1)
14179         ;
14180       else
14181         {
14182           if (fate == 0)
14183             {
14184               t = TREE_CHAIN (t);
14185               if (! t)
14186                 {
14187                   ambiguous_p = true;
14188                   break;
14189                 }
14190             }
14191           champ = t;
14192         }
14193     }
14194
14195   if (!ambiguous_p)
14196     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14197       {
14198         fate = more_specialized_class (champ, t);
14199         if (fate != 1)
14200           {
14201             ambiguous_p = true;
14202             break;
14203           }
14204       }
14205
14206   if (ambiguous_p)
14207     {
14208       const char *str = "candidates are:";
14209       error ("ambiguous class template instantiation for %q#T", type);
14210       for (t = list; t; t = TREE_CHAIN (t))
14211         {
14212           error ("%s %+#T", str, TREE_TYPE (t));
14213           str = "               ";
14214         }
14215       return error_mark_node;
14216     }
14217
14218   return champ;
14219 }
14220
14221 /* Explicitly instantiate DECL.  */
14222
14223 void
14224 do_decl_instantiation (tree decl, tree storage)
14225 {
14226   tree result = NULL_TREE;
14227   int extern_p = 0;
14228
14229   if (!decl || decl == error_mark_node)
14230     /* An error occurred, for which grokdeclarator has already issued
14231        an appropriate message.  */
14232     return;
14233   else if (! DECL_LANG_SPECIFIC (decl))
14234     {
14235       error ("explicit instantiation of non-template %q#D", decl);
14236       return;
14237     }
14238   else if (TREE_CODE (decl) == VAR_DECL)
14239     {
14240       /* There is an asymmetry here in the way VAR_DECLs and
14241          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14242          the latter, the DECL we get back will be marked as a
14243          template instantiation, and the appropriate
14244          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14245          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14246          should handle VAR_DECLs as it currently handles
14247          FUNCTION_DECLs.  */
14248       if (!DECL_CLASS_SCOPE_P (decl))
14249         {
14250           error ("%qD is not a static data member of a class template", decl);
14251           return;
14252         }
14253       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14254       if (!result || TREE_CODE (result) != VAR_DECL)
14255         {
14256           error ("no matching template for %qD found", decl);
14257           return;
14258         }
14259       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14260         {
14261           error ("type %qT for explicit instantiation %qD does not match "
14262                  "declared type %qT", TREE_TYPE (result), decl,
14263                  TREE_TYPE (decl));
14264           return;
14265         }
14266     }
14267   else if (TREE_CODE (decl) != FUNCTION_DECL)
14268     {
14269       error ("explicit instantiation of %q#D", decl);
14270       return;
14271     }
14272   else
14273     result = decl;
14274
14275   /* Check for various error cases.  Note that if the explicit
14276      instantiation is valid the RESULT will currently be marked as an
14277      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
14278      until we get here.  */
14279
14280   if (DECL_TEMPLATE_SPECIALIZATION (result))
14281     {
14282       /* DR 259 [temp.spec].
14283
14284          Both an explicit instantiation and a declaration of an explicit
14285          specialization shall not appear in a program unless the explicit
14286          instantiation follows a declaration of the explicit specialization.
14287
14288          For a given set of template parameters, if an explicit
14289          instantiation of a template appears after a declaration of an
14290          explicit specialization for that template, the explicit
14291          instantiation has no effect.  */
14292       return;
14293     }
14294   else if (DECL_EXPLICIT_INSTANTIATION (result))
14295     {
14296       /* [temp.spec]
14297
14298          No program shall explicitly instantiate any template more
14299          than once.
14300
14301          We check DECL_NOT_REALLY_EXTERN so as not to complain when
14302          the first instantiation was `extern' and the second is not,
14303          and EXTERN_P for the opposite case.  */
14304       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
14305         pedwarn ("duplicate explicit instantiation of %q#D", result);
14306       /* If an "extern" explicit instantiation follows an ordinary
14307          explicit instantiation, the template is instantiated.  */
14308       if (extern_p)
14309         return;
14310     }
14311   else if (!DECL_IMPLICIT_INSTANTIATION (result))
14312     {
14313       error ("no matching template for %qD found", result);
14314       return;
14315     }
14316   else if (!DECL_TEMPLATE_INFO (result))
14317     {
14318       pedwarn ("explicit instantiation of non-template %q#D", result);
14319       return;
14320     }
14321
14322   if (storage == NULL_TREE)
14323     ;
14324   else if (storage == ridpointers[(int) RID_EXTERN])
14325     {
14326       if (pedantic && !in_system_header)
14327         pedwarn ("ISO C++ forbids the use of %<extern%> on explicit "
14328                  "instantiations");
14329       extern_p = 1;
14330     }
14331   else
14332     error ("storage class %qD applied to template instantiation", storage);
14333
14334   check_explicit_instantiation_namespace (result);
14335   mark_decl_instantiated (result, extern_p);
14336   if (! extern_p)
14337     instantiate_decl (result, /*defer_ok=*/1,
14338                       /*expl_inst_class_mem_p=*/false);
14339 }
14340
14341 static void
14342 mark_class_instantiated (tree t, int extern_p)
14343 {
14344   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
14345   SET_CLASSTYPE_INTERFACE_KNOWN (t);
14346   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
14347   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
14348   if (! extern_p)
14349     {
14350       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
14351       rest_of_type_compilation (t, 1);
14352     }
14353 }
14354
14355 /* Called from do_type_instantiation through binding_table_foreach to
14356    do recursive instantiation for the type bound in ENTRY.  */
14357 static void
14358 bt_instantiate_type_proc (binding_entry entry, void *data)
14359 {
14360   tree storage = *(tree *) data;
14361
14362   if (IS_AGGR_TYPE (entry->type)
14363       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
14364     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
14365 }
14366
14367 /* Called from do_type_instantiation to instantiate a member
14368    (a member function or a static member variable) of an
14369    explicitly instantiated class template.  */
14370 static void
14371 instantiate_class_member (tree decl, int extern_p)
14372 {
14373   mark_decl_instantiated (decl, extern_p);
14374   if (! extern_p)
14375     instantiate_decl (decl, /*defer_ok=*/1,
14376                       /*expl_inst_class_mem_p=*/true);
14377 }
14378
14379 /* Perform an explicit instantiation of template class T.  STORAGE, if
14380    non-null, is the RID for extern, inline or static.  COMPLAIN is
14381    nonzero if this is called from the parser, zero if called recursively,
14382    since the standard is unclear (as detailed below).  */
14383
14384 void
14385 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
14386 {
14387   int extern_p = 0;
14388   int nomem_p = 0;
14389   int static_p = 0;
14390   int previous_instantiation_extern_p = 0;
14391
14392   if (TREE_CODE (t) == TYPE_DECL)
14393     t = TREE_TYPE (t);
14394
14395   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
14396     {
14397       error ("explicit instantiation of non-template type %qT", t);
14398       return;
14399     }
14400
14401   complete_type (t);
14402
14403   if (!COMPLETE_TYPE_P (t))
14404     {
14405       if (complain & tf_error)
14406         error ("explicit instantiation of %q#T before definition of template",
14407                t);
14408       return;
14409     }
14410
14411   if (storage != NULL_TREE)
14412     {
14413       if (pedantic && !in_system_header)
14414         pedwarn("ISO C++ forbids the use of %qE on explicit instantiations",
14415                 storage);
14416
14417       if (storage == ridpointers[(int) RID_INLINE])
14418         nomem_p = 1;
14419       else if (storage == ridpointers[(int) RID_EXTERN])
14420         extern_p = 1;
14421       else if (storage == ridpointers[(int) RID_STATIC])
14422         static_p = 1;
14423       else
14424         {
14425           error ("storage class %qD applied to template instantiation",
14426                  storage);
14427           extern_p = 0;
14428         }
14429     }
14430
14431   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
14432     {
14433       /* DR 259 [temp.spec].
14434
14435          Both an explicit instantiation and a declaration of an explicit
14436          specialization shall not appear in a program unless the explicit
14437          instantiation follows a declaration of the explicit specialization.
14438
14439          For a given set of template parameters, if an explicit
14440          instantiation of a template appears after a declaration of an
14441          explicit specialization for that template, the explicit
14442          instantiation has no effect.  */
14443       return;
14444     }
14445   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
14446     {
14447       /* [temp.spec]
14448
14449          No program shall explicitly instantiate any template more
14450          than once.
14451
14452          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
14453          instantiation was `extern'.  If EXTERN_P then the second is.
14454          These cases are OK.  */
14455       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
14456
14457       if (!previous_instantiation_extern_p && !extern_p
14458           && (complain & tf_error))
14459         pedwarn ("duplicate explicit instantiation of %q#T", t);
14460
14461       /* If we've already instantiated the template, just return now.  */
14462       if (!CLASSTYPE_INTERFACE_ONLY (t))
14463         return;
14464     }
14465
14466   check_explicit_instantiation_namespace (TYPE_NAME (t));
14467   mark_class_instantiated (t, extern_p);
14468
14469   if (nomem_p)
14470     return;
14471
14472   {
14473     tree tmp;
14474
14475     /* In contrast to implicit instantiation, where only the
14476        declarations, and not the definitions, of members are
14477        instantiated, we have here:
14478
14479          [temp.explicit]
14480
14481          The explicit instantiation of a class template specialization
14482          implies the instantiation of all of its members not
14483          previously explicitly specialized in the translation unit
14484          containing the explicit instantiation.
14485
14486        Of course, we can't instantiate member template classes, since
14487        we don't have any arguments for them.  Note that the standard
14488        is unclear on whether the instantiation of the members are
14489        *explicit* instantiations or not.  However, the most natural
14490        interpretation is that it should be an explicit instantiation.  */
14491
14492     if (! static_p)
14493       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
14494         if (TREE_CODE (tmp) == FUNCTION_DECL
14495             && DECL_TEMPLATE_INSTANTIATION (tmp))
14496           instantiate_class_member (tmp, extern_p);
14497
14498     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
14499       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
14500         instantiate_class_member (tmp, extern_p);
14501
14502     if (CLASSTYPE_NESTED_UTDS (t))
14503       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
14504                              bt_instantiate_type_proc, &storage);
14505   }
14506 }
14507
14508 /* Given a function DECL, which is a specialization of TMPL, modify
14509    DECL to be a re-instantiation of TMPL with the same template
14510    arguments.  TMPL should be the template into which tsubst'ing
14511    should occur for DECL, not the most general template.
14512
14513    One reason for doing this is a scenario like this:
14514
14515      template <class T>
14516      void f(const T&, int i);
14517
14518      void g() { f(3, 7); }
14519
14520      template <class T>
14521      void f(const T& t, const int i) { }
14522
14523    Note that when the template is first instantiated, with
14524    instantiate_template, the resulting DECL will have no name for the
14525    first parameter, and the wrong type for the second.  So, when we go
14526    to instantiate the DECL, we regenerate it.  */
14527
14528 static void
14529 regenerate_decl_from_template (tree decl, tree tmpl)
14530 {
14531   /* The arguments used to instantiate DECL, from the most general
14532      template.  */
14533   tree args;
14534   tree code_pattern;
14535
14536   args = DECL_TI_ARGS (decl);
14537   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
14538
14539   /* Make sure that we can see identifiers, and compute access
14540      correctly.  */
14541   push_access_scope (decl);
14542
14543   if (TREE_CODE (decl) == FUNCTION_DECL)
14544     {
14545       tree decl_parm;
14546       tree pattern_parm;
14547       tree specs;
14548       int args_depth;
14549       int parms_depth;
14550
14551       args_depth = TMPL_ARGS_DEPTH (args);
14552       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
14553       if (args_depth > parms_depth)
14554         args = get_innermost_template_args (args, parms_depth);
14555
14556       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
14557                                               args, tf_error, NULL_TREE);
14558       if (specs)
14559         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
14560                                                     specs);
14561
14562       /* Merge parameter declarations.  */
14563       decl_parm = skip_artificial_parms_for (decl,
14564                                              DECL_ARGUMENTS (decl));
14565       pattern_parm
14566         = skip_artificial_parms_for (code_pattern,
14567                                      DECL_ARGUMENTS (code_pattern));
14568       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
14569         {
14570           tree parm_type;
14571           tree attributes;
14572           
14573           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14574             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
14575           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
14576                               NULL_TREE);
14577           parm_type = type_decays_to (parm_type);
14578           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14579             TREE_TYPE (decl_parm) = parm_type;
14580           attributes = DECL_ATTRIBUTES (pattern_parm);
14581           if (DECL_ATTRIBUTES (decl_parm) != attributes)
14582             {
14583               DECL_ATTRIBUTES (decl_parm) = attributes;
14584               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14585             }
14586           decl_parm = TREE_CHAIN (decl_parm);
14587           pattern_parm = TREE_CHAIN (pattern_parm);
14588         }
14589       /* Merge any parameters that match with the function parameter
14590          pack.  */
14591       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
14592         {
14593           int i, len;
14594           tree expanded_types;
14595           /* Expand the TYPE_PACK_EXPANSION that provides the types for
14596              the parameters in this function parameter pack.  */
14597           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
14598                                                  args, tf_error, NULL_TREE);
14599           len = TREE_VEC_LENGTH (expanded_types);
14600           for (i = 0; i < len; i++)
14601             {
14602               tree parm_type;
14603               tree attributes;
14604           
14605               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14606                 /* Rename the parameter to include the index.  */
14607                 DECL_NAME (decl_parm) = 
14608                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
14609               parm_type = TREE_VEC_ELT (expanded_types, i);
14610               parm_type = type_decays_to (parm_type);
14611               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14612                 TREE_TYPE (decl_parm) = parm_type;
14613               attributes = DECL_ATTRIBUTES (pattern_parm);
14614               if (DECL_ATTRIBUTES (decl_parm) != attributes)
14615                 {
14616                   DECL_ATTRIBUTES (decl_parm) = attributes;
14617                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14618                 }
14619               decl_parm = TREE_CHAIN (decl_parm);
14620             }
14621         }
14622       /* Merge additional specifiers from the CODE_PATTERN.  */
14623       if (DECL_DECLARED_INLINE_P (code_pattern)
14624           && !DECL_DECLARED_INLINE_P (decl))
14625         DECL_DECLARED_INLINE_P (decl) = 1;
14626       if (DECL_INLINE (code_pattern) && !DECL_INLINE (decl))
14627         DECL_INLINE (decl) = 1;
14628     }
14629   else if (TREE_CODE (decl) == VAR_DECL)
14630     DECL_INITIAL (decl) =
14631       tsubst_expr (DECL_INITIAL (code_pattern), args,
14632                    tf_error, DECL_TI_TEMPLATE (decl),
14633                    /*integral_constant_expression_p=*/false);
14634   else
14635     gcc_unreachable ();
14636
14637   pop_access_scope (decl);
14638 }
14639
14640 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
14641    substituted to get DECL.  */
14642
14643 tree
14644 template_for_substitution (tree decl)
14645 {
14646   tree tmpl = DECL_TI_TEMPLATE (decl);
14647
14648   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
14649      for the instantiation.  This is not always the most general
14650      template.  Consider, for example:
14651
14652         template <class T>
14653         struct S { template <class U> void f();
14654                    template <> void f<int>(); };
14655
14656      and an instantiation of S<double>::f<int>.  We want TD to be the
14657      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
14658   while (/* An instantiation cannot have a definition, so we need a
14659             more general template.  */
14660          DECL_TEMPLATE_INSTANTIATION (tmpl)
14661            /* We must also deal with friend templates.  Given:
14662
14663                 template <class T> struct S {
14664                   template <class U> friend void f() {};
14665                 };
14666
14667               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
14668               so far as the language is concerned, but that's still
14669               where we get the pattern for the instantiation from.  On
14670               other hand, if the definition comes outside the class, say:
14671
14672                 template <class T> struct S {
14673                   template <class U> friend void f();
14674                 };
14675                 template <class U> friend void f() {}
14676
14677               we don't need to look any further.  That's what the check for
14678               DECL_INITIAL is for.  */
14679           || (TREE_CODE (decl) == FUNCTION_DECL
14680               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
14681               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
14682     {
14683       /* The present template, TD, should not be a definition.  If it
14684          were a definition, we should be using it!  Note that we
14685          cannot restructure the loop to just keep going until we find
14686          a template with a definition, since that might go too far if
14687          a specialization was declared, but not defined.  */
14688       gcc_assert (TREE_CODE (decl) != VAR_DECL
14689                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
14690
14691       /* Fetch the more general template.  */
14692       tmpl = DECL_TI_TEMPLATE (tmpl);
14693     }
14694
14695   return tmpl;
14696 }
14697
14698 /* Produce the definition of D, a _DECL generated from a template.  If
14699    DEFER_OK is nonzero, then we don't have to actually do the
14700    instantiation now; we just have to do it sometime.  Normally it is
14701    an error if this is an explicit instantiation but D is undefined.
14702    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
14703    explicitly instantiated class template.  */
14704
14705 tree
14706 instantiate_decl (tree d, int defer_ok,
14707                   bool expl_inst_class_mem_p)
14708 {
14709   tree tmpl = DECL_TI_TEMPLATE (d);
14710   tree gen_args;
14711   tree args;
14712   tree td;
14713   tree code_pattern;
14714   tree spec;
14715   tree gen_tmpl;
14716   bool pattern_defined;
14717   int need_push;
14718   location_t saved_loc = input_location;
14719   int saved_in_system_header = in_system_header;
14720   bool external_p;
14721
14722   /* This function should only be used to instantiate templates for
14723      functions and static member variables.  */
14724   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
14725               || TREE_CODE (d) == VAR_DECL);
14726
14727   /* Variables are never deferred; if instantiation is required, they
14728      are instantiated right away.  That allows for better code in the
14729      case that an expression refers to the value of the variable --
14730      if the variable has a constant value the referring expression can
14731      take advantage of that fact.  */
14732   if (TREE_CODE (d) == VAR_DECL)
14733     defer_ok = 0;
14734
14735   /* Don't instantiate cloned functions.  Instead, instantiate the
14736      functions they cloned.  */
14737   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
14738     d = DECL_CLONED_FUNCTION (d);
14739
14740   if (DECL_TEMPLATE_INSTANTIATED (d))
14741     /* D has already been instantiated.  It might seem reasonable to
14742        check whether or not D is an explicit instantiation, and, if so,
14743        stop here.  But when an explicit instantiation is deferred
14744        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
14745        is set, even though we still need to do the instantiation.  */
14746     return d;
14747
14748   /* If we already have a specialization of this declaration, then
14749      there's no reason to instantiate it.  Note that
14750      retrieve_specialization gives us both instantiations and
14751      specializations, so we must explicitly check
14752      DECL_TEMPLATE_SPECIALIZATION.  */
14753   gen_tmpl = most_general_template (tmpl);
14754   gen_args = DECL_TI_ARGS (d);
14755   spec = retrieve_specialization (gen_tmpl, gen_args,
14756                                   /*class_specializations_p=*/false);
14757   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
14758     return spec;
14759
14760   /* This needs to happen before any tsubsting.  */
14761   if (! push_tinst_level (d))
14762     return d;
14763
14764   timevar_push (TV_PARSE);
14765
14766   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
14767      for the instantiation.  */
14768   td = template_for_substitution (d);
14769   code_pattern = DECL_TEMPLATE_RESULT (td);
14770
14771   /* We should never be trying to instantiate a member of a class
14772      template or partial specialization.  */
14773   gcc_assert (d != code_pattern);
14774
14775   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
14776       || DECL_TEMPLATE_SPECIALIZATION (td))
14777     /* In the case of a friend template whose definition is provided
14778        outside the class, we may have too many arguments.  Drop the
14779        ones we don't need.  The same is true for specializations.  */
14780     args = get_innermost_template_args
14781       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
14782   else
14783     args = gen_args;
14784
14785   if (TREE_CODE (d) == FUNCTION_DECL)
14786     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
14787   else
14788     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
14789
14790   /* We may be in the middle of deferred access check.  Disable it now.  */
14791   push_deferring_access_checks (dk_no_deferred);
14792
14793   /* Unless an explicit instantiation directive has already determined
14794      the linkage of D, remember that a definition is available for
14795      this entity.  */
14796   if (pattern_defined
14797       && !DECL_INTERFACE_KNOWN (d)
14798       && !DECL_NOT_REALLY_EXTERN (d))
14799     mark_definable (d);
14800
14801   input_location = DECL_SOURCE_LOCATION (d);
14802   in_system_header = DECL_IN_SYSTEM_HEADER (d);
14803
14804   /* If D is a member of an explicitly instantiated class template,
14805      and no definition is available, treat it like an implicit
14806      instantiation.  */
14807   if (!pattern_defined && expl_inst_class_mem_p
14808       && DECL_EXPLICIT_INSTANTIATION (d))
14809     {
14810       DECL_NOT_REALLY_EXTERN (d) = 0;
14811       DECL_INTERFACE_KNOWN (d) = 0;
14812       SET_DECL_IMPLICIT_INSTANTIATION (d);
14813     }
14814
14815   if (!defer_ok)
14816     {
14817       /* Recheck the substitutions to obtain any warning messages
14818          about ignoring cv qualifiers.  */
14819       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
14820       tree type = TREE_TYPE (gen);
14821
14822       /* Make sure that we can see identifiers, and compute access
14823          correctly.  D is already the target FUNCTION_DECL with the
14824          right context.  */
14825       push_access_scope (d);
14826
14827       if (TREE_CODE (gen) == FUNCTION_DECL)
14828         {
14829           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
14830           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
14831                                           d);
14832           /* Don't simply tsubst the function type, as that will give
14833              duplicate warnings about poor parameter qualifications.
14834              The function arguments are the same as the decl_arguments
14835              without the top level cv qualifiers.  */
14836           type = TREE_TYPE (type);
14837         }
14838       tsubst (type, gen_args, tf_warning_or_error, d);
14839
14840       pop_access_scope (d);
14841     }
14842
14843   /* Check to see whether we know that this template will be
14844      instantiated in some other file, as with "extern template"
14845      extension.  */
14846   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
14847   /* In general, we do not instantiate such templates...  */
14848   if (external_p
14849       /* ... but we instantiate inline functions so that we can inline
14850          them and ... */
14851       && ! (TREE_CODE (d) == FUNCTION_DECL && DECL_INLINE (d))
14852       /* ... we instantiate static data members whose values are
14853          needed in integral constant expressions.  */
14854       && ! (TREE_CODE (d) == VAR_DECL
14855             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
14856     goto out;
14857   /* Defer all other templates, unless we have been explicitly
14858      forbidden from doing so.  */
14859   if (/* If there is no definition, we cannot instantiate the
14860          template.  */
14861       ! pattern_defined
14862       /* If it's OK to postpone instantiation, do so.  */
14863       || defer_ok
14864       /* If this is a static data member that will be defined
14865          elsewhere, we don't want to instantiate the entire data
14866          member, but we do want to instantiate the initializer so that
14867          we can substitute that elsewhere.  */
14868       || (external_p && TREE_CODE (d) == VAR_DECL))
14869     {
14870       /* The definition of the static data member is now required so
14871          we must substitute the initializer.  */
14872       if (TREE_CODE (d) == VAR_DECL
14873           && !DECL_INITIAL (d)
14874           && DECL_INITIAL (code_pattern))
14875         {
14876           tree ns;
14877           tree init;
14878
14879           ns = decl_namespace_context (d);
14880           push_nested_namespace (ns);
14881           push_nested_class (DECL_CONTEXT (d));
14882           init = tsubst_expr (DECL_INITIAL (code_pattern),
14883                               args,
14884                               tf_warning_or_error, NULL_TREE,
14885                               /*integral_constant_expression_p=*/false);
14886           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
14887                           /*asmspec_tree=*/NULL_TREE,
14888                           LOOKUP_ONLYCONVERTING);
14889           pop_nested_class ();
14890           pop_nested_namespace (ns);
14891         }
14892
14893       /* We restore the source position here because it's used by
14894          add_pending_template.  */
14895       input_location = saved_loc;
14896
14897       if (at_eof && !pattern_defined
14898           && DECL_EXPLICIT_INSTANTIATION (d))
14899         /* [temp.explicit]
14900
14901            The definition of a non-exported function template, a
14902            non-exported member function template, or a non-exported
14903            member function or static data member of a class template
14904            shall be present in every translation unit in which it is
14905            explicitly instantiated.  */
14906         pedwarn
14907           ("explicit instantiation of %qD but no definition available", d);
14908
14909       /* ??? Historically, we have instantiated inline functions, even
14910          when marked as "extern template".  */
14911       if (!(external_p && TREE_CODE (d) == VAR_DECL))
14912         add_pending_template (d);
14913       goto out;
14914     }
14915   /* Tell the repository that D is available in this translation unit
14916      -- and see if it is supposed to be instantiated here.  */
14917   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
14918     {
14919       /* In a PCH file, despite the fact that the repository hasn't
14920          requested instantiation in the PCH it is still possible that
14921          an instantiation will be required in a file that includes the
14922          PCH.  */
14923       if (pch_file)
14924         add_pending_template (d);
14925       /* Instantiate inline functions so that the inliner can do its
14926          job, even though we'll not be emitting a copy of this
14927          function.  */
14928       if (!(TREE_CODE (d) == FUNCTION_DECL
14929             && flag_inline_trees
14930             && DECL_DECLARED_INLINE_P (d)))
14931         goto out;
14932     }
14933
14934   need_push = !cfun || !global_bindings_p ();
14935   if (need_push)
14936     push_to_top_level ();
14937
14938   /* Mark D as instantiated so that recursive calls to
14939      instantiate_decl do not try to instantiate it again.  */
14940   DECL_TEMPLATE_INSTANTIATED (d) = 1;
14941
14942   /* Regenerate the declaration in case the template has been modified
14943      by a subsequent redeclaration.  */
14944   regenerate_decl_from_template (d, td);
14945
14946   /* We already set the file and line above.  Reset them now in case
14947      they changed as a result of calling regenerate_decl_from_template.  */
14948   input_location = DECL_SOURCE_LOCATION (d);
14949
14950   if (TREE_CODE (d) == VAR_DECL)
14951     {
14952       tree init;
14953
14954       /* Clear out DECL_RTL; whatever was there before may not be right
14955          since we've reset the type of the declaration.  */
14956       SET_DECL_RTL (d, NULL_RTX);
14957       DECL_IN_AGGR_P (d) = 0;
14958
14959       /* The initializer is placed in DECL_INITIAL by
14960          regenerate_decl_from_template.  Pull it out so that
14961          finish_decl can process it.  */
14962       init = DECL_INITIAL (d);
14963       DECL_INITIAL (d) = NULL_TREE;
14964       DECL_INITIALIZED_P (d) = 0;
14965
14966       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
14967          initializer.  That function will defer actual emission until
14968          we have a chance to determine linkage.  */
14969       DECL_EXTERNAL (d) = 0;
14970
14971       /* Enter the scope of D so that access-checking works correctly.  */
14972       push_nested_class (DECL_CONTEXT (d));
14973       finish_decl (d, init, NULL_TREE);
14974       pop_nested_class ();
14975     }
14976   else if (TREE_CODE (d) == FUNCTION_DECL)
14977     {
14978       htab_t saved_local_specializations;
14979       tree subst_decl;
14980       tree tmpl_parm;
14981       tree spec_parm;
14982
14983       /* Save away the current list, in case we are instantiating one
14984          template from within the body of another.  */
14985       saved_local_specializations = local_specializations;
14986
14987       /* Set up the list of local specializations.  */
14988       local_specializations = htab_create (37,
14989                                            hash_local_specialization,
14990                                            eq_local_specializations,
14991                                            NULL);
14992
14993       /* Set up context.  */
14994       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
14995
14996       /* Create substitution entries for the parameters.  */
14997       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
14998       tmpl_parm = DECL_ARGUMENTS (subst_decl);
14999       spec_parm = DECL_ARGUMENTS (d);
15000       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15001         {
15002           register_local_specialization (spec_parm, tmpl_parm);
15003           spec_parm = skip_artificial_parms_for (d, spec_parm);
15004           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15005         }
15006       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15007         {
15008           register_local_specialization (spec_parm, tmpl_parm);
15009           tmpl_parm = TREE_CHAIN (tmpl_parm);
15010           spec_parm = TREE_CHAIN (spec_parm);
15011         }
15012       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15013         {
15014           /* Collect all of the extra "packed" parameters into an
15015              argument pack.  */
15016           tree parmvec;
15017           tree parmtypevec;
15018           tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
15019           tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
15020           int i, len = 0;
15021           tree t;
15022           
15023           /* Count how many parameters remain.  */
15024           for (t = spec_parm; t; t = TREE_CHAIN (t))
15025             len++;
15026
15027           /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
15028           parmvec = make_tree_vec (len);
15029           parmtypevec = make_tree_vec (len);
15030           for(i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
15031             {
15032               TREE_VEC_ELT (parmvec, i) = spec_parm;
15033               TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
15034             }
15035
15036           /* Build the argument packs.  */
15037           SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
15038           SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
15039           TREE_TYPE (argpack) = argtypepack;
15040           
15041           /* Register the (value) argument pack as a specialization of
15042              TMPL_PARM, then move on.  */
15043           register_local_specialization (argpack, tmpl_parm);
15044           tmpl_parm = TREE_CHAIN (tmpl_parm);
15045         }
15046       gcc_assert (!spec_parm);
15047
15048       /* Substitute into the body of the function.  */
15049       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15050                    tf_warning_or_error, tmpl,
15051                    /*integral_constant_expression_p=*/false);
15052
15053       /* Set the current input_location to the end of the function
15054          so that finish_function knows where we are.  */
15055       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15056
15057       /* We don't need the local specializations any more.  */
15058       htab_delete (local_specializations);
15059       local_specializations = saved_local_specializations;
15060
15061       /* Finish the function.  */
15062       d = finish_function (0);
15063       expand_or_defer_fn (d);
15064     }
15065
15066   /* We're not deferring instantiation any more.  */
15067   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15068
15069   if (need_push)
15070     pop_from_top_level ();
15071
15072 out:
15073   input_location = saved_loc;
15074   in_system_header = saved_in_system_header;
15075   pop_deferring_access_checks ();
15076   pop_tinst_level ();
15077
15078   timevar_pop (TV_PARSE);
15079
15080   return d;
15081 }
15082
15083 /* Run through the list of templates that we wish we could
15084    instantiate, and instantiate any we can.  RETRIES is the
15085    number of times we retry pending template instantiation.  */
15086
15087 void
15088 instantiate_pending_templates (int retries)
15089 {
15090   int reconsider;
15091   location_t saved_loc = input_location;
15092   int saved_in_system_header = in_system_header;
15093
15094   /* Instantiating templates may trigger vtable generation.  This in turn
15095      may require further template instantiations.  We place a limit here
15096      to avoid infinite loop.  */
15097   if (pending_templates && retries >= max_tinst_depth)
15098     {
15099       tree decl = pending_templates->tinst->decl;
15100
15101       error ("template instantiation depth exceeds maximum of %d"
15102              " instantiating %q+D, possibly from virtual table generation"
15103              " (use -ftemplate-depth-NN to increase the maximum)",
15104              max_tinst_depth, decl);
15105       if (TREE_CODE (decl) == FUNCTION_DECL)
15106         /* Pretend that we defined it.  */
15107         DECL_INITIAL (decl) = error_mark_node;
15108       return;
15109     }
15110
15111   do
15112     {
15113       struct pending_template **t = &pending_templates;
15114       struct pending_template *last = NULL;
15115       reconsider = 0;
15116       while (*t)
15117         {
15118           tree instantiation = reopen_tinst_level ((*t)->tinst);
15119           bool complete = false;
15120
15121           if (TYPE_P (instantiation))
15122             {
15123               tree fn;
15124
15125               if (!COMPLETE_TYPE_P (instantiation))
15126                 {
15127                   instantiate_class_template (instantiation);
15128                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15129                     for (fn = TYPE_METHODS (instantiation);
15130                          fn;
15131                          fn = TREE_CHAIN (fn))
15132                       if (! DECL_ARTIFICIAL (fn))
15133                         instantiate_decl (fn,
15134                                           /*defer_ok=*/0,
15135                                           /*expl_inst_class_mem_p=*/false);
15136                   if (COMPLETE_TYPE_P (instantiation))
15137                     reconsider = 1;
15138                 }
15139
15140               complete = COMPLETE_TYPE_P (instantiation);
15141             }
15142           else
15143             {
15144               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15145                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15146                 {
15147                   instantiation
15148                     = instantiate_decl (instantiation,
15149                                         /*defer_ok=*/0,
15150                                         /*expl_inst_class_mem_p=*/false);
15151                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15152                     reconsider = 1;
15153                 }
15154
15155               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15156                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15157             }
15158
15159           if (complete)
15160             /* If INSTANTIATION has been instantiated, then we don't
15161                need to consider it again in the future.  */
15162             *t = (*t)->next;
15163           else
15164             {
15165               last = *t;
15166               t = &(*t)->next;
15167             }
15168           tinst_depth = 0;
15169           current_tinst_level = NULL;
15170         }
15171       last_pending_template = last;
15172     }
15173   while (reconsider);
15174
15175   input_location = saved_loc;
15176   in_system_header = saved_in_system_header;
15177 }
15178
15179 /* Substitute ARGVEC into T, which is a list of initializers for
15180    either base class or a non-static data member.  The TREE_PURPOSEs
15181    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15182    instantiate_decl.  */
15183
15184 static tree
15185 tsubst_initializer_list (tree t, tree argvec)
15186 {
15187   tree inits = NULL_TREE;
15188
15189   for (; t; t = TREE_CHAIN (t))
15190     {
15191       tree decl;
15192       tree init;
15193       tree expanded_bases = NULL_TREE;
15194       tree expanded_arguments = NULL_TREE;
15195       int i, len = 1;
15196
15197       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15198         {
15199           tree expr;
15200           tree arg;
15201
15202           /* Expand the base class expansion type into separate base
15203              classes.  */
15204           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15205                                                  tf_warning_or_error,
15206                                                  NULL_TREE);
15207           if (expanded_bases == error_mark_node)
15208             continue;
15209           
15210           /* We'll be building separate TREE_LISTs of arguments for
15211              each base.  */
15212           len = TREE_VEC_LENGTH (expanded_bases);
15213           expanded_arguments = make_tree_vec (len);
15214           for (i = 0; i < len; i++)
15215             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15216
15217           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15218              expand each argument in the TREE_VALUE of t.  */
15219           expr = make_node (EXPR_PACK_EXPANSION);
15220           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15221             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15222
15223           /* Substitute parameter packs into each argument in the
15224              TREE_LIST.  */
15225           in_base_initializer = 1;
15226           for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15227             {
15228               tree expanded_exprs;
15229
15230               /* Expand the argument.  */
15231               SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15232               expanded_exprs = tsubst_pack_expansion (expr, argvec,
15233                                                       tf_warning_or_error,
15234                                                       NULL_TREE);
15235
15236               /* Prepend each of the expanded expressions to the
15237                  corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15238               for (i = 0; i < len; i++)
15239                 {
15240                   TREE_VEC_ELT (expanded_arguments, i) = 
15241                     tree_cons (NULL_TREE, TREE_VEC_ELT (expanded_exprs, i),
15242                                TREE_VEC_ELT (expanded_arguments, i));
15243                 }
15244             }
15245           in_base_initializer = 0;
15246
15247           /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15248              since we built them backwards.  */
15249           for (i = 0; i < len; i++)
15250             {
15251               TREE_VEC_ELT (expanded_arguments, i) = 
15252                 nreverse (TREE_VEC_ELT (expanded_arguments, i));
15253             }
15254         }
15255
15256       for (i = 0; i < len; ++i)
15257         {
15258           if (expanded_bases)
15259             {
15260               decl = TREE_VEC_ELT (expanded_bases, i);
15261               decl = expand_member_init (decl);
15262               init = TREE_VEC_ELT (expanded_arguments, i);
15263             }
15264           else
15265             {
15266               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15267                                   tf_warning_or_error, NULL_TREE);
15268
15269               decl = expand_member_init (decl);
15270               if (decl && !DECL_P (decl))
15271                 in_base_initializer = 1;
15272
15273               init = tsubst_expr (TREE_VALUE (t), argvec, 
15274                                   tf_warning_or_error, NULL_TREE,
15275                                   /*integral_constant_expression_p=*/false);
15276               in_base_initializer = 0;
15277             }
15278
15279           if (decl)
15280             {
15281               init = build_tree_list (decl, init);
15282               TREE_CHAIN (init) = inits;
15283               inits = init;
15284             }
15285         }
15286     }
15287   return inits;
15288 }
15289
15290 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
15291
15292 static void
15293 set_current_access_from_decl (tree decl)
15294 {
15295   if (TREE_PRIVATE (decl))
15296     current_access_specifier = access_private_node;
15297   else if (TREE_PROTECTED (decl))
15298     current_access_specifier = access_protected_node;
15299   else
15300     current_access_specifier = access_public_node;
15301 }
15302
15303 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
15304    is the instantiation (which should have been created with
15305    start_enum) and ARGS are the template arguments to use.  */
15306
15307 static void
15308 tsubst_enum (tree tag, tree newtag, tree args)
15309 {
15310   tree e;
15311
15312   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
15313     {
15314       tree value;
15315       tree decl;
15316
15317       decl = TREE_VALUE (e);
15318       /* Note that in a template enum, the TREE_VALUE is the
15319          CONST_DECL, not the corresponding INTEGER_CST.  */
15320       value = tsubst_expr (DECL_INITIAL (decl),
15321                            args, tf_warning_or_error, NULL_TREE,
15322                            /*integral_constant_expression_p=*/true);
15323
15324       /* Give this enumeration constant the correct access.  */
15325       set_current_access_from_decl (decl);
15326
15327       /* Actually build the enumerator itself.  */
15328       build_enumerator (DECL_NAME (decl), value, newtag);
15329     }
15330
15331   finish_enum (newtag);
15332   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
15333     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
15334 }
15335
15336 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
15337    its type -- but without substituting the innermost set of template
15338    arguments.  So, innermost set of template parameters will appear in
15339    the type.  */
15340
15341 tree
15342 get_mostly_instantiated_function_type (tree decl)
15343 {
15344   tree fn_type;
15345   tree tmpl;
15346   tree targs;
15347   tree tparms;
15348   int parm_depth;
15349
15350   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15351   targs = DECL_TI_ARGS (decl);
15352   tparms = DECL_TEMPLATE_PARMS (tmpl);
15353   parm_depth = TMPL_PARMS_DEPTH (tparms);
15354
15355   /* There should be as many levels of arguments as there are levels
15356      of parameters.  */
15357   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
15358
15359   fn_type = TREE_TYPE (tmpl);
15360
15361   if (parm_depth == 1)
15362     /* No substitution is necessary.  */
15363     ;
15364   else
15365     {
15366       int i, save_access_control;
15367       tree partial_args;
15368
15369       /* Replace the innermost level of the TARGS with NULL_TREEs to
15370          let tsubst know not to substitute for those parameters.  */
15371       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
15372       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
15373         SET_TMPL_ARGS_LEVEL (partial_args, i,
15374                              TMPL_ARGS_LEVEL (targs, i));
15375       SET_TMPL_ARGS_LEVEL (partial_args,
15376                            TMPL_ARGS_DEPTH (targs),
15377                            make_tree_vec (DECL_NTPARMS (tmpl)));
15378
15379       /* Disable access control as this function is used only during
15380          name-mangling.  */
15381       save_access_control = flag_access_control;
15382       flag_access_control = 0;
15383
15384       ++processing_template_decl;
15385       /* Now, do the (partial) substitution to figure out the
15386          appropriate function type.  */
15387       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
15388       --processing_template_decl;
15389
15390       /* Substitute into the template parameters to obtain the real
15391          innermost set of parameters.  This step is important if the
15392          innermost set of template parameters contains value
15393          parameters whose types depend on outer template parameters.  */
15394       TREE_VEC_LENGTH (partial_args)--;
15395       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
15396
15397       flag_access_control = save_access_control;
15398     }
15399
15400   return fn_type;
15401 }
15402
15403 /* Return truthvalue if we're processing a template different from
15404    the last one involved in diagnostics.  */
15405 int
15406 problematic_instantiation_changed (void)
15407 {
15408   return last_template_error_tick != tinst_level_tick;
15409 }
15410
15411 /* Remember current template involved in diagnostics.  */
15412 void
15413 record_last_problematic_instantiation (void)
15414 {
15415   last_template_error_tick = tinst_level_tick;
15416 }
15417
15418 struct tinst_level *
15419 current_instantiation (void)
15420 {
15421   return current_tinst_level;
15422 }
15423
15424 /* [temp.param] Check that template non-type parm TYPE is of an allowable
15425    type. Return zero for ok, nonzero for disallowed. Issue error and
15426    warning messages under control of COMPLAIN.  */
15427
15428 static int
15429 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
15430 {
15431   if (INTEGRAL_TYPE_P (type))
15432     return 0;
15433   else if (POINTER_TYPE_P (type))
15434     return 0;
15435   else if (TYPE_PTR_TO_MEMBER_P (type))
15436     return 0;
15437   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15438     return 0;
15439   else if (TREE_CODE (type) == TYPENAME_TYPE)
15440     return 0;
15441
15442   if (complain & tf_error)
15443     error ("%q#T is not a valid type for a template constant parameter", type);
15444   return 1;
15445 }
15446
15447 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
15448    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
15449
15450 static bool
15451 dependent_type_p_r (tree type)
15452 {
15453   tree scope;
15454
15455   /* [temp.dep.type]
15456
15457      A type is dependent if it is:
15458
15459      -- a template parameter. Template template parameters are types
15460         for us (since TYPE_P holds true for them) so we handle
15461         them here.  */
15462   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
15463       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
15464     return true;
15465   /* -- a qualified-id with a nested-name-specifier which contains a
15466         class-name that names a dependent type or whose unqualified-id
15467         names a dependent type.  */
15468   if (TREE_CODE (type) == TYPENAME_TYPE)
15469     return true;
15470   /* -- a cv-qualified type where the cv-unqualified type is
15471         dependent.  */
15472   type = TYPE_MAIN_VARIANT (type);
15473   /* -- a compound type constructed from any dependent type.  */
15474   if (TYPE_PTR_TO_MEMBER_P (type))
15475     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
15476             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
15477                                            (type)));
15478   else if (TREE_CODE (type) == POINTER_TYPE
15479            || TREE_CODE (type) == REFERENCE_TYPE)
15480     return dependent_type_p (TREE_TYPE (type));
15481   else if (TREE_CODE (type) == FUNCTION_TYPE
15482            || TREE_CODE (type) == METHOD_TYPE)
15483     {
15484       tree arg_type;
15485
15486       if (dependent_type_p (TREE_TYPE (type)))
15487         return true;
15488       for (arg_type = TYPE_ARG_TYPES (type);
15489            arg_type;
15490            arg_type = TREE_CHAIN (arg_type))
15491         if (dependent_type_p (TREE_VALUE (arg_type)))
15492           return true;
15493       return false;
15494     }
15495   /* -- an array type constructed from any dependent type or whose
15496         size is specified by a constant expression that is
15497         value-dependent.  */
15498   if (TREE_CODE (type) == ARRAY_TYPE)
15499     {
15500       if (TYPE_DOMAIN (type)
15501           && dependent_type_p (TYPE_DOMAIN (type)))
15502         return true;
15503       return dependent_type_p (TREE_TYPE (type));
15504     }
15505   else if (TREE_CODE (type) == INTEGER_TYPE
15506            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
15507     {
15508       /* If this is the TYPE_DOMAIN of an array type, consider it
15509          dependent.  */
15510       return (value_dependent_expression_p (TYPE_MAX_VALUE (type))
15511               || type_dependent_expression_p (TYPE_MAX_VALUE (type)));
15512     }
15513
15514   /* -- a template-id in which either the template name is a template
15515      parameter ...  */
15516   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
15517     return true;
15518   /* ... or any of the template arguments is a dependent type or
15519         an expression that is type-dependent or value-dependent.  */
15520   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
15521            && (any_dependent_template_arguments_p
15522                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
15523     return true;
15524
15525   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
15526      argument of the `typeof' expression is not type-dependent, then
15527      it should already been have resolved.  */
15528   if (TREE_CODE (type) == TYPEOF_TYPE
15529       || TREE_CODE (type) == DECLTYPE_TYPE)
15530     return true;
15531
15532   /* A template argument pack is dependent if any of its packed
15533      arguments are.  */
15534   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
15535     {
15536       tree args = ARGUMENT_PACK_ARGS (type);
15537       int i, len = TREE_VEC_LENGTH (args);
15538       for (i = 0; i < len; ++i)
15539         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
15540           return true;
15541     }
15542
15543   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
15544      be template parameters.  */
15545   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
15546     return true;
15547
15548   /* The standard does not specifically mention types that are local
15549      to template functions or local classes, but they should be
15550      considered dependent too.  For example:
15551
15552        template <int I> void f() {
15553          enum E { a = I };
15554          S<sizeof (E)> s;
15555        }
15556
15557      The size of `E' cannot be known until the value of `I' has been
15558      determined.  Therefore, `E' must be considered dependent.  */
15559   scope = TYPE_CONTEXT (type);
15560   if (scope && TYPE_P (scope))
15561     return dependent_type_p (scope);
15562   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
15563     return type_dependent_expression_p (scope);
15564
15565   /* Other types are non-dependent.  */
15566   return false;
15567 }
15568
15569 /* Returns TRUE if TYPE is dependent, in the sense of
15570    [temp.dep.type].  */
15571
15572 bool
15573 dependent_type_p (tree type)
15574 {
15575   /* If there are no template parameters in scope, then there can't be
15576      any dependent types.  */
15577   if (!processing_template_decl)
15578     {
15579       /* If we are not processing a template, then nobody should be
15580          providing us with a dependent type.  */
15581       gcc_assert (type);
15582       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM);
15583       return false;
15584     }
15585
15586   /* If the type is NULL, we have not computed a type for the entity
15587      in question; in that case, the type is dependent.  */
15588   if (!type)
15589     return true;
15590
15591   /* Erroneous types can be considered non-dependent.  */
15592   if (type == error_mark_node)
15593     return false;
15594
15595   /* If we have not already computed the appropriate value for TYPE,
15596      do so now.  */
15597   if (!TYPE_DEPENDENT_P_VALID (type))
15598     {
15599       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
15600       TYPE_DEPENDENT_P_VALID (type) = 1;
15601     }
15602
15603   return TYPE_DEPENDENT_P (type);
15604 }
15605
15606 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
15607
15608 static bool
15609 dependent_scope_ref_p (tree expression, bool criterion (tree))
15610 {
15611   tree scope;
15612   tree name;
15613
15614   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
15615
15616   if (!TYPE_P (TREE_OPERAND (expression, 0)))
15617     return true;
15618
15619   scope = TREE_OPERAND (expression, 0);
15620   name = TREE_OPERAND (expression, 1);
15621
15622   /* [temp.dep.expr]
15623
15624      An id-expression is type-dependent if it contains a
15625      nested-name-specifier that contains a class-name that names a
15626      dependent type.  */
15627   /* The suggested resolution to Core Issue 2 implies that if the
15628      qualifying type is the current class, then we must peek
15629      inside it.  */
15630   if (DECL_P (name)
15631       && currently_open_class (scope)
15632       && !criterion (name))
15633     return false;
15634   if (dependent_type_p (scope))
15635     return true;
15636
15637   return false;
15638 }
15639
15640 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
15641    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
15642    expression.  */
15643
15644 bool
15645 value_dependent_expression_p (tree expression)
15646 {
15647   if (!processing_template_decl)
15648     return false;
15649
15650   /* A name declared with a dependent type.  */
15651   if (DECL_P (expression) && type_dependent_expression_p (expression))
15652     return true;
15653
15654   switch (TREE_CODE (expression))
15655     {
15656     case IDENTIFIER_NODE:
15657       /* A name that has not been looked up -- must be dependent.  */
15658       return true;
15659
15660     case TEMPLATE_PARM_INDEX:
15661       /* A non-type template parm.  */
15662       return true;
15663
15664     case CONST_DECL:
15665       /* A non-type template parm.  */
15666       if (DECL_TEMPLATE_PARM_P (expression))
15667         return true;
15668       return false;
15669
15670     case VAR_DECL:
15671        /* A constant with integral or enumeration type and is initialized
15672           with an expression that is value-dependent.  */
15673       if (DECL_INITIAL (expression)
15674           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
15675           && value_dependent_expression_p (DECL_INITIAL (expression)))
15676         return true;
15677       return false;
15678
15679     case DYNAMIC_CAST_EXPR:
15680     case STATIC_CAST_EXPR:
15681     case CONST_CAST_EXPR:
15682     case REINTERPRET_CAST_EXPR:
15683     case CAST_EXPR:
15684       /* These expressions are value-dependent if the type to which
15685          the cast occurs is dependent or the expression being casted
15686          is value-dependent.  */
15687       {
15688         tree type = TREE_TYPE (expression);
15689
15690         if (dependent_type_p (type))
15691           return true;
15692
15693         /* A functional cast has a list of operands.  */
15694         expression = TREE_OPERAND (expression, 0);
15695         if (!expression)
15696           {
15697             /* If there are no operands, it must be an expression such
15698                as "int()". This should not happen for aggregate types
15699                because it would form non-constant expressions.  */
15700             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
15701
15702             return false;
15703           }
15704
15705         if (TREE_CODE (expression) == TREE_LIST)
15706           return any_value_dependent_elements_p (expression);
15707
15708         return value_dependent_expression_p (expression);
15709       }
15710
15711     case SIZEOF_EXPR:
15712     case ALIGNOF_EXPR:
15713       /* A `sizeof' expression is value-dependent if the operand is
15714          type-dependent or is a pack expansion.  */
15715       expression = TREE_OPERAND (expression, 0);
15716       if (PACK_EXPANSION_P (expression))
15717         return true;
15718       else if (TYPE_P (expression))
15719         return dependent_type_p (expression);
15720       return type_dependent_expression_p (expression);
15721
15722     case SCOPE_REF:
15723       return dependent_scope_ref_p (expression, value_dependent_expression_p);
15724
15725     case COMPONENT_REF:
15726       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
15727               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
15728
15729     case CALL_EXPR:
15730       /* A CALL_EXPR may appear in a constant expression if it is a
15731          call to a builtin function, e.g., __builtin_constant_p.  All
15732          such calls are value-dependent.  */
15733       return true;
15734
15735     case NONTYPE_ARGUMENT_PACK:
15736       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
15737          is value-dependent.  */
15738       {
15739         tree values = ARGUMENT_PACK_ARGS (expression);
15740         int i, len = TREE_VEC_LENGTH (values);
15741         
15742         for (i = 0; i < len; ++i)
15743           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
15744             return true;
15745         
15746         return false;
15747       }
15748
15749     case TRAIT_EXPR:
15750       {
15751         tree type2 = TRAIT_EXPR_TYPE2 (expression);
15752         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
15753                 || (type2 ? dependent_type_p (type2) : false));
15754       }
15755
15756     case MODOP_EXPR:
15757       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
15758               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
15759
15760     default:
15761       /* A constant expression is value-dependent if any subexpression is
15762          value-dependent.  */
15763       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
15764         {
15765         case tcc_reference:
15766         case tcc_unary:
15767           return (value_dependent_expression_p
15768                   (TREE_OPERAND (expression, 0)));
15769
15770         case tcc_comparison:
15771         case tcc_binary:
15772           return ((value_dependent_expression_p
15773                    (TREE_OPERAND (expression, 0)))
15774                   || (value_dependent_expression_p
15775                       (TREE_OPERAND (expression, 1))));
15776
15777         case tcc_expression:
15778         case tcc_vl_exp:
15779           {
15780             int i;
15781             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
15782               /* In some cases, some of the operands may be missing.
15783                  (For example, in the case of PREDECREMENT_EXPR, the
15784                  amount to increment by may be missing.)  That doesn't
15785                  make the expression dependent.  */
15786               if (TREE_OPERAND (expression, i)
15787                   && (value_dependent_expression_p
15788                       (TREE_OPERAND (expression, i))))
15789                 return true;
15790             return false;
15791           }
15792
15793         default:
15794           break;
15795         }
15796     }
15797
15798   /* The expression is not value-dependent.  */
15799   return false;
15800 }
15801
15802 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
15803    [temp.dep.expr].  */
15804
15805 bool
15806 type_dependent_expression_p (tree expression)
15807 {
15808   if (!processing_template_decl)
15809     return false;
15810
15811   if (expression == error_mark_node)
15812     return false;
15813
15814   /* An unresolved name is always dependent.  */
15815   if (TREE_CODE (expression) == IDENTIFIER_NODE
15816       || TREE_CODE (expression) == USING_DECL)
15817     return true;
15818
15819   /* Some expression forms are never type-dependent.  */
15820   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
15821       || TREE_CODE (expression) == SIZEOF_EXPR
15822       || TREE_CODE (expression) == ALIGNOF_EXPR
15823       || TREE_CODE (expression) == TRAIT_EXPR
15824       || TREE_CODE (expression) == TYPEID_EXPR
15825       || TREE_CODE (expression) == DELETE_EXPR
15826       || TREE_CODE (expression) == VEC_DELETE_EXPR
15827       || TREE_CODE (expression) == THROW_EXPR)
15828     return false;
15829
15830   /* The types of these expressions depends only on the type to which
15831      the cast occurs.  */
15832   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
15833       || TREE_CODE (expression) == STATIC_CAST_EXPR
15834       || TREE_CODE (expression) == CONST_CAST_EXPR
15835       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
15836       || TREE_CODE (expression) == CAST_EXPR)
15837     return dependent_type_p (TREE_TYPE (expression));
15838
15839   /* The types of these expressions depends only on the type created
15840      by the expression.  */
15841   if (TREE_CODE (expression) == NEW_EXPR
15842       || TREE_CODE (expression) == VEC_NEW_EXPR)
15843     {
15844       /* For NEW_EXPR tree nodes created inside a template, either
15845          the object type itself or a TREE_LIST may appear as the
15846          operand 1.  */
15847       tree type = TREE_OPERAND (expression, 1);
15848       if (TREE_CODE (type) == TREE_LIST)
15849         /* This is an array type.  We need to check array dimensions
15850            as well.  */
15851         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
15852                || value_dependent_expression_p
15853                     (TREE_OPERAND (TREE_VALUE (type), 1));
15854       else
15855         return dependent_type_p (type);
15856     }
15857
15858   if (TREE_CODE (expression) == SCOPE_REF
15859       && dependent_scope_ref_p (expression,
15860                                 type_dependent_expression_p))
15861     return true;
15862
15863   if (TREE_CODE (expression) == FUNCTION_DECL
15864       && DECL_LANG_SPECIFIC (expression)
15865       && DECL_TEMPLATE_INFO (expression)
15866       && (any_dependent_template_arguments_p
15867           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
15868     return true;
15869
15870   if (TREE_CODE (expression) == TEMPLATE_DECL
15871       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
15872     return false;
15873
15874   if (TREE_CODE (expression) == STMT_EXPR)
15875     expression = stmt_expr_value_expr (expression);
15876
15877   if (TREE_TYPE (expression) == unknown_type_node)
15878     {
15879       if (TREE_CODE (expression) == ADDR_EXPR)
15880         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
15881       if (TREE_CODE (expression) == COMPONENT_REF
15882           || TREE_CODE (expression) == OFFSET_REF)
15883         {
15884           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
15885             return true;
15886           expression = TREE_OPERAND (expression, 1);
15887           if (TREE_CODE (expression) == IDENTIFIER_NODE)
15888             return false;
15889         }
15890       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
15891       if (TREE_CODE (expression) == SCOPE_REF)
15892         return false;
15893
15894       if (TREE_CODE (expression) == BASELINK)
15895         expression = BASELINK_FUNCTIONS (expression);
15896
15897       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
15898         {
15899           if (any_dependent_template_arguments_p
15900               (TREE_OPERAND (expression, 1)))
15901             return true;
15902           expression = TREE_OPERAND (expression, 0);
15903         }
15904       gcc_assert (TREE_CODE (expression) == OVERLOAD
15905                   || TREE_CODE (expression) == FUNCTION_DECL);
15906
15907       while (expression)
15908         {
15909           if (type_dependent_expression_p (OVL_CURRENT (expression)))
15910             return true;
15911           expression = OVL_NEXT (expression);
15912         }
15913       return false;
15914     }
15915
15916   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
15917
15918   return (dependent_type_p (TREE_TYPE (expression)));
15919 }
15920
15921 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
15922    contains a type-dependent expression.  */
15923
15924 bool
15925 any_type_dependent_arguments_p (const_tree args)
15926 {
15927   while (args)
15928     {
15929       tree arg = TREE_VALUE (args);
15930
15931       if (type_dependent_expression_p (arg))
15932         return true;
15933       args = TREE_CHAIN (args);
15934     }
15935   return false;
15936 }
15937
15938 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
15939    expressions) contains any value-dependent expressions.  */
15940
15941 bool
15942 any_value_dependent_elements_p (const_tree list)
15943 {
15944   for (; list; list = TREE_CHAIN (list))
15945     if (value_dependent_expression_p (TREE_VALUE (list)))
15946       return true;
15947
15948   return false;
15949 }
15950
15951 /* Returns TRUE if the ARG (a template argument) is dependent.  */
15952
15953 bool
15954 dependent_template_arg_p (tree arg)
15955 {
15956   if (!processing_template_decl)
15957     return false;
15958
15959   if (TREE_CODE (arg) == TEMPLATE_DECL
15960       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15961     return dependent_template_p (arg);
15962   else if (ARGUMENT_PACK_P (arg))
15963     {
15964       tree args = ARGUMENT_PACK_ARGS (arg);
15965       int i, len = TREE_VEC_LENGTH (args);
15966       for (i = 0; i < len; ++i)
15967         {
15968           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
15969             return true;
15970         }
15971
15972       return false;
15973     }
15974   else if (TYPE_P (arg))
15975     return dependent_type_p (arg);
15976   else
15977     return (type_dependent_expression_p (arg)
15978             || value_dependent_expression_p (arg));
15979 }
15980
15981 /* Returns true if ARGS (a collection of template arguments) contains
15982    any types that require structural equality testing.  */
15983
15984 bool
15985 any_template_arguments_need_structural_equality_p (tree args)
15986 {
15987   int i;
15988   int j;
15989
15990   if (!args)
15991     return false;
15992   if (args == error_mark_node)
15993     return true;
15994
15995   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
15996     {
15997       tree level = TMPL_ARGS_LEVEL (args, i + 1);
15998       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
15999         {
16000           tree arg = TREE_VEC_ELT (level, j);
16001           tree packed_args = NULL_TREE;
16002           int k, len = 1;
16003
16004           if (ARGUMENT_PACK_P (arg))
16005             {
16006               /* Look inside the argument pack.  */
16007               packed_args = ARGUMENT_PACK_ARGS (arg);
16008               len = TREE_VEC_LENGTH (packed_args);
16009             }
16010
16011           for (k = 0; k < len; ++k)
16012             {
16013               if (packed_args)
16014                 arg = TREE_VEC_ELT (packed_args, k);
16015
16016               if (error_operand_p (arg))
16017                 return true;
16018               else if (TREE_CODE (arg) == TEMPLATE_DECL
16019                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16020                 continue;
16021               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
16022                 return true;
16023               else if (!TYPE_P (arg) && TREE_TYPE (arg)
16024                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
16025                 return true;
16026             }
16027         }
16028     }
16029
16030   return false;
16031 }
16032
16033 /* Returns true if ARGS (a collection of template arguments) contains
16034    any dependent arguments.  */
16035
16036 bool
16037 any_dependent_template_arguments_p (const_tree args)
16038 {
16039   int i;
16040   int j;
16041
16042   if (!args)
16043     return false;
16044   if (args == error_mark_node)
16045     return true;
16046
16047   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16048     {
16049       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16050       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16051         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16052           return true;
16053     }
16054
16055   return false;
16056 }
16057
16058 /* Returns TRUE if the template TMPL is dependent.  */
16059
16060 bool
16061 dependent_template_p (tree tmpl)
16062 {
16063   if (TREE_CODE (tmpl) == OVERLOAD)
16064     {
16065       while (tmpl)
16066         {
16067           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16068             return true;
16069           tmpl = OVL_CHAIN (tmpl);
16070         }
16071       return false;
16072     }
16073
16074   /* Template template parameters are dependent.  */
16075   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16076       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16077     return true;
16078   /* So are names that have not been looked up.  */
16079   if (TREE_CODE (tmpl) == SCOPE_REF
16080       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16081     return true;
16082   /* So are member templates of dependent classes.  */
16083   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16084     return dependent_type_p (DECL_CONTEXT (tmpl));
16085   return false;
16086 }
16087
16088 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16089
16090 bool
16091 dependent_template_id_p (tree tmpl, tree args)
16092 {
16093   return (dependent_template_p (tmpl)
16094           || any_dependent_template_arguments_p (args));
16095 }
16096
16097 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16098    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16099    no such TYPE can be found.  Note that this function peers inside
16100    uninstantiated templates and therefore should be used only in
16101    extremely limited situations.  ONLY_CURRENT_P restricts this
16102    peering to the currently open classes hierarchy (which is required
16103    when comparing types).  */
16104
16105 tree
16106 resolve_typename_type (tree type, bool only_current_p)
16107 {
16108   tree scope;
16109   tree name;
16110   tree decl;
16111   int quals;
16112   tree pushed_scope;
16113   tree result;
16114
16115   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16116
16117   scope = TYPE_CONTEXT (type);
16118   name = TYPE_IDENTIFIER (type);
16119
16120   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16121      it first before we can figure out what NAME refers to.  */
16122   if (TREE_CODE (scope) == TYPENAME_TYPE)
16123     scope = resolve_typename_type (scope, only_current_p);
16124   /* If we don't know what SCOPE refers to, then we cannot resolve the
16125      TYPENAME_TYPE.  */
16126   if (TREE_CODE (scope) == TYPENAME_TYPE)
16127     return type;
16128   /* If the SCOPE is a template type parameter, we have no way of
16129      resolving the name.  */
16130   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16131     return type;
16132   /* If the SCOPE is not the current instantiation, there's no reason
16133      to look inside it.  */
16134   if (only_current_p && !currently_open_class (scope))
16135     return type;
16136   /* If SCOPE isn't the template itself, it will not have a valid
16137      TYPE_FIELDS list.  */
16138   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16139     /* scope is either the template itself or a compatible instantiation
16140        like X<T>, so look up the name in the original template.  */
16141     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16142   else
16143     /* scope is a partial instantiation, so we can't do the lookup or we
16144        will lose the template arguments.  */
16145     return type;
16146   /* Enter the SCOPE so that name lookup will be resolved as if we
16147      were in the class definition.  In particular, SCOPE will no
16148      longer be considered a dependent type.  */
16149   pushed_scope = push_scope (scope);
16150   /* Look up the declaration.  */
16151   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16152
16153   result = NULL_TREE;
16154   
16155   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
16156      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
16157   if (!decl)
16158     /*nop*/;
16159   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
16160            && TREE_CODE (decl) == TYPE_DECL)
16161     {
16162       result = TREE_TYPE (decl);
16163       if (result == error_mark_node)
16164         result = NULL_TREE;
16165     }
16166   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
16167            && DECL_CLASS_TEMPLATE_P (decl))
16168     {
16169       tree tmpl;
16170       tree args;
16171       /* Obtain the template and the arguments.  */
16172       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
16173       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
16174       /* Instantiate the template.  */
16175       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
16176                                       /*entering_scope=*/0,
16177                                       tf_error | tf_user);
16178       if (result == error_mark_node)
16179         result = NULL_TREE;
16180     }
16181   
16182   /* Leave the SCOPE.  */
16183   if (pushed_scope)
16184     pop_scope (pushed_scope);
16185
16186   /* If we failed to resolve it, return the original typename.  */
16187   if (!result)
16188     return type;
16189   
16190   /* If lookup found a typename type, resolve that too.  */
16191   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
16192     {
16193       /* Ill-formed programs can cause infinite recursion here, so we
16194          must catch that.  */
16195       TYPENAME_IS_RESOLVING_P (type) = 1;
16196       result = resolve_typename_type (result, only_current_p);
16197       TYPENAME_IS_RESOLVING_P (type) = 0;
16198     }
16199   
16200   /* Qualify the resulting type.  */
16201   quals = cp_type_quals (type);
16202   if (quals)
16203     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
16204
16205   return result;
16206 }
16207
16208 /* EXPR is an expression which is not type-dependent.  Return a proxy
16209    for EXPR that can be used to compute the types of larger
16210    expressions containing EXPR.  */
16211
16212 tree
16213 build_non_dependent_expr (tree expr)
16214 {
16215   tree inner_expr;
16216
16217   /* Preserve null pointer constants so that the type of things like
16218      "p == 0" where "p" is a pointer can be determined.  */
16219   if (null_ptr_cst_p (expr))
16220     return expr;
16221   /* Preserve OVERLOADs; the functions must be available to resolve
16222      types.  */
16223   inner_expr = expr;
16224   if (TREE_CODE (inner_expr) == STMT_EXPR)
16225     inner_expr = stmt_expr_value_expr (inner_expr);
16226   if (TREE_CODE (inner_expr) == ADDR_EXPR)
16227     inner_expr = TREE_OPERAND (inner_expr, 0);
16228   if (TREE_CODE (inner_expr) == COMPONENT_REF)
16229     inner_expr = TREE_OPERAND (inner_expr, 1);
16230   if (is_overloaded_fn (inner_expr)
16231       || TREE_CODE (inner_expr) == OFFSET_REF)
16232     return expr;
16233   /* There is no need to return a proxy for a variable.  */
16234   if (TREE_CODE (expr) == VAR_DECL)
16235     return expr;
16236   /* Preserve string constants; conversions from string constants to
16237      "char *" are allowed, even though normally a "const char *"
16238      cannot be used to initialize a "char *".  */
16239   if (TREE_CODE (expr) == STRING_CST)
16240     return expr;
16241   /* Preserve arithmetic constants, as an optimization -- there is no
16242      reason to create a new node.  */
16243   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
16244     return expr;
16245   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
16246      There is at least one place where we want to know that a
16247      particular expression is a throw-expression: when checking a ?:
16248      expression, there are special rules if the second or third
16249      argument is a throw-expression.  */
16250   if (TREE_CODE (expr) == THROW_EXPR)
16251     return expr;
16252
16253   if (TREE_CODE (expr) == COND_EXPR)
16254     return build3 (COND_EXPR,
16255                    TREE_TYPE (expr),
16256                    TREE_OPERAND (expr, 0),
16257                    (TREE_OPERAND (expr, 1)
16258                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
16259                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
16260                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
16261   if (TREE_CODE (expr) == COMPOUND_EXPR
16262       && !COMPOUND_EXPR_OVERLOADED (expr))
16263     return build2 (COMPOUND_EXPR,
16264                    TREE_TYPE (expr),
16265                    TREE_OPERAND (expr, 0),
16266                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
16267
16268   /* If the type is unknown, it can't really be non-dependent */
16269   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
16270
16271   /* Otherwise, build a NON_DEPENDENT_EXPR.
16272
16273      REFERENCE_TYPEs are not stripped for expressions in templates
16274      because doing so would play havoc with mangling.  Consider, for
16275      example:
16276
16277        template <typename T> void f<T& g>() { g(); }
16278
16279      In the body of "f", the expression for "g" will have
16280      REFERENCE_TYPE, even though the standard says that it should
16281      not.  The reason is that we must preserve the syntactic form of
16282      the expression so that mangling (say) "f<g>" inside the body of
16283      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
16284      stripped here.  */
16285   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
16286 }
16287
16288 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
16289    Return a new TREE_LIST with the various arguments replaced with
16290    equivalent non-dependent expressions.  */
16291
16292 tree
16293 build_non_dependent_args (tree args)
16294 {
16295   tree a;
16296   tree new_args;
16297
16298   new_args = NULL_TREE;
16299   for (a = args; a; a = TREE_CHAIN (a))
16300     new_args = tree_cons (NULL_TREE,
16301                           build_non_dependent_expr (TREE_VALUE (a)),
16302                           new_args);
16303   return nreverse (new_args);
16304 }
16305
16306 #include "gt-cp-pt.h"