re PR c++/33962 (ICE at call to overloaded template function with variable-length...
[platform/upstream/gcc.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*);
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 int template_args_equal (tree, tree);
162 static void tsubst_default_arguments (tree);
163 static tree for_each_template_parm_r (tree *, int *, void *);
164 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
165 static void copy_default_args_to_explicit_spec (tree);
166 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
167 static int eq_local_specializations (const void *, const void *);
168 static bool dependent_template_arg_p (tree);
169 static bool any_template_arguments_need_structural_equality_p (tree);
170 static bool dependent_type_p_r (tree);
171 static tree tsubst (tree, tree, tsubst_flags_t, tree);
172 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
173 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
174 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
175
176 /* Make the current scope suitable for access checking when we are
177    processing T.  T can be FUNCTION_DECL for instantiated function
178    template, or VAR_DECL for static member variable (need by
179    instantiate_decl).  */
180
181 static void
182 push_access_scope (tree t)
183 {
184   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
185               || TREE_CODE (t) == VAR_DECL);
186
187   if (DECL_FRIEND_CONTEXT (t))
188     push_nested_class (DECL_FRIEND_CONTEXT (t));
189   else if (DECL_CLASS_SCOPE_P (t))
190     push_nested_class (DECL_CONTEXT (t));
191   else
192     push_to_top_level ();
193
194   if (TREE_CODE (t) == FUNCTION_DECL)
195     {
196       saved_access_scope = tree_cons
197         (NULL_TREE, current_function_decl, saved_access_scope);
198       current_function_decl = t;
199     }
200 }
201
202 /* Restore the scope set up by push_access_scope.  T is the node we
203    are processing.  */
204
205 static void
206 pop_access_scope (tree t)
207 {
208   if (TREE_CODE (t) == FUNCTION_DECL)
209     {
210       current_function_decl = TREE_VALUE (saved_access_scope);
211       saved_access_scope = TREE_CHAIN (saved_access_scope);
212     }
213
214   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
215     pop_nested_class ();
216   else
217     pop_from_top_level ();
218 }
219
220 /* Do any processing required when DECL (a member template
221    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
222    to DECL, unless it is a specialization, in which case the DECL
223    itself is returned.  */
224
225 tree
226 finish_member_template_decl (tree decl)
227 {
228   if (decl == error_mark_node)
229     return error_mark_node;
230
231   gcc_assert (DECL_P (decl));
232
233   if (TREE_CODE (decl) == TYPE_DECL)
234     {
235       tree type;
236
237       type = TREE_TYPE (decl);
238       if (IS_AGGR_TYPE (type)
239           && CLASSTYPE_TEMPLATE_INFO (type)
240           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
241         {
242           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
243           check_member_template (tmpl);
244           return tmpl;
245         }
246       return NULL_TREE;
247     }
248   else if (TREE_CODE (decl) == FIELD_DECL)
249     error ("data member %qD cannot be a member template", decl);
250   else if (DECL_TEMPLATE_INFO (decl))
251     {
252       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
253         {
254           check_member_template (DECL_TI_TEMPLATE (decl));
255           return DECL_TI_TEMPLATE (decl);
256         }
257       else
258         return decl;
259     }
260   else
261     error ("invalid member template declaration %qD", decl);
262
263   return error_mark_node;
264 }
265
266 /* Return the template info node corresponding to T, whatever T is.  */
267
268 tree
269 get_template_info (tree t)
270 {
271   tree tinfo = NULL_TREE;
272
273   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
274     tinfo = DECL_TEMPLATE_INFO (t);
275
276   if (!tinfo && TREE_CODE (t) == TYPE_DECL)
277     t = TREE_TYPE (t);
278
279   if (TAGGED_TYPE_P (t))
280     tinfo = TYPE_TEMPLATE_INFO (t);
281
282   return tinfo;
283 }
284
285 /* Returns the template nesting level of the indicated class TYPE.
286
287    For example, in:
288      template <class T>
289      struct A
290      {
291        template <class U>
292        struct B {};
293      };
294
295    A<T>::B<U> has depth two, while A<T> has depth one.
296    Both A<T>::B<int> and A<int>::B<U> have depth one, if
297    they are instantiations, not specializations.
298
299    This function is guaranteed to return 0 if passed NULL_TREE so
300    that, for example, `template_class_depth (current_class_type)' is
301    always safe.  */
302
303 int
304 template_class_depth (tree type)
305 {
306   int depth;
307
308   for (depth = 0;
309        type && TREE_CODE (type) != NAMESPACE_DECL;
310        type = (TREE_CODE (type) == FUNCTION_DECL)
311          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
312     {
313       tree tinfo = get_template_info (type);
314
315       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
316           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
317         ++depth;
318     }
319
320   return depth;
321 }
322
323 /* Subroutine of maybe_begin_member_template_processing.
324    Returns true if processing DECL needs us to push template parms.  */
325
326 static bool
327 inline_needs_template_parms (tree decl)
328 {
329   if (! DECL_TEMPLATE_INFO (decl))
330     return false;
331
332   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
333           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
334 }
335
336 /* Subroutine of maybe_begin_member_template_processing.
337    Push the template parms in PARMS, starting from LEVELS steps into the
338    chain, and ending at the beginning, since template parms are listed
339    innermost first.  */
340
341 static void
342 push_inline_template_parms_recursive (tree parmlist, int levels)
343 {
344   tree parms = TREE_VALUE (parmlist);
345   int i;
346
347   if (levels > 1)
348     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
349
350   ++processing_template_decl;
351   current_template_parms
352     = tree_cons (size_int (processing_template_decl),
353                  parms, current_template_parms);
354   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
355
356   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
357                NULL);
358   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
359     {
360       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
361
362       if (parm == error_mark_node)
363         continue;
364
365       gcc_assert (DECL_P (parm));
366
367       switch (TREE_CODE (parm))
368         {
369         case TYPE_DECL:
370         case TEMPLATE_DECL:
371           pushdecl (parm);
372           break;
373
374         case PARM_DECL:
375           {
376             /* Make a CONST_DECL as is done in process_template_parm.
377                It is ugly that we recreate this here; the original
378                version built in process_template_parm is no longer
379                available.  */
380             tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
381                                     TREE_TYPE (parm));
382             DECL_ARTIFICIAL (decl) = 1;
383             TREE_CONSTANT (decl) = 1;
384             TREE_INVARIANT (decl) = 1;
385             TREE_READONLY (decl) = 1;
386             DECL_INITIAL (decl) = DECL_INITIAL (parm);
387             SET_DECL_TEMPLATE_PARM_P (decl);
388             pushdecl (decl);
389           }
390           break;
391
392         default:
393           gcc_unreachable ();
394         }
395     }
396 }
397
398 /* Restore the template parameter context for a member template or
399    a friend template defined in a class definition.  */
400
401 void
402 maybe_begin_member_template_processing (tree decl)
403 {
404   tree parms;
405   int levels = 0;
406
407   if (inline_needs_template_parms (decl))
408     {
409       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
410       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
411
412       if (DECL_TEMPLATE_SPECIALIZATION (decl))
413         {
414           --levels;
415           parms = TREE_CHAIN (parms);
416         }
417
418       push_inline_template_parms_recursive (parms, levels);
419     }
420
421   /* Remember how many levels of template parameters we pushed so that
422      we can pop them later.  */
423   VEC_safe_push (int, heap, inline_parm_levels, levels);
424 }
425
426 /* Undo the effects of maybe_begin_member_template_processing.  */
427
428 void
429 maybe_end_member_template_processing (void)
430 {
431   int i;
432   int last;
433
434   if (VEC_length (int, inline_parm_levels) == 0)
435     return;
436
437   last = VEC_pop (int, inline_parm_levels);
438   for (i = 0; i < last; ++i)
439     {
440       --processing_template_decl;
441       current_template_parms = TREE_CHAIN (current_template_parms);
442       poplevel (0, 0, 0);
443     }
444 }
445
446 /* Return a new template argument vector which contains all of ARGS,
447    but has as its innermost set of arguments the EXTRA_ARGS.  */
448
449 static tree
450 add_to_template_args (tree args, tree extra_args)
451 {
452   tree new_args;
453   int extra_depth;
454   int i;
455   int j;
456
457   extra_depth = TMPL_ARGS_DEPTH (extra_args);
458   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
459
460   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
461     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
462
463   for (j = 1; j <= extra_depth; ++j, ++i)
464     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
465
466   return new_args;
467 }
468
469 /* Like add_to_template_args, but only the outermost ARGS are added to
470    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
471    (EXTRA_ARGS) levels are added.  This function is used to combine
472    the template arguments from a partial instantiation with the
473    template arguments used to attain the full instantiation from the
474    partial instantiation.  */
475
476 static tree
477 add_outermost_template_args (tree args, tree extra_args)
478 {
479   tree new_args;
480
481   /* If there are more levels of EXTRA_ARGS than there are ARGS,
482      something very fishy is going on.  */
483   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
484
485   /* If *all* the new arguments will be the EXTRA_ARGS, just return
486      them.  */
487   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
488     return extra_args;
489
490   /* For the moment, we make ARGS look like it contains fewer levels.  */
491   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
492
493   new_args = add_to_template_args (args, extra_args);
494
495   /* Now, we restore ARGS to its full dimensions.  */
496   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
497
498   return new_args;
499 }
500
501 /* Return the N levels of innermost template arguments from the ARGS.  */
502
503 tree
504 get_innermost_template_args (tree args, int n)
505 {
506   tree new_args;
507   int extra_levels;
508   int i;
509
510   gcc_assert (n >= 0);
511
512   /* If N is 1, just return the innermost set of template arguments.  */
513   if (n == 1)
514     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
515
516   /* If we're not removing anything, just return the arguments we were
517      given.  */
518   extra_levels = TMPL_ARGS_DEPTH (args) - n;
519   gcc_assert (extra_levels >= 0);
520   if (extra_levels == 0)
521     return args;
522
523   /* Make a new set of arguments, not containing the outer arguments.  */
524   new_args = make_tree_vec (n);
525   for (i = 1; i <= n; ++i)
526     SET_TMPL_ARGS_LEVEL (new_args, i,
527                          TMPL_ARGS_LEVEL (args, i + extra_levels));
528
529   return new_args;
530 }
531
532 /* The inverse of get_innermost_template_args: Return all but the innermost
533    EXTRA_LEVELS levels of template arguments from the ARGS.  */
534
535 static tree
536 strip_innermost_template_args (tree args, int extra_levels)
537 {
538   tree new_args;
539   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
540   int i;
541
542   gcc_assert (n >= 0);
543
544   /* If N is 1, just return the outermost set of template arguments.  */
545   if (n == 1)
546     return TMPL_ARGS_LEVEL (args, 1);
547
548   /* If we're not removing anything, just return the arguments we were
549      given.  */
550   gcc_assert (extra_levels >= 0);
551   if (extra_levels == 0)
552     return args;
553
554   /* Make a new set of arguments, not containing the inner arguments.  */
555   new_args = make_tree_vec (n);
556   for (i = 1; i <= n; ++i)
557     SET_TMPL_ARGS_LEVEL (new_args, i,
558                          TMPL_ARGS_LEVEL (args, i));
559
560   return new_args;
561 }
562
563 /* We've got a template header coming up; push to a new level for storing
564    the parms.  */
565
566 void
567 begin_template_parm_list (void)
568 {
569   /* We use a non-tag-transparent scope here, which causes pushtag to
570      put tags in this scope, rather than in the enclosing class or
571      namespace scope.  This is the right thing, since we want
572      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
573      global template class, push_template_decl handles putting the
574      TEMPLATE_DECL into top-level scope.  For a nested template class,
575      e.g.:
576
577        template <class T> struct S1 {
578          template <class T> struct S2 {};
579        };
580
581      pushtag contains special code to call pushdecl_with_scope on the
582      TEMPLATE_DECL for S2.  */
583   begin_scope (sk_template_parms, NULL);
584   ++processing_template_decl;
585   ++processing_template_parmlist;
586   note_template_header (0);
587 }
588
589 /* This routine is called when a specialization is declared.  If it is
590    invalid to declare a specialization here, an error is reported and
591    false is returned, otherwise this routine will return true.  */
592
593 static bool
594 check_specialization_scope (void)
595 {
596   tree scope = current_scope ();
597
598   /* [temp.expl.spec]
599
600      An explicit specialization shall be declared in the namespace of
601      which the template is a member, or, for member templates, in the
602      namespace of which the enclosing class or enclosing class
603      template is a member.  An explicit specialization of a member
604      function, member class or static data member of a class template
605      shall be declared in the namespace of which the class template
606      is a member.  */
607   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
608     {
609       error ("explicit specialization in non-namespace scope %qD", scope);
610       return false;
611     }
612
613   /* [temp.expl.spec]
614
615      In an explicit specialization declaration for a member of a class
616      template or a member template that appears in namespace scope,
617      the member template and some of its enclosing class templates may
618      remain unspecialized, except that the declaration shall not
619      explicitly specialize a class member template if its enclosing
620      class templates are not explicitly specialized as well.  */
621   if (current_template_parms)
622     {
623       error ("enclosing class templates are not explicitly specialized");
624       return false;
625     }
626
627   return true;
628 }
629
630 /* We've just seen template <>.  */
631
632 bool
633 begin_specialization (void)
634 {
635   begin_scope (sk_template_spec, NULL);
636   note_template_header (1);
637   return check_specialization_scope ();
638 }
639
640 /* Called at then end of processing a declaration preceded by
641    template<>.  */
642
643 void
644 end_specialization (void)
645 {
646   finish_scope ();
647   reset_specialization ();
648 }
649
650 /* Any template <>'s that we have seen thus far are not referring to a
651    function specialization.  */
652
653 void
654 reset_specialization (void)
655 {
656   processing_specialization = 0;
657   template_header_count = 0;
658 }
659
660 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
661    it was of the form template <>.  */
662
663 static void
664 note_template_header (int specialization)
665 {
666   processing_specialization = specialization;
667   template_header_count++;
668 }
669
670 /* We're beginning an explicit instantiation.  */
671
672 void
673 begin_explicit_instantiation (void)
674 {
675   gcc_assert (!processing_explicit_instantiation);
676   processing_explicit_instantiation = true;
677 }
678
679
680 void
681 end_explicit_instantiation (void)
682 {
683   gcc_assert (processing_explicit_instantiation);
684   processing_explicit_instantiation = false;
685 }
686
687 /* An explicit specialization or partial specialization TMPL is being
688    declared.  Check that the namespace in which the specialization is
689    occurring is permissible.  Returns false iff it is invalid to
690    specialize TMPL in the current namespace.  */
691
692 static bool
693 check_specialization_namespace (tree tmpl)
694 {
695   tree tpl_ns = decl_namespace_context (tmpl);
696
697   /* [tmpl.expl.spec]
698
699      An explicit specialization shall be declared in the namespace of
700      which the template is a member, or, for member templates, in the
701      namespace of which the enclosing class or enclosing class
702      template is a member.  An explicit specialization of a member
703      function, member class or static data member of a class template
704      shall be declared in the namespace of which the class template is
705      a member.  */
706   if (is_associated_namespace (current_namespace, tpl_ns))
707     /* Same or super-using namespace.  */
708     return true;
709   else
710     {
711       pedwarn ("specialization of %qD in different namespace", tmpl);
712       pedwarn ("  from definition of %q+#D", tmpl);
713       return false;
714     }
715 }
716
717 /* SPEC is an explicit instantiation.  Check that it is valid to
718    perform this explicit instantiation in the current namespace.  */
719
720 static void
721 check_explicit_instantiation_namespace (tree spec)
722 {
723   tree ns;
724
725   /* DR 275: An explicit instantiation shall appear in an enclosing
726      namespace of its template.  */
727   ns = decl_namespace_context (spec);
728   if (!is_ancestor (current_namespace, ns))
729     pedwarn ("explicit instantiation of %qD in namespace %qD "
730              "(which does not enclose namespace %qD)",
731              spec, current_namespace, ns);
732 }
733
734 /* The TYPE is being declared.  If it is a template type, that means it
735    is a partial specialization.  Do appropriate error-checking.  */
736
737 tree
738 maybe_process_partial_specialization (tree type)
739 {
740   tree context;
741
742   if (type == error_mark_node)
743     return error_mark_node;
744
745   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
746     {
747       error ("name of class shadows template template parameter %qD",
748              TYPE_NAME (type));
749       return error_mark_node;
750     }
751
752   context = TYPE_CONTEXT (type);
753
754   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
755     {
756       /* This is for ordinary explicit specialization and partial
757          specialization of a template class such as:
758
759            template <> class C<int>;
760
761          or:
762
763            template <class T> class C<T*>;
764
765          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
766
767       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
768           && !COMPLETE_TYPE_P (type))
769         {
770           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
771           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
772           if (processing_template_decl)
773             push_template_decl (TYPE_MAIN_DECL (type));
774         }
775       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
776         error ("specialization of %qT after instantiation", type);
777     }
778   else if (CLASS_TYPE_P (type)
779            && !CLASSTYPE_USE_TEMPLATE (type)
780            && CLASSTYPE_TEMPLATE_INFO (type)
781            && context && CLASS_TYPE_P (context)
782            && CLASSTYPE_TEMPLATE_INFO (context))
783     {
784       /* This is for an explicit specialization of member class
785          template according to [temp.expl.spec/18]:
786
787            template <> template <class U> class C<int>::D;
788
789          The context `C<int>' must be an implicit instantiation.
790          Otherwise this is just a member class template declared
791          earlier like:
792
793            template <> class C<int> { template <class U> class D; };
794            template <> template <class U> class C<int>::D;
795
796          In the first case, `C<int>::D' is a specialization of `C<T>::D'
797          while in the second case, `C<int>::D' is a primary template
798          and `C<T>::D' may not exist.  */
799
800       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
801           && !COMPLETE_TYPE_P (type))
802         {
803           tree t;
804
805           if (current_namespace
806               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
807             {
808               pedwarn ("specializing %q#T in different namespace", type);
809               pedwarn ("  from definition of %q+#D",
810                        CLASSTYPE_TI_TEMPLATE (type));
811             }
812
813           /* Check for invalid specialization after instantiation:
814
815                template <> template <> class C<int>::D<int>;
816                template <> template <class U> class C<int>::D;  */
817
818           for (t = DECL_TEMPLATE_INSTANTIATIONS
819                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
820                t; t = TREE_CHAIN (t))
821             if (TREE_VALUE (t) != type
822                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
823               error ("specialization %qT after instantiation %qT",
824                      type, TREE_VALUE (t));
825
826           /* Mark TYPE as a specialization.  And as a result, we only
827              have one level of template argument for the innermost
828              class template.  */
829           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
830           CLASSTYPE_TI_ARGS (type)
831             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
832         }
833     }
834   else if (processing_specialization)
835     {
836       error ("explicit specialization of non-template %qT", type);
837       return error_mark_node;
838     }
839
840   return type;
841 }
842
843 /* Returns nonzero if we can optimize the retrieval of specializations
844    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
845    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
846
847 static inline bool
848 optimize_specialization_lookup_p (tree tmpl)
849 {
850   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
851           && DECL_CLASS_SCOPE_P (tmpl)
852           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
853              parameter.  */
854           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
855           /* The optimized lookup depends on the fact that the
856              template arguments for the member function template apply
857              purely to the containing class, which is not true if the
858              containing class is an explicit or partial
859              specialization.  */
860           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
861           && !DECL_MEMBER_TEMPLATE_P (tmpl)
862           && !DECL_CONV_FN_P (tmpl)
863           /* It is possible to have a template that is not a member
864              template and is not a member of a template class:
865
866              template <typename T>
867              struct S { friend A::f(); };
868
869              Here, the friend function is a template, but the context does
870              not have template information.  The optimized lookup relies
871              on having ARGS be the template arguments for both the class
872              and the function template.  */
873           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
874 }
875
876 /* Retrieve the specialization (in the sense of [temp.spec] - a
877    specialization is either an instantiation or an explicit
878    specialization) of TMPL for the given template ARGS.  If there is
879    no such specialization, return NULL_TREE.  The ARGS are a vector of
880    arguments, or a vector of vectors of arguments, in the case of
881    templates with more than one level of parameters.
882
883    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
884    then we search for a partial specialization matching ARGS.  This
885    parameter is ignored if TMPL is not a class template.  */
886
887 static tree
888 retrieve_specialization (tree tmpl, tree args,
889                          bool class_specializations_p)
890 {
891   if (args == error_mark_node)
892     return NULL_TREE;
893
894   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
895
896   /* There should be as many levels of arguments as there are
897      levels of parameters.  */
898   gcc_assert (TMPL_ARGS_DEPTH (args)
899               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
900
901   if (optimize_specialization_lookup_p (tmpl))
902     {
903       tree class_template;
904       tree class_specialization;
905       VEC(tree,gc) *methods;
906       tree fns;
907       int idx;
908
909       /* The template arguments actually apply to the containing
910          class.  Find the class specialization with those
911          arguments.  */
912       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
913       class_specialization
914         = retrieve_specialization (class_template, args,
915                                    /*class_specializations_p=*/false);
916       if (!class_specialization)
917         return NULL_TREE;
918       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
919          for the specialization.  */
920       idx = class_method_index_for_fn (class_specialization, tmpl);
921       if (idx == -1)
922         return NULL_TREE;
923       /* Iterate through the methods with the indicated name, looking
924          for the one that has an instance of TMPL.  */
925       methods = CLASSTYPE_METHOD_VEC (class_specialization);
926       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
927         {
928           tree fn = OVL_CURRENT (fns);
929           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
930             return fn;
931         }
932       return NULL_TREE;
933     }
934   else
935     {
936       tree *sp;
937       tree *head;
938
939       /* Class templates store their instantiations on the
940          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
941          DECL_TEMPLATE_SPECIALIZATIONS list.  */
942       if (!class_specializations_p
943           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL
944           && TAGGED_TYPE_P (TREE_TYPE (tmpl)))
945         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
946       else
947         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
948       head = sp;
949       /* Iterate through the list until we find a matching template.  */
950       while (*sp != NULL_TREE)
951         {
952           tree spec = *sp;
953
954           if (comp_template_args (TREE_PURPOSE (spec), args))
955             {
956               /* Use the move-to-front heuristic to speed up future
957                  searches.  */
958               if (spec != *head)
959                 {
960                   *sp = TREE_CHAIN (*sp);
961                   TREE_CHAIN (spec) = *head;
962                   *head = spec;
963                 }
964               return TREE_VALUE (spec);
965             }
966           sp = &TREE_CHAIN (spec);
967         }
968     }
969
970   return NULL_TREE;
971 }
972
973 /* Like retrieve_specialization, but for local declarations.  */
974
975 static tree
976 retrieve_local_specialization (tree tmpl)
977 {
978   tree spec = (tree) htab_find_with_hash (local_specializations, tmpl,
979                                           htab_hash_pointer (tmpl));
980   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
981 }
982
983 /* Returns nonzero iff DECL is a specialization of TMPL.  */
984
985 int
986 is_specialization_of (tree decl, tree tmpl)
987 {
988   tree t;
989
990   if (TREE_CODE (decl) == FUNCTION_DECL)
991     {
992       for (t = decl;
993            t != NULL_TREE;
994            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
995         if (t == tmpl)
996           return 1;
997     }
998   else
999     {
1000       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1001
1002       for (t = TREE_TYPE (decl);
1003            t != NULL_TREE;
1004            t = CLASSTYPE_USE_TEMPLATE (t)
1005              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1006         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1007           return 1;
1008     }
1009
1010   return 0;
1011 }
1012
1013 /* Returns nonzero iff DECL is a specialization of friend declaration
1014    FRIEND according to [temp.friend].  */
1015
1016 bool
1017 is_specialization_of_friend (tree decl, tree friend)
1018 {
1019   bool need_template = true;
1020   int template_depth;
1021
1022   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1023               || TREE_CODE (decl) == TYPE_DECL);
1024
1025   /* For [temp.friend/6] when FRIEND is an ordinary member function
1026      of a template class, we want to check if DECL is a specialization
1027      if this.  */
1028   if (TREE_CODE (friend) == FUNCTION_DECL
1029       && DECL_TEMPLATE_INFO (friend)
1030       && !DECL_USE_TEMPLATE (friend))
1031     {
1032       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1033       friend = DECL_TI_TEMPLATE (friend);
1034       need_template = false;
1035     }
1036   else if (TREE_CODE (friend) == TEMPLATE_DECL
1037            && !PRIMARY_TEMPLATE_P (friend))
1038     need_template = false;
1039
1040   /* There is nothing to do if this is not a template friend.  */
1041   if (TREE_CODE (friend) != TEMPLATE_DECL)
1042     return false;
1043
1044   if (is_specialization_of (decl, friend))
1045     return true;
1046
1047   /* [temp.friend/6]
1048      A member of a class template may be declared to be a friend of a
1049      non-template class.  In this case, the corresponding member of
1050      every specialization of the class template is a friend of the
1051      class granting friendship.
1052
1053      For example, given a template friend declaration
1054
1055        template <class T> friend void A<T>::f();
1056
1057      the member function below is considered a friend
1058
1059        template <> struct A<int> {
1060          void f();
1061        };
1062
1063      For this type of template friend, TEMPLATE_DEPTH below will be
1064      nonzero.  To determine if DECL is a friend of FRIEND, we first
1065      check if the enclosing class is a specialization of another.  */
1066
1067   template_depth = template_class_depth (DECL_CONTEXT (friend));
1068   if (template_depth
1069       && DECL_CLASS_SCOPE_P (decl)
1070       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1071                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend))))
1072     {
1073       /* Next, we check the members themselves.  In order to handle
1074          a few tricky cases, such as when FRIEND's are
1075
1076            template <class T> friend void A<T>::g(T t);
1077            template <class T> template <T t> friend void A<T>::h();
1078
1079          and DECL's are
1080
1081            void A<int>::g(int);
1082            template <int> void A<int>::h();
1083
1084          we need to figure out ARGS, the template arguments from
1085          the context of DECL.  This is required for template substitution
1086          of `T' in the function parameter of `g' and template parameter
1087          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1088
1089       tree context = DECL_CONTEXT (decl);
1090       tree args = NULL_TREE;
1091       int current_depth = 0;
1092
1093       while (current_depth < template_depth)
1094         {
1095           if (CLASSTYPE_TEMPLATE_INFO (context))
1096             {
1097               if (current_depth == 0)
1098                 args = TYPE_TI_ARGS (context);
1099               else
1100                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1101               current_depth++;
1102             }
1103           context = TYPE_CONTEXT (context);
1104         }
1105
1106       if (TREE_CODE (decl) == FUNCTION_DECL)
1107         {
1108           bool is_template;
1109           tree friend_type;
1110           tree decl_type;
1111           tree friend_args_type;
1112           tree decl_args_type;
1113
1114           /* Make sure that both DECL and FRIEND are templates or
1115              non-templates.  */
1116           is_template = DECL_TEMPLATE_INFO (decl)
1117                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1118           if (need_template ^ is_template)
1119             return false;
1120           else if (is_template)
1121             {
1122               /* If both are templates, check template parameter list.  */
1123               tree friend_parms
1124                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1125                                          args, tf_none);
1126               if (!comp_template_parms
1127                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1128                       friend_parms))
1129                 return false;
1130
1131               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1132             }
1133           else
1134             decl_type = TREE_TYPE (decl);
1135
1136           friend_type = tsubst_function_type (TREE_TYPE (friend), args,
1137                                               tf_none, NULL_TREE);
1138           if (friend_type == error_mark_node)
1139             return false;
1140
1141           /* Check if return types match.  */
1142           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1143             return false;
1144
1145           /* Check if function parameter types match, ignoring the
1146              `this' parameter.  */
1147           friend_args_type = TYPE_ARG_TYPES (friend_type);
1148           decl_args_type = TYPE_ARG_TYPES (decl_type);
1149           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend))
1150             friend_args_type = TREE_CHAIN (friend_args_type);
1151           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1152             decl_args_type = TREE_CHAIN (decl_args_type);
1153
1154           return compparms (decl_args_type, friend_args_type);
1155         }
1156       else
1157         {
1158           /* DECL is a TYPE_DECL */
1159           bool is_template;
1160           tree decl_type = TREE_TYPE (decl);
1161
1162           /* Make sure that both DECL and FRIEND are templates or
1163              non-templates.  */
1164           is_template
1165             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1166               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1167
1168           if (need_template ^ is_template)
1169             return false;
1170           else if (is_template)
1171             {
1172               tree friend_parms;
1173               /* If both are templates, check the name of the two
1174                  TEMPLATE_DECL's first because is_friend didn't.  */
1175               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1176                   != DECL_NAME (friend))
1177                 return false;
1178
1179               /* Now check template parameter list.  */
1180               friend_parms
1181                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1182                                          args, tf_none);
1183               return comp_template_parms
1184                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1185                  friend_parms);
1186             }
1187           else
1188             return (DECL_NAME (decl)
1189                     == DECL_NAME (friend));
1190         }
1191     }
1192   return false;
1193 }
1194
1195 /* Register the specialization SPEC as a specialization of TMPL with
1196    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1197    is actually just a friend declaration.  Returns SPEC, or an
1198    equivalent prior declaration, if available.  */
1199
1200 static tree
1201 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1202 {
1203   tree fn;
1204
1205   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1206
1207   if (TREE_CODE (spec) == FUNCTION_DECL
1208       && uses_template_parms (DECL_TI_ARGS (spec)))
1209     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1210        register it; we want the corresponding TEMPLATE_DECL instead.
1211        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1212        the more obvious `uses_template_parms (spec)' to avoid problems
1213        with default function arguments.  In particular, given
1214        something like this:
1215
1216           template <class T> void f(T t1, T t = T())
1217
1218        the default argument expression is not substituted for in an
1219        instantiation unless and until it is actually needed.  */
1220     return spec;
1221
1222   fn = retrieve_specialization (tmpl, args,
1223                                 /*class_specializations_p=*/false);
1224   /* We can sometimes try to re-register a specialization that we've
1225      already got.  In particular, regenerate_decl_from_template calls
1226      duplicate_decls which will update the specialization list.  But,
1227      we'll still get called again here anyhow.  It's more convenient
1228      to simply allow this than to try to prevent it.  */
1229   if (fn == spec)
1230     return spec;
1231   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1232     {
1233       if (DECL_TEMPLATE_INSTANTIATION (fn))
1234         {
1235           if (TREE_USED (fn)
1236               || DECL_EXPLICIT_INSTANTIATION (fn))
1237             {
1238               error ("specialization of %qD after instantiation",
1239                      fn);
1240               return error_mark_node;
1241             }
1242           else
1243             {
1244               tree clone;
1245               /* This situation should occur only if the first
1246                  specialization is an implicit instantiation, the
1247                  second is an explicit specialization, and the
1248                  implicit instantiation has not yet been used.  That
1249                  situation can occur if we have implicitly
1250                  instantiated a member function and then specialized
1251                  it later.
1252
1253                  We can also wind up here if a friend declaration that
1254                  looked like an instantiation turns out to be a
1255                  specialization:
1256
1257                    template <class T> void foo(T);
1258                    class S { friend void foo<>(int) };
1259                    template <> void foo(int);
1260
1261                  We transform the existing DECL in place so that any
1262                  pointers to it become pointers to the updated
1263                  declaration.
1264
1265                  If there was a definition for the template, but not
1266                  for the specialization, we want this to look as if
1267                  there were no definition, and vice versa.  */
1268               DECL_INITIAL (fn) = NULL_TREE;
1269               duplicate_decls (spec, fn, is_friend);
1270               /* The call to duplicate_decls will have applied
1271                  [temp.expl.spec]:
1272
1273                    An explicit specialization of a function template
1274                    is inline only if it is explicitly declared to be,
1275                    and independently of whether its function template
1276                    is.
1277
1278                 to the primary function; now copy the inline bits to
1279                 the various clones.  */
1280               FOR_EACH_CLONE (clone, fn)
1281                 {
1282                   DECL_DECLARED_INLINE_P (clone)
1283                     = DECL_DECLARED_INLINE_P (fn);
1284                   DECL_INLINE (clone)
1285                     = DECL_INLINE (fn);
1286                 }
1287               check_specialization_namespace (fn);
1288
1289               return fn;
1290             }
1291         }
1292       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1293         {
1294           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1295             /* Dup decl failed, but this is a new definition. Set the
1296                line number so any errors match this new
1297                definition.  */
1298             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1299
1300           return fn;
1301         }
1302     }
1303
1304   /* A specialization must be declared in the same namespace as the
1305      template it is specializing.  */
1306   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1307       && !check_specialization_namespace (tmpl))
1308     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1309
1310   if (!optimize_specialization_lookup_p (tmpl))
1311     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1312       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1313
1314   return spec;
1315 }
1316
1317 /* Unregister the specialization SPEC as a specialization of TMPL.
1318    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1319    if the SPEC was listed as a specialization of TMPL.  */
1320
1321 bool
1322 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1323 {
1324   tree* s;
1325
1326   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1327        *s != NULL_TREE;
1328        s = &TREE_CHAIN (*s))
1329     if (TREE_VALUE (*s) == spec)
1330       {
1331         if (!new_spec)
1332           *s = TREE_CHAIN (*s);
1333         else
1334           TREE_VALUE (*s) = new_spec;
1335         return 1;
1336       }
1337
1338   return 0;
1339 }
1340
1341 /* Compare an entry in the local specializations hash table P1 (which
1342    is really a pointer to a TREE_LIST) with P2 (which is really a
1343    DECL).  */
1344
1345 static int
1346 eq_local_specializations (const void *p1, const void *p2)
1347 {
1348   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1349 }
1350
1351 /* Hash P1, an entry in the local specializations table.  */
1352
1353 static hashval_t
1354 hash_local_specialization (const void* p1)
1355 {
1356   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1357 }
1358
1359 /* Like register_specialization, but for local declarations.  We are
1360    registering SPEC, an instantiation of TMPL.  */
1361
1362 static void
1363 register_local_specialization (tree spec, tree tmpl)
1364 {
1365   void **slot;
1366
1367   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1368                                    htab_hash_pointer (tmpl), INSERT);
1369   *slot = build_tree_list (spec, tmpl);
1370 }
1371
1372 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1373    specialized class.  */
1374
1375 bool
1376 explicit_class_specialization_p (tree type)
1377 {
1378   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1379     return false;
1380   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1381 }
1382
1383 /* Print the list of candidate FNS in an error message.  */
1384
1385 void
1386 print_candidates (tree fns)
1387 {
1388   tree fn;
1389
1390   const char *str = "candidates are:";
1391
1392   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1393     {
1394       tree f;
1395
1396       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1397         error ("%s %+#D", str, OVL_CURRENT (f));
1398       str = "               ";
1399     }
1400 }
1401
1402 /* Returns the template (one of the functions given by TEMPLATE_ID)
1403    which can be specialized to match the indicated DECL with the
1404    explicit template args given in TEMPLATE_ID.  The DECL may be
1405    NULL_TREE if none is available.  In that case, the functions in
1406    TEMPLATE_ID are non-members.
1407
1408    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1409    specialization of a member template.
1410
1411    The TEMPLATE_COUNT is the number of references to qualifying
1412    template classes that appeared in the name of the function. See
1413    check_explicit_specialization for a more accurate description.
1414
1415    TSK indicates what kind of template declaration (if any) is being
1416    declared.  TSK_TEMPLATE indicates that the declaration given by
1417    DECL, though a FUNCTION_DECL, has template parameters, and is
1418    therefore a template function.
1419
1420    The template args (those explicitly specified and those deduced)
1421    are output in a newly created vector *TARGS_OUT.
1422
1423    If it is impossible to determine the result, an error message is
1424    issued.  The error_mark_node is returned to indicate failure.  */
1425
1426 static tree
1427 determine_specialization (tree template_id,
1428                           tree decl,
1429                           tree* targs_out,
1430                           int need_member_template,
1431                           int template_count,
1432                           tmpl_spec_kind tsk)
1433 {
1434   tree fns;
1435   tree targs;
1436   tree explicit_targs;
1437   tree candidates = NULL_TREE;
1438   /* A TREE_LIST of templates of which DECL may be a specialization.
1439      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1440      corresponding TREE_PURPOSE is the set of template arguments that,
1441      when used to instantiate the template, would produce a function
1442      with the signature of DECL.  */
1443   tree templates = NULL_TREE;
1444   int header_count;
1445   struct cp_binding_level *b;
1446
1447   *targs_out = NULL_TREE;
1448
1449   if (template_id == error_mark_node || decl == error_mark_node)
1450     return error_mark_node;
1451
1452   fns = TREE_OPERAND (template_id, 0);
1453   explicit_targs = TREE_OPERAND (template_id, 1);
1454
1455   if (fns == error_mark_node)
1456     return error_mark_node;
1457
1458   /* Check for baselinks.  */
1459   if (BASELINK_P (fns))
1460     fns = BASELINK_FUNCTIONS (fns);
1461
1462   if (!is_overloaded_fn (fns))
1463     {
1464       error ("%qD is not a function template", fns);
1465       return error_mark_node;
1466     }
1467
1468   /* Count the number of template headers specified for this
1469      specialization.  */
1470   header_count = 0;
1471   for (b = current_binding_level;
1472        b->kind == sk_template_parms;
1473        b = b->level_chain)
1474     ++header_count;
1475
1476   for (; fns; fns = OVL_NEXT (fns))
1477     {
1478       tree fn = OVL_CURRENT (fns);
1479
1480       if (TREE_CODE (fn) == TEMPLATE_DECL)
1481         {
1482           tree decl_arg_types;
1483           tree fn_arg_types;
1484
1485           /* In case of explicit specialization, we need to check if
1486              the number of template headers appearing in the specialization
1487              is correct. This is usually done in check_explicit_specialization,
1488              but the check done there cannot be exhaustive when specializing
1489              member functions. Consider the following code:
1490
1491              template <> void A<int>::f(int);
1492              template <> template <> void A<int>::f(int);
1493
1494              Assuming that A<int> is not itself an explicit specialization
1495              already, the first line specializes "f" which is a non-template
1496              member function, whilst the second line specializes "f" which
1497              is a template member function. So both lines are syntactically
1498              correct, and check_explicit_specialization does not reject
1499              them.
1500
1501              Here, we can do better, as we are matching the specialization
1502              against the declarations. We count the number of template
1503              headers, and we check if they match TEMPLATE_COUNT + 1
1504              (TEMPLATE_COUNT is the number of qualifying template classes,
1505              plus there must be another header for the member template
1506              itself).
1507
1508              Notice that if header_count is zero, this is not a
1509              specialization but rather a template instantiation, so there
1510              is no check we can perform here.  */
1511           if (header_count && header_count != template_count + 1)
1512             continue;
1513
1514           /* Check that the number of template arguments at the
1515              innermost level for DECL is the same as for FN.  */
1516           if (current_binding_level->kind == sk_template_parms
1517               && !current_binding_level->explicit_spec_p
1518               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1519                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1520                                       (current_template_parms))))
1521             continue;
1522
1523           /* DECL might be a specialization of FN.  */
1524           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1525           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1526
1527           /* For a non-static member function, we need to make sure
1528              that the const qualification is the same.  Since
1529              get_bindings does not try to merge the "this" parameter,
1530              we must do the comparison explicitly.  */
1531           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1532               && !same_type_p (TREE_VALUE (fn_arg_types),
1533                                TREE_VALUE (decl_arg_types)))
1534             continue;
1535
1536           /* Skip the "this" parameter and, for constructors of
1537              classes with virtual bases, the VTT parameter.  A
1538              full specialization of a constructor will have a VTT
1539              parameter, but a template never will.  */ 
1540           decl_arg_types 
1541             = skip_artificial_parms_for (decl, decl_arg_types);
1542           fn_arg_types 
1543             = skip_artificial_parms_for (fn, fn_arg_types);
1544
1545           /* Check that the number of function parameters matches.
1546              For example,
1547                template <class T> void f(int i = 0);
1548                template <> void f<int>();
1549              The specialization f<int> is invalid but is not caught
1550              by get_bindings below.  */
1551           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1552             continue;
1553
1554           /* Function templates cannot be specializations; there are
1555              no partial specializations of functions.  Therefore, if
1556              the type of DECL does not match FN, there is no
1557              match.  */
1558           if (tsk == tsk_template)
1559             {
1560               if (compparms (fn_arg_types, decl_arg_types))
1561                 candidates = tree_cons (NULL_TREE, fn, candidates);
1562               continue;
1563             }
1564
1565           /* See whether this function might be a specialization of this
1566              template.  */
1567           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1568
1569           if (!targs)
1570             /* We cannot deduce template arguments that when used to
1571                specialize TMPL will produce DECL.  */
1572             continue;
1573
1574           /* Save this template, and the arguments deduced.  */
1575           templates = tree_cons (targs, fn, templates);
1576         }
1577       else if (need_member_template)
1578         /* FN is an ordinary member function, and we need a
1579            specialization of a member template.  */
1580         ;
1581       else if (TREE_CODE (fn) != FUNCTION_DECL)
1582         /* We can get IDENTIFIER_NODEs here in certain erroneous
1583            cases.  */
1584         ;
1585       else if (!DECL_FUNCTION_MEMBER_P (fn))
1586         /* This is just an ordinary non-member function.  Nothing can
1587            be a specialization of that.  */
1588         ;
1589       else if (DECL_ARTIFICIAL (fn))
1590         /* Cannot specialize functions that are created implicitly.  */
1591         ;
1592       else
1593         {
1594           tree decl_arg_types;
1595
1596           /* This is an ordinary member function.  However, since
1597              we're here, we can assume it's enclosing class is a
1598              template class.  For example,
1599
1600                template <typename T> struct S { void f(); };
1601                template <> void S<int>::f() {}
1602
1603              Here, S<int>::f is a non-template, but S<int> is a
1604              template class.  If FN has the same type as DECL, we
1605              might be in business.  */
1606
1607           if (!DECL_TEMPLATE_INFO (fn))
1608             /* Its enclosing class is an explicit specialization
1609                of a template class.  This is not a candidate.  */
1610             continue;
1611
1612           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1613                             TREE_TYPE (TREE_TYPE (fn))))
1614             /* The return types differ.  */
1615             continue;
1616
1617           /* Adjust the type of DECL in case FN is a static member.  */
1618           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1619           if (DECL_STATIC_FUNCTION_P (fn)
1620               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1621             decl_arg_types = TREE_CHAIN (decl_arg_types);
1622
1623           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1624                          decl_arg_types))
1625             /* They match!  */
1626             candidates = tree_cons (NULL_TREE, fn, candidates);
1627         }
1628     }
1629
1630   if (templates && TREE_CHAIN (templates))
1631     {
1632       /* We have:
1633
1634            [temp.expl.spec]
1635
1636            It is possible for a specialization with a given function
1637            signature to be instantiated from more than one function
1638            template.  In such cases, explicit specification of the
1639            template arguments must be used to uniquely identify the
1640            function template specialization being specialized.
1641
1642          Note that here, there's no suggestion that we're supposed to
1643          determine which of the candidate templates is most
1644          specialized.  However, we, also have:
1645
1646            [temp.func.order]
1647
1648            Partial ordering of overloaded function template
1649            declarations is used in the following contexts to select
1650            the function template to which a function template
1651            specialization refers:
1652
1653            -- when an explicit specialization refers to a function
1654               template.
1655
1656          So, we do use the partial ordering rules, at least for now.
1657          This extension can only serve to make invalid programs valid,
1658          so it's safe.  And, there is strong anecdotal evidence that
1659          the committee intended the partial ordering rules to apply;
1660          the EDG front end has that behavior, and John Spicer claims
1661          that the committee simply forgot to delete the wording in
1662          [temp.expl.spec].  */
1663       tree tmpl = most_specialized_instantiation (templates);
1664       if (tmpl != error_mark_node)
1665         {
1666           templates = tmpl;
1667           TREE_CHAIN (templates) = NULL_TREE;
1668         }
1669     }
1670
1671   if (templates == NULL_TREE && candidates == NULL_TREE)
1672     {
1673       error ("template-id %qD for %q+D does not match any template "
1674              "declaration", template_id, decl);
1675       return error_mark_node;
1676     }
1677   else if ((templates && TREE_CHAIN (templates))
1678            || (candidates && TREE_CHAIN (candidates))
1679            || (templates && candidates))
1680     {
1681       error ("ambiguous template specialization %qD for %q+D",
1682              template_id, decl);
1683       chainon (candidates, templates);
1684       print_candidates (candidates);
1685       return error_mark_node;
1686     }
1687
1688   /* We have one, and exactly one, match.  */
1689   if (candidates)
1690     {
1691       tree fn = TREE_VALUE (candidates);
1692       /* DECL is a re-declaration of a template function.  */
1693       if (TREE_CODE (fn) == TEMPLATE_DECL)
1694         return fn;
1695       /* It was a specialization of an ordinary member function in a
1696          template class.  */
1697       *targs_out = copy_node (DECL_TI_ARGS (fn));
1698       return DECL_TI_TEMPLATE (fn);
1699     }
1700
1701   /* It was a specialization of a template.  */
1702   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1703   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1704     {
1705       *targs_out = copy_node (targs);
1706       SET_TMPL_ARGS_LEVEL (*targs_out,
1707                            TMPL_ARGS_DEPTH (*targs_out),
1708                            TREE_PURPOSE (templates));
1709     }
1710   else
1711     *targs_out = TREE_PURPOSE (templates);
1712   return TREE_VALUE (templates);
1713 }
1714
1715 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1716    but with the default argument values filled in from those in the
1717    TMPL_TYPES.  */
1718
1719 static tree
1720 copy_default_args_to_explicit_spec_1 (tree spec_types,
1721                                       tree tmpl_types)
1722 {
1723   tree new_spec_types;
1724
1725   if (!spec_types)
1726     return NULL_TREE;
1727
1728   if (spec_types == void_list_node)
1729     return void_list_node;
1730
1731   /* Substitute into the rest of the list.  */
1732   new_spec_types =
1733     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1734                                           TREE_CHAIN (tmpl_types));
1735
1736   /* Add the default argument for this parameter.  */
1737   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1738                          TREE_VALUE (spec_types),
1739                          new_spec_types);
1740 }
1741
1742 /* DECL is an explicit specialization.  Replicate default arguments
1743    from the template it specializes.  (That way, code like:
1744
1745      template <class T> void f(T = 3);
1746      template <> void f(double);
1747      void g () { f (); }
1748
1749    works, as required.)  An alternative approach would be to look up
1750    the correct default arguments at the call-site, but this approach
1751    is consistent with how implicit instantiations are handled.  */
1752
1753 static void
1754 copy_default_args_to_explicit_spec (tree decl)
1755 {
1756   tree tmpl;
1757   tree spec_types;
1758   tree tmpl_types;
1759   tree new_spec_types;
1760   tree old_type;
1761   tree new_type;
1762   tree t;
1763   tree object_type = NULL_TREE;
1764   tree in_charge = NULL_TREE;
1765   tree vtt = NULL_TREE;
1766
1767   /* See if there's anything we need to do.  */
1768   tmpl = DECL_TI_TEMPLATE (decl);
1769   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1770   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1771     if (TREE_PURPOSE (t))
1772       break;
1773   if (!t)
1774     return;
1775
1776   old_type = TREE_TYPE (decl);
1777   spec_types = TYPE_ARG_TYPES (old_type);
1778
1779   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1780     {
1781       /* Remove the this pointer, but remember the object's type for
1782          CV quals.  */
1783       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1784       spec_types = TREE_CHAIN (spec_types);
1785       tmpl_types = TREE_CHAIN (tmpl_types);
1786
1787       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1788         {
1789           /* DECL may contain more parameters than TMPL due to the extra
1790              in-charge parameter in constructors and destructors.  */
1791           in_charge = spec_types;
1792           spec_types = TREE_CHAIN (spec_types);
1793         }
1794       if (DECL_HAS_VTT_PARM_P (decl))
1795         {
1796           vtt = spec_types;
1797           spec_types = TREE_CHAIN (spec_types);
1798         }
1799     }
1800
1801   /* Compute the merged default arguments.  */
1802   new_spec_types =
1803     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1804
1805   /* Compute the new FUNCTION_TYPE.  */
1806   if (object_type)
1807     {
1808       if (vtt)
1809         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1810                                          TREE_VALUE (vtt),
1811                                          new_spec_types);
1812
1813       if (in_charge)
1814         /* Put the in-charge parameter back.  */
1815         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1816                                          TREE_VALUE (in_charge),
1817                                          new_spec_types);
1818
1819       new_type = build_method_type_directly (object_type,
1820                                              TREE_TYPE (old_type),
1821                                              new_spec_types);
1822     }
1823   else
1824     new_type = build_function_type (TREE_TYPE (old_type),
1825                                     new_spec_types);
1826   new_type = cp_build_type_attribute_variant (new_type,
1827                                               TYPE_ATTRIBUTES (old_type));
1828   new_type = build_exception_variant (new_type,
1829                                       TYPE_RAISES_EXCEPTIONS (old_type));
1830   TREE_TYPE (decl) = new_type;
1831 }
1832
1833 /* Check to see if the function just declared, as indicated in
1834    DECLARATOR, and in DECL, is a specialization of a function
1835    template.  We may also discover that the declaration is an explicit
1836    instantiation at this point.
1837
1838    Returns DECL, or an equivalent declaration that should be used
1839    instead if all goes well.  Issues an error message if something is
1840    amiss.  Returns error_mark_node if the error is not easily
1841    recoverable.
1842
1843    FLAGS is a bitmask consisting of the following flags:
1844
1845    2: The function has a definition.
1846    4: The function is a friend.
1847
1848    The TEMPLATE_COUNT is the number of references to qualifying
1849    template classes that appeared in the name of the function.  For
1850    example, in
1851
1852      template <class T> struct S { void f(); };
1853      void S<int>::f();
1854
1855    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1856    classes are not counted in the TEMPLATE_COUNT, so that in
1857
1858      template <class T> struct S {};
1859      template <> struct S<int> { void f(); }
1860      template <> void S<int>::f();
1861
1862    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1863    invalid; there should be no template <>.)
1864
1865    If the function is a specialization, it is marked as such via
1866    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1867    is set up correctly, and it is added to the list of specializations
1868    for that template.  */
1869
1870 tree
1871 check_explicit_specialization (tree declarator,
1872                                tree decl,
1873                                int template_count,
1874                                int flags)
1875 {
1876   int have_def = flags & 2;
1877   int is_friend = flags & 4;
1878   int specialization = 0;
1879   int explicit_instantiation = 0;
1880   int member_specialization = 0;
1881   tree ctype = DECL_CLASS_CONTEXT (decl);
1882   tree dname = DECL_NAME (decl);
1883   tmpl_spec_kind tsk;
1884
1885   if (is_friend)
1886     {
1887       if (!processing_specialization)
1888         tsk = tsk_none;
1889       else
1890         tsk = tsk_excessive_parms;
1891     }
1892   else
1893     tsk = current_tmpl_spec_kind (template_count);
1894
1895   switch (tsk)
1896     {
1897     case tsk_none:
1898       if (processing_specialization)
1899         {
1900           specialization = 1;
1901           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1902         }
1903       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1904         {
1905           if (is_friend)
1906             /* This could be something like:
1907
1908                template <class T> void f(T);
1909                class S { friend void f<>(int); }  */
1910             specialization = 1;
1911           else
1912             {
1913               /* This case handles bogus declarations like template <>
1914                  template <class T> void f<int>(); */
1915
1916               error ("template-id %qD in declaration of primary template",
1917                      declarator);
1918               return decl;
1919             }
1920         }
1921       break;
1922
1923     case tsk_invalid_member_spec:
1924       /* The error has already been reported in
1925          check_specialization_scope.  */
1926       return error_mark_node;
1927
1928     case tsk_invalid_expl_inst:
1929       error ("template parameter list used in explicit instantiation");
1930
1931       /* Fall through.  */
1932
1933     case tsk_expl_inst:
1934       if (have_def)
1935         error ("definition provided for explicit instantiation");
1936
1937       explicit_instantiation = 1;
1938       break;
1939
1940     case tsk_excessive_parms:
1941     case tsk_insufficient_parms:
1942       if (tsk == tsk_excessive_parms)
1943         error ("too many template parameter lists in declaration of %qD",
1944                decl);
1945       else if (template_header_count)
1946         error("too few template parameter lists in declaration of %qD", decl);
1947       else
1948         error("explicit specialization of %qD must be introduced by "
1949               "%<template <>%>", decl);
1950
1951       /* Fall through.  */
1952     case tsk_expl_spec:
1953       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1954       if (ctype)
1955         member_specialization = 1;
1956       else
1957         specialization = 1;
1958       break;
1959
1960     case tsk_template:
1961       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1962         {
1963           /* This case handles bogus declarations like template <>
1964              template <class T> void f<int>(); */
1965
1966           if (uses_template_parms (declarator))
1967             error ("function template partial specialization %qD "
1968                    "is not allowed", declarator);
1969           else
1970             error ("template-id %qD in declaration of primary template",
1971                    declarator);
1972           return decl;
1973         }
1974
1975       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1976         /* This is a specialization of a member template, without
1977            specialization the containing class.  Something like:
1978
1979              template <class T> struct S {
1980                template <class U> void f (U);
1981              };
1982              template <> template <class U> void S<int>::f(U) {}
1983
1984            That's a specialization -- but of the entire template.  */
1985         specialization = 1;
1986       break;
1987
1988     default:
1989       gcc_unreachable ();
1990     }
1991
1992   if (specialization || member_specialization)
1993     {
1994       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
1995       for (; t; t = TREE_CHAIN (t))
1996         if (TREE_PURPOSE (t))
1997           {
1998             pedwarn
1999               ("default argument specified in explicit specialization");
2000             break;
2001           }
2002     }
2003
2004   if (specialization || member_specialization || explicit_instantiation)
2005     {
2006       tree tmpl = NULL_TREE;
2007       tree targs = NULL_TREE;
2008
2009       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2010       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2011         {
2012           tree fns;
2013
2014           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2015           if (ctype)
2016             fns = dname;
2017           else
2018             {
2019               /* If there is no class context, the explicit instantiation
2020                  must be at namespace scope.  */
2021               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2022
2023               /* Find the namespace binding, using the declaration
2024                  context.  */
2025               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2026                                            false, true);
2027               if (fns == error_mark_node || !is_overloaded_fn (fns))
2028                 {
2029                   error ("%qD is not a template function", dname);
2030                   fns = error_mark_node;
2031                 }
2032               else
2033                 {
2034                   tree fn = OVL_CURRENT (fns);
2035                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2036                                                 CP_DECL_CONTEXT (fn)))
2037                     error ("%qD is not declared in %qD",
2038                            decl, current_namespace);
2039                 }
2040             }
2041
2042           declarator = lookup_template_function (fns, NULL_TREE);
2043         }
2044
2045       if (declarator == error_mark_node)
2046         return error_mark_node;
2047
2048       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2049         {
2050           if (!explicit_instantiation)
2051             /* A specialization in class scope.  This is invalid,
2052                but the error will already have been flagged by
2053                check_specialization_scope.  */
2054             return error_mark_node;
2055           else
2056             {
2057               /* It's not valid to write an explicit instantiation in
2058                  class scope, e.g.:
2059
2060                    class C { template void f(); }
2061
2062                    This case is caught by the parser.  However, on
2063                    something like:
2064
2065                    template class C { void f(); };
2066
2067                    (which is invalid) we can get here.  The error will be
2068                    issued later.  */
2069               ;
2070             }
2071
2072           return decl;
2073         }
2074       else if (ctype != NULL_TREE
2075                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2076                    IDENTIFIER_NODE))
2077         {
2078           /* Find the list of functions in ctype that have the same
2079              name as the declared function.  */
2080           tree name = TREE_OPERAND (declarator, 0);
2081           tree fns = NULL_TREE;
2082           int idx;
2083
2084           if (constructor_name_p (name, ctype))
2085             {
2086               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2087
2088               if (is_constructor ? !TYPE_HAS_CONSTRUCTOR (ctype)
2089                   : !CLASSTYPE_DESTRUCTORS (ctype))
2090                 {
2091                   /* From [temp.expl.spec]:
2092
2093                      If such an explicit specialization for the member
2094                      of a class template names an implicitly-declared
2095                      special member function (clause _special_), the
2096                      program is ill-formed.
2097
2098                      Similar language is found in [temp.explicit].  */
2099                   error ("specialization of implicitly-declared special member function");
2100                   return error_mark_node;
2101                 }
2102
2103               name = is_constructor ? ctor_identifier : dtor_identifier;
2104             }
2105
2106           if (!DECL_CONV_FN_P (decl))
2107             {
2108               idx = lookup_fnfields_1 (ctype, name);
2109               if (idx >= 0)
2110                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2111             }
2112           else
2113             {
2114               VEC(tree,gc) *methods;
2115               tree ovl;
2116
2117               /* For a type-conversion operator, we cannot do a
2118                  name-based lookup.  We might be looking for `operator
2119                  int' which will be a specialization of `operator T'.
2120                  So, we find *all* the conversion operators, and then
2121                  select from them.  */
2122               fns = NULL_TREE;
2123
2124               methods = CLASSTYPE_METHOD_VEC (ctype);
2125               if (methods)
2126                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2127                      VEC_iterate (tree, methods, idx, ovl);
2128                      ++idx)
2129                   {
2130                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2131                       /* There are no more conversion functions.  */
2132                       break;
2133
2134                     /* Glue all these conversion functions together
2135                        with those we already have.  */
2136                     for (; ovl; ovl = OVL_NEXT (ovl))
2137                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2138                   }
2139             }
2140
2141           if (fns == NULL_TREE)
2142             {
2143               error ("no member function %qD declared in %qT", name, ctype);
2144               return error_mark_node;
2145             }
2146           else
2147             TREE_OPERAND (declarator, 0) = fns;
2148         }
2149
2150       /* Figure out what exactly is being specialized at this point.
2151          Note that for an explicit instantiation, even one for a
2152          member function, we cannot tell apriori whether the
2153          instantiation is for a member template, or just a member
2154          function of a template class.  Even if a member template is
2155          being instantiated, the member template arguments may be
2156          elided if they can be deduced from the rest of the
2157          declaration.  */
2158       tmpl = determine_specialization (declarator, decl,
2159                                        &targs,
2160                                        member_specialization,
2161                                        template_count,
2162                                        tsk);
2163
2164       if (!tmpl || tmpl == error_mark_node)
2165         /* We couldn't figure out what this declaration was
2166            specializing.  */
2167         return error_mark_node;
2168       else
2169         {
2170           tree gen_tmpl = most_general_template (tmpl);
2171
2172           if (explicit_instantiation)
2173             {
2174               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2175                  is done by do_decl_instantiation later.  */
2176
2177               int arg_depth = TMPL_ARGS_DEPTH (targs);
2178               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2179
2180               if (arg_depth > parm_depth)
2181                 {
2182                   /* If TMPL is not the most general template (for
2183                      example, if TMPL is a friend template that is
2184                      injected into namespace scope), then there will
2185                      be too many levels of TARGS.  Remove some of them
2186                      here.  */
2187                   int i;
2188                   tree new_targs;
2189
2190                   new_targs = make_tree_vec (parm_depth);
2191                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2192                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2193                       = TREE_VEC_ELT (targs, i);
2194                   targs = new_targs;
2195                 }
2196
2197               return instantiate_template (tmpl, targs, tf_error);
2198             }
2199
2200           /* If we thought that the DECL was a member function, but it
2201              turns out to be specializing a static member function,
2202              make DECL a static member function as well.  */
2203           if (DECL_STATIC_FUNCTION_P (tmpl)
2204               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2205             revert_static_member_fn (decl);
2206
2207           /* If this is a specialization of a member template of a
2208              template class, we want to return the TEMPLATE_DECL, not
2209              the specialization of it.  */
2210           if (tsk == tsk_template)
2211             {
2212               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2213               DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl)) = NULL_TREE;
2214               if (have_def)
2215                 {
2216                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2217                   DECL_SOURCE_LOCATION (DECL_TEMPLATE_RESULT (tmpl))
2218                     = DECL_SOURCE_LOCATION (decl);
2219                   /* We want to use the argument list specified in the
2220                      definition, not in the original declaration.  */
2221                   DECL_ARGUMENTS (DECL_TEMPLATE_RESULT (tmpl))
2222                     = DECL_ARGUMENTS (decl);
2223                 }
2224               return tmpl;
2225             }
2226
2227           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2228           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2229
2230           /* Inherit default function arguments from the template
2231              DECL is specializing.  */
2232           copy_default_args_to_explicit_spec (decl);
2233
2234           /* This specialization has the same protection as the
2235              template it specializes.  */
2236           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2237           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2238
2239           /* 7.1.1-1 [dcl.stc]
2240
2241              A storage-class-specifier shall not be specified in an
2242              explicit specialization...
2243
2244              The parser rejects these, so unless action is taken here,
2245              explicit function specializations will always appear with
2246              global linkage.
2247
2248              The action recommended by the C++ CWG in response to C++
2249              defect report 605 is to make the storage class and linkage
2250              of the explicit specialization match the templated function:
2251
2252              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2253            */
2254           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2255             {
2256               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2257               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2258
2259               /* This specialization has the same linkage and visibility as
2260                  the function template it specializes.  */
2261               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2262               if (! TREE_PUBLIC (decl))
2263                 {
2264                   DECL_INTERFACE_KNOWN (decl) = 1;
2265                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2266                 }
2267               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2268               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2269                 {
2270                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2271                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2272                 }
2273             }
2274
2275           /* If DECL is a friend declaration, declared using an
2276              unqualified name, the namespace associated with DECL may
2277              have been set incorrectly.  For example, in:
2278
2279                template <typename T> void f(T);
2280                namespace N {
2281                  struct S { friend void f<int>(int); }
2282                }
2283
2284              we will have set the DECL_CONTEXT for the friend
2285              declaration to N, rather than to the global namespace.  */
2286           if (DECL_NAMESPACE_SCOPE_P (decl))
2287             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2288
2289           if (is_friend && !have_def)
2290             /* This is not really a declaration of a specialization.
2291                It's just the name of an instantiation.  But, it's not
2292                a request for an instantiation, either.  */
2293             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2294           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2295             /* This is indeed a specialization.  In case of constructors
2296                and destructors, we need in-charge and not-in-charge
2297                versions in V3 ABI.  */
2298             clone_function_decl (decl, /*update_method_vec_p=*/0);
2299
2300           /* Register this specialization so that we can find it
2301              again.  */
2302           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2303         }
2304     }
2305
2306   return decl;
2307 }
2308
2309 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2310    parameters.  These are represented in the same format used for
2311    DECL_TEMPLATE_PARMS.  */
2312
2313 int
2314 comp_template_parms (const_tree parms1, const_tree parms2)
2315 {
2316   const_tree p1;
2317   const_tree p2;
2318
2319   if (parms1 == parms2)
2320     return 1;
2321
2322   for (p1 = parms1, p2 = parms2;
2323        p1 != NULL_TREE && p2 != NULL_TREE;
2324        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2325     {
2326       tree t1 = TREE_VALUE (p1);
2327       tree t2 = TREE_VALUE (p2);
2328       int i;
2329
2330       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2331       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2332
2333       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2334         return 0;
2335
2336       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2337         {
2338           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2339           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2340
2341           /* If either of the template parameters are invalid, assume
2342              they match for the sake of error recovery. */
2343           if (parm1 == error_mark_node || parm2 == error_mark_node)
2344             return 1;
2345
2346           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2347             return 0;
2348
2349           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2350               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2351                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2352             continue;
2353           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2354             return 0;
2355         }
2356     }
2357
2358   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2359     /* One set of parameters has more parameters lists than the
2360        other.  */
2361     return 0;
2362
2363   return 1;
2364 }
2365
2366 /* Determine whether PARM is a parameter pack.  */
2367 bool 
2368 template_parameter_pack_p (const_tree parm)
2369 {
2370   /* Determine if we have a non-type template parameter pack.  */
2371   if (TREE_CODE (parm) == PARM_DECL)
2372     return (DECL_TEMPLATE_PARM_P (parm) 
2373             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2374
2375   /* If this is a list of template parameters, we could get a
2376      TYPE_DECL or a TEMPLATE_DECL.  */ 
2377   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2378     parm = TREE_TYPE (parm);
2379
2380   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2381            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2382           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2383 }
2384
2385 /* Determine whether ARGS describes a variadic template args list,
2386    i.e., one that is terminated by a template argument pack.  */
2387 static bool 
2388 template_args_variadic_p (tree args)
2389 {
2390   int nargs;
2391   tree last_parm;
2392
2393   if (args == NULL_TREE)
2394     return false;
2395
2396   args = INNERMOST_TEMPLATE_ARGS (args);
2397   nargs = TREE_VEC_LENGTH (args);
2398
2399   if (nargs == 0)
2400     return false;
2401
2402   last_parm = TREE_VEC_ELT (args, nargs - 1);
2403
2404   return ARGUMENT_PACK_P (last_parm);
2405 }
2406
2407 /* Generate a new name for the parameter pack name NAME (an
2408    IDENTIFIER_NODE) that incorporates its */
2409 static tree
2410 make_ith_pack_parameter_name (tree name, int i)
2411 {
2412   /* Munge the name to include the parameter index.  */
2413   char numbuf[128];
2414   char* newname;
2415   
2416   sprintf(numbuf, "%i", i);
2417   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2418   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2419   return get_identifier (newname);
2420 }
2421
2422 /* Structure used to track the progress of find_parameter_packs_r.  */
2423 struct find_parameter_pack_data 
2424 {
2425   /* TREE_LIST that will contain all of the parameter packs found by
2426      the traversal.  */
2427   tree* parameter_packs;
2428
2429   /* Set of AST nodes that have been visited by the traversal.  */
2430   struct pointer_set_t *visited;
2431
2432   /* Whether we should replace parameter packs with
2433      ERROR_MARK_NODE. Used by check_for_bare_parameter_packs.  */
2434   bool set_packs_to_error;
2435 };
2436
2437 /* Identifies all of the argument packs that occur in a template
2438    argument and appends them to the TREE_LIST inside DATA, which is a
2439    find_parameter_pack_data structure. This is a subroutine of
2440    make_pack_expansion and uses_parameter_packs.  */
2441 static tree
2442 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2443 {
2444   tree t = *tp;
2445   struct find_parameter_pack_data* ppd = 
2446     (struct find_parameter_pack_data*)data;
2447   bool parameter_pack_p = false;
2448
2449   /* Don't visit nodes twice, except when we're clearing out parameter
2450      packs.  */
2451   if (pointer_set_contains (ppd->visited, *tp))
2452     {
2453       *walk_subtrees = 0;
2454       return NULL_TREE;
2455     }
2456
2457 recheck:
2458   /* Identify whether this is a parameter pack or not.  */
2459   switch (TREE_CODE (t))
2460     {
2461     case TEMPLATE_PARM_INDEX:
2462       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2463         parameter_pack_p = true;
2464       break;
2465
2466     case TEMPLATE_TYPE_PARM:
2467     case TEMPLATE_TEMPLATE_PARM:
2468       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2469         parameter_pack_p = true;
2470       break;
2471
2472     case PARM_DECL:
2473       if (FUNCTION_PARAMETER_PACK_P (t))
2474         {
2475           /* We don't want to walk into the type of a PARM_DECL,
2476              because we don't want to see the type parameter pack.  */
2477           *walk_subtrees = 0;
2478           parameter_pack_p = true;
2479         }
2480       break;
2481
2482     case POINTER_TYPE:
2483       if (ppd->set_packs_to_error)
2484         /* Pointer types are shared, set in that case the outermost
2485            POINTER_TYPE to error_mark_node rather than the parameter pack.  */
2486         {
2487           t = TREE_TYPE (t);
2488           goto recheck;
2489         }
2490       break;
2491
2492     default:
2493       /* Not a parameter pack.  */
2494       break;
2495     }
2496
2497   if (parameter_pack_p)
2498     {
2499       /* Add this parameter pack to the list.  */
2500       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2501
2502       if (ppd->set_packs_to_error)
2503         /* The caller requested that we set the parameter packs to
2504            ERROR_MARK_NODE so that they will not trip up the compiler
2505            later.  The caller is responsible for emitting an error.  */
2506         *tp = error_mark_node;
2507       else
2508         /* Make sure we do not visit this node again.  */
2509         pointer_set_insert (ppd->visited, *tp);
2510     }
2511   else
2512     /* Make sure we do not visit this node again.  */
2513     pointer_set_insert (ppd->visited, *tp);
2514
2515   if (TYPE_P (t))
2516     cp_walk_tree (&TYPE_CONTEXT (t), 
2517                   &find_parameter_packs_r, ppd, NULL);
2518
2519   /* This switch statement will return immediately if we don't find a
2520      parameter pack.  */
2521   switch (TREE_CODE (t)) 
2522     {
2523     case TEMPLATE_PARM_INDEX:
2524       return NULL_TREE;
2525
2526     case BOUND_TEMPLATE_TEMPLATE_PARM:
2527       /* Check the template itself.  */
2528       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2529                     &find_parameter_packs_r, ppd, NULL);
2530       /* Check the template arguments.  */
2531       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2532                     NULL);
2533       *walk_subtrees = 0;
2534       return NULL_TREE;
2535
2536     case TEMPLATE_TYPE_PARM:
2537     case TEMPLATE_TEMPLATE_PARM:
2538       return NULL_TREE;
2539
2540     case PARM_DECL:
2541       return NULL_TREE;
2542
2543     case RECORD_TYPE:
2544       if (TYPE_PTRMEMFUNC_P (t))
2545         return NULL_TREE;
2546       /* Fall through.  */
2547
2548     case UNION_TYPE:
2549     case ENUMERAL_TYPE:
2550       if (TYPE_TEMPLATE_INFO (t))
2551         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2552                       &find_parameter_packs_r, ppd, NULL);
2553
2554       *walk_subtrees = 0;
2555       return NULL_TREE;
2556
2557     case TEMPLATE_DECL:
2558       cp_walk_tree (&TREE_TYPE (t),
2559                     &find_parameter_packs_r, ppd, NULL);
2560       return NULL_TREE;
2561  
2562     case TYPENAME_TYPE:
2563       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2564                    ppd, NULL);
2565       *walk_subtrees = 0;
2566       return NULL_TREE;
2567       
2568     case TYPE_PACK_EXPANSION:
2569     case EXPR_PACK_EXPANSION:
2570       *walk_subtrees = 0;
2571       return NULL_TREE;
2572
2573     case INTEGER_TYPE:
2574       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2575                     ppd, NULL);
2576       *walk_subtrees = 0;
2577       return NULL_TREE;
2578
2579     default:
2580       return NULL_TREE;
2581     }
2582
2583   return NULL_TREE;
2584 }
2585
2586 /* Determines if the expression or type T uses any parameter packs.  */
2587 bool
2588 uses_parameter_packs (tree t)
2589 {
2590   tree parameter_packs = NULL_TREE;
2591   struct find_parameter_pack_data ppd;
2592   ppd.parameter_packs = &parameter_packs;
2593   ppd.visited = pointer_set_create ();
2594   ppd.set_packs_to_error = false;
2595   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, NULL);
2596   pointer_set_destroy (ppd.visited);
2597   return parameter_packs != NULL_TREE;
2598 }
2599
2600 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2601    representation a base-class initializer into a parameter pack
2602    expansion. If all goes well, the resulting node will be an
2603    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2604    respectively.  */
2605 tree 
2606 make_pack_expansion (tree arg)
2607 {
2608   tree result;
2609   tree parameter_packs = NULL_TREE;
2610   bool for_types = false;
2611   struct find_parameter_pack_data ppd;
2612
2613   ppd.set_packs_to_error = false;
2614
2615   if (!arg || arg == error_mark_node)
2616     return arg;
2617
2618   if (TREE_CODE (arg) == TREE_LIST)
2619     {
2620       /* The only time we will see a TREE_LIST here is for a base
2621          class initializer.  In this case, the TREE_PURPOSE will be a
2622          _TYPE node (representing the base class expansion we're
2623          initializing) and the TREE_VALUE will be a TREE_LIST
2624          containing the initialization arguments. 
2625
2626          The resulting expansion looks somewhat different from most
2627          expansions. Rather than returning just one _EXPANSION, we
2628          return a TREE_LIST whose TREE_PURPOSE is a
2629          TYPE_PACK_EXPANSION containing the bases that will be
2630          initialized.  The TREE_VALUE will be identical to the
2631          original TREE_VALUE, which is a list of arguments that will
2632          be passed to each base.  We do not introduce any new pack
2633          expansion nodes into the TREE_VALUE (although it is possible
2634          that some already exist), because the TREE_PURPOSE and
2635          TREE_VALUE all need to be expanded together with the same
2636          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2637          resulting TREE_PURPOSE will mention the parameter packs in
2638          both the bases and the arguments to the bases.  */
2639       tree purpose;
2640       tree value;
2641       tree parameter_packs = NULL_TREE;
2642
2643       /* Determine which parameter packs will be used by the base
2644          class expansion.  */
2645       ppd.visited = pointer_set_create ();
2646       ppd.parameter_packs = &parameter_packs;
2647       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2648                     &ppd, NULL);
2649
2650       if (parameter_packs == NULL_TREE)
2651         {
2652           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2653           pointer_set_destroy (ppd.visited);
2654           return error_mark_node;
2655         }
2656
2657       if (TREE_VALUE (arg) != void_type_node)
2658         {
2659           /* Collect the sets of parameter packs used in each of the
2660              initialization arguments.  */
2661           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2662             {
2663               /* Determine which parameter packs will be expanded in this
2664                  argument.  */
2665               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2666                             &ppd, NULL);
2667             }
2668         }
2669
2670       pointer_set_destroy (ppd.visited);
2671
2672       /* Create the pack expansion type for the base type.  */
2673       purpose = make_node (TYPE_PACK_EXPANSION);
2674       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2675       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2676
2677       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2678          they will rarely be compared to anything.  */
2679       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2680
2681       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2682     }
2683
2684   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2685     for_types = true;
2686
2687   /* Build the PACK_EXPANSION_* node.  */
2688   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2689   SET_PACK_EXPANSION_PATTERN (result, arg);
2690   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2691     {
2692       /* Propagate type and const-expression information.  */
2693       TREE_TYPE (result) = TREE_TYPE (arg);
2694       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2695     }
2696   else
2697     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2698        they will rarely be compared to anything.  */
2699     SET_TYPE_STRUCTURAL_EQUALITY (result);
2700
2701   /* Determine which parameter packs will be expanded.  */
2702   ppd.parameter_packs = &parameter_packs;
2703   ppd.visited = pointer_set_create ();
2704   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, NULL);
2705   pointer_set_destroy (ppd.visited);
2706
2707   /* Make sure we found some parameter packs.  */
2708   if (parameter_packs == NULL_TREE)
2709     {
2710       if (TYPE_P (arg))
2711         error ("expansion pattern %<%T%> contains no argument packs", arg);
2712       else
2713         error ("expansion pattern %<%E%> contains no argument packs", arg);
2714       return error_mark_node;
2715     }
2716   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2717
2718   return result;
2719 }
2720
2721 /* Checks T for any "bare" parameter packs, which have not yet been
2722    expanded, and issues an error if any are found. This operation can
2723    only be done on full expressions or types (e.g., an expression
2724    statement, "if" condition, etc.), because we could have expressions like:
2725
2726      foo(f(g(h(args)))...)
2727
2728    where "args" is a parameter pack. check_for_bare_parameter_packs
2729    should not be called for the subexpressions args, h(args),
2730    g(h(args)), or f(g(h(args))), because we would produce erroneous
2731    error messages. 
2732
2733    Returns TRUE if there were no bare parameter packs, returns FALSE
2734    (and emits an error) if there were bare parameter packs.*/
2735 bool 
2736 check_for_bare_parameter_packs (tree* t)
2737 {
2738   tree parameter_packs = NULL_TREE;
2739   struct find_parameter_pack_data ppd;
2740
2741   if (!processing_template_decl || !t || !*t || *t == error_mark_node)
2742     return true;
2743
2744   if (TREE_CODE (*t) == TYPE_DECL)
2745     t = &TREE_TYPE (*t);
2746
2747   ppd.parameter_packs = &parameter_packs;
2748   ppd.visited = pointer_set_create ();
2749   ppd.set_packs_to_error = false;
2750   cp_walk_tree (t, &find_parameter_packs_r, &ppd, NULL);
2751   pointer_set_destroy (ppd.visited);
2752
2753   if (parameter_packs) 
2754     {
2755       error ("parameter packs not expanded with `...':");
2756       while (parameter_packs)
2757         {
2758           tree pack = TREE_VALUE (parameter_packs);
2759           tree name = NULL_TREE;
2760
2761           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2762               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2763             name = TYPE_NAME (pack);
2764           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2765             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2766           else
2767             name = DECL_NAME (pack);
2768
2769           if (name)
2770             inform ("        %qD", name);
2771           else
2772             inform ("        <anonymous>");
2773
2774           parameter_packs = TREE_CHAIN (parameter_packs);
2775         }
2776
2777       /* Clean up any references to these parameter packs within the
2778          tree.  */
2779       ppd.parameter_packs = &parameter_packs;
2780       ppd.visited = pointer_set_create ();
2781       ppd.set_packs_to_error = true;
2782       cp_walk_tree (t, &find_parameter_packs_r, &ppd, NULL);
2783       pointer_set_destroy (ppd.visited);
2784
2785       return false;
2786     }
2787
2788   return true;
2789 }
2790
2791 /* Expand any parameter packs that occur in the template arguments in
2792    ARGS.  */
2793 tree
2794 expand_template_argument_pack (tree args)
2795 {
2796   tree result_args = NULL_TREE;
2797   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2798   int num_result_args = -1;
2799
2800   /* First, determine if we need to expand anything, and the number of
2801      slots we'll need.  */
2802   for (in_arg = 0; in_arg < nargs; ++in_arg)
2803     {
2804       tree arg = TREE_VEC_ELT (args, in_arg);
2805       if (ARGUMENT_PACK_P (arg))
2806         {
2807           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2808           if (num_result_args < 0)
2809             num_result_args = in_arg + num_packed;
2810           else
2811             num_result_args += num_packed;
2812         }
2813       else
2814         {
2815           if (num_result_args >= 0)
2816             num_result_args++;
2817         }
2818     }
2819
2820   /* If no expansion is necessary, we're done.  */
2821   if (num_result_args < 0)
2822     return args;
2823
2824   /* Expand arguments.  */
2825   result_args = make_tree_vec (num_result_args);
2826   for (in_arg = 0; in_arg < nargs; ++in_arg)
2827     {
2828       tree arg = TREE_VEC_ELT (args, in_arg);
2829       if (ARGUMENT_PACK_P (arg))
2830         {
2831           tree packed = ARGUMENT_PACK_ARGS (arg);
2832           int i, num_packed = TREE_VEC_LENGTH (packed);
2833           for (i = 0; i < num_packed; ++i, ++out_arg)
2834             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2835         }
2836       else
2837         {
2838           TREE_VEC_ELT (result_args, out_arg) = arg;
2839           ++out_arg;
2840         }
2841     }
2842
2843   return result_args;
2844 }
2845
2846 /* Complain if DECL shadows a template parameter.
2847
2848    [temp.local]: A template-parameter shall not be redeclared within its
2849    scope (including nested scopes).  */
2850
2851 void
2852 check_template_shadow (tree decl)
2853 {
2854   tree olddecl;
2855
2856   /* If we're not in a template, we can't possibly shadow a template
2857      parameter.  */
2858   if (!current_template_parms)
2859     return;
2860
2861   /* Figure out what we're shadowing.  */
2862   if (TREE_CODE (decl) == OVERLOAD)
2863     decl = OVL_CURRENT (decl);
2864   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2865
2866   /* If there's no previous binding for this name, we're not shadowing
2867      anything, let alone a template parameter.  */
2868   if (!olddecl)
2869     return;
2870
2871   /* If we're not shadowing a template parameter, we're done.  Note
2872      that OLDDECL might be an OVERLOAD (or perhaps even an
2873      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2874      node.  */
2875   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2876     return;
2877
2878   /* We check for decl != olddecl to avoid bogus errors for using a
2879      name inside a class.  We check TPFI to avoid duplicate errors for
2880      inline member templates.  */
2881   if (decl == olddecl
2882       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2883     return;
2884
2885   error ("declaration of %q+#D", decl);
2886   error (" shadows template parm %q+#D", olddecl);
2887 }
2888
2889 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2890    ORIG_LEVEL, DECL, and TYPE.  */
2891
2892 static tree
2893 build_template_parm_index (int index,
2894                            int level,
2895                            int orig_level,
2896                            tree decl,
2897                            tree type)
2898 {
2899   tree t = make_node (TEMPLATE_PARM_INDEX);
2900   TEMPLATE_PARM_IDX (t) = index;
2901   TEMPLATE_PARM_LEVEL (t) = level;
2902   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2903   TEMPLATE_PARM_DECL (t) = decl;
2904   TREE_TYPE (t) = type;
2905   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2906   TREE_INVARIANT (t) = TREE_INVARIANT (decl);
2907   TREE_READONLY (t) = TREE_READONLY (decl);
2908
2909   return t;
2910 }
2911
2912 /* Find the canonical type parameter for the given template type
2913    parameter.  Returns the canonical type parameter, which may be TYPE
2914    if no such parameter existed.  */
2915 static tree
2916 canonical_type_parameter (tree type)
2917 {
2918   tree list;
2919   int idx = TEMPLATE_TYPE_IDX (type);
2920   if (!canonical_template_parms)
2921     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2922
2923   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2924     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2925
2926   list = VEC_index (tree, canonical_template_parms, idx);
2927   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2928     list = TREE_CHAIN (list);
2929
2930   if (list)
2931     return TREE_VALUE (list);
2932   else
2933     {
2934       VEC_replace(tree, canonical_template_parms, idx,
2935                   tree_cons (NULL_TREE, type, 
2936                              VEC_index (tree, canonical_template_parms, idx)));
2937       return type;
2938     }
2939 }
2940
2941 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2942    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2943    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2944    new one is created.  */
2945
2946 static tree
2947 reduce_template_parm_level (tree index, tree type, int levels, tree args,
2948                             tsubst_flags_t complain)
2949 {
2950   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2951       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2952           != TEMPLATE_PARM_LEVEL (index) - levels))
2953     {
2954       tree orig_decl = TEMPLATE_PARM_DECL (index);
2955       tree decl, t;
2956
2957       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2958       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2959       TREE_INVARIANT (decl) = TREE_INVARIANT (orig_decl);
2960       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2961       DECL_ARTIFICIAL (decl) = 1;
2962       SET_DECL_TEMPLATE_PARM_P (decl);
2963
2964       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2965                                      TEMPLATE_PARM_LEVEL (index) - levels,
2966                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2967                                      decl, type);
2968       TEMPLATE_PARM_DESCENDANTS (index) = t;
2969       TEMPLATE_PARM_PARAMETER_PACK (t) 
2970         = TEMPLATE_PARM_PARAMETER_PACK (index);
2971
2972         /* Template template parameters need this.  */
2973       if (TREE_CODE (decl) == TEMPLATE_DECL)
2974         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
2975           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
2976            args, complain);
2977     }
2978
2979   return TEMPLATE_PARM_DESCENDANTS (index);
2980 }
2981
2982 /* Process information from new template parameter PARM and append it to the
2983    LIST being built.  This new parameter is a non-type parameter iff
2984    IS_NON_TYPE is true. This new parameter is a parameter
2985    pack iff IS_PARAMETER_PACK is true.  */
2986
2987 tree
2988 process_template_parm (tree list, tree parm, bool is_non_type, 
2989                        bool is_parameter_pack)
2990 {
2991   tree decl = 0;
2992   tree defval;
2993   tree err_parm_list;
2994   int idx = 0;
2995
2996   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2997   defval = TREE_PURPOSE (parm);
2998
2999   if (list)
3000     {
3001       tree p = tree_last (list);
3002
3003       if (p && TREE_VALUE (p) != error_mark_node)
3004         {
3005           p = TREE_VALUE (p);
3006           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3007             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3008           else
3009             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3010         }
3011
3012       ++idx;
3013     }
3014   else
3015     idx = 0;
3016
3017   if (is_non_type)
3018     {
3019       parm = TREE_VALUE (parm);
3020
3021       SET_DECL_TEMPLATE_PARM_P (parm);
3022
3023       if (TREE_TYPE (parm) == error_mark_node)
3024         {
3025           err_parm_list = build_tree_list (defval, parm);
3026           TREE_VALUE (err_parm_list) = error_mark_node;
3027            return chainon (list, err_parm_list);
3028         }
3029       else
3030       {
3031         /* [temp.param]
3032
3033            The top-level cv-qualifiers on the template-parameter are
3034            ignored when determining its type.  */
3035         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3036         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3037           {
3038             err_parm_list = build_tree_list (defval, parm);
3039             TREE_VALUE (err_parm_list) = error_mark_node;
3040              return chainon (list, err_parm_list);
3041           }
3042
3043         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3044           {
3045             /* This template parameter is not a parameter pack, but it
3046                should be. Complain about "bare" parameter packs.  */
3047             check_for_bare_parameter_packs (&TREE_TYPE (parm));
3048             
3049             /* Recover by calling this a parameter pack.  */
3050             is_parameter_pack = true;
3051           }
3052       }
3053
3054       /* A template parameter is not modifiable.  */
3055       TREE_CONSTANT (parm) = 1;
3056       TREE_INVARIANT (parm) = 1;
3057       TREE_READONLY (parm) = 1;
3058       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3059       TREE_CONSTANT (decl) = 1;
3060       TREE_INVARIANT (decl) = 1;
3061       TREE_READONLY (decl) = 1;
3062       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3063         = build_template_parm_index (idx, processing_template_decl,
3064                                      processing_template_decl,
3065                                      decl, TREE_TYPE (parm));
3066
3067       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3068         = is_parameter_pack;
3069     }
3070   else
3071     {
3072       tree t;
3073       parm = TREE_VALUE (TREE_VALUE (parm));
3074
3075       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3076         {
3077           t = make_aggr_type (TEMPLATE_TEMPLATE_PARM);
3078           /* This is for distinguishing between real templates and template
3079              template parameters */
3080           TREE_TYPE (parm) = t;
3081           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3082           decl = parm;
3083         }
3084       else
3085         {
3086           t = make_aggr_type (TEMPLATE_TYPE_PARM);
3087           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3088           decl = build_decl (TYPE_DECL, parm, t);
3089         }
3090
3091       TYPE_NAME (t) = decl;
3092       TYPE_STUB_DECL (t) = decl;
3093       parm = decl;
3094       TEMPLATE_TYPE_PARM_INDEX (t)
3095         = build_template_parm_index (idx, processing_template_decl,
3096                                      processing_template_decl,
3097                                      decl, TREE_TYPE (parm));
3098       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3099       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3100     }
3101   DECL_ARTIFICIAL (decl) = 1;
3102   SET_DECL_TEMPLATE_PARM_P (decl);
3103   pushdecl (decl);
3104   parm = build_tree_list (defval, parm);
3105   return chainon (list, parm);
3106 }
3107
3108 /* The end of a template parameter list has been reached.  Process the
3109    tree list into a parameter vector, converting each parameter into a more
3110    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3111    as PARM_DECLs.  */
3112
3113 tree
3114 end_template_parm_list (tree parms)
3115 {
3116   int nparms;
3117   tree parm, next;
3118   tree saved_parmlist = make_tree_vec (list_length (parms));
3119
3120   current_template_parms
3121     = tree_cons (size_int (processing_template_decl),
3122                  saved_parmlist, current_template_parms);
3123
3124   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3125     {
3126       next = TREE_CHAIN (parm);
3127       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3128       TREE_CHAIN (parm) = NULL_TREE;
3129     }
3130
3131   --processing_template_parmlist;
3132
3133   return saved_parmlist;
3134 }
3135
3136 /* end_template_decl is called after a template declaration is seen.  */
3137
3138 void
3139 end_template_decl (void)
3140 {
3141   reset_specialization ();
3142
3143   if (! processing_template_decl)
3144     return;
3145
3146   /* This matches the pushlevel in begin_template_parm_list.  */
3147   finish_scope ();
3148
3149   --processing_template_decl;
3150   current_template_parms = TREE_CHAIN (current_template_parms);
3151 }
3152
3153 /* Within the declaration of a template, return all levels of template
3154    parameters that apply.  The template parameters are represented as
3155    a TREE_VEC, in the form documented in cp-tree.h for template
3156    arguments.  */
3157
3158 static tree
3159 current_template_args (void)
3160 {
3161   tree header;
3162   tree args = NULL_TREE;
3163   int length = TMPL_PARMS_DEPTH (current_template_parms);
3164   int l = length;
3165
3166   /* If there is only one level of template parameters, we do not
3167      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3168      TREE_VEC containing the arguments.  */
3169   if (length > 1)
3170     args = make_tree_vec (length);
3171
3172   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3173     {
3174       tree a = copy_node (TREE_VALUE (header));
3175       int i;
3176
3177       TREE_TYPE (a) = NULL_TREE;
3178       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3179         {
3180           tree t = TREE_VEC_ELT (a, i);
3181
3182           /* T will be a list if we are called from within a
3183              begin/end_template_parm_list pair, but a vector directly
3184              if within a begin/end_member_template_processing pair.  */
3185           if (TREE_CODE (t) == TREE_LIST)
3186             {
3187               t = TREE_VALUE (t);
3188
3189               if (t != error_mark_node)
3190                 {
3191                   if (TREE_CODE (t) == TYPE_DECL
3192                       || TREE_CODE (t) == TEMPLATE_DECL)
3193                     {
3194                       t = TREE_TYPE (t);
3195                       
3196                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3197                         {
3198                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3199                              with a single element, which expands T.  */
3200                           tree vec = make_tree_vec (1);
3201                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3202                           
3203                           t = make_node (TYPE_ARGUMENT_PACK);
3204                           SET_ARGUMENT_PACK_ARGS (t, vec);
3205                         }
3206                     }
3207                   else
3208                     {
3209                       t = DECL_INITIAL (t);
3210                       
3211                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3212                         {
3213                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3214                              with a single element, which expands T.  */
3215                           tree vec = make_tree_vec (1);
3216                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3217                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3218                           
3219                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3220                           SET_ARGUMENT_PACK_ARGS (t, vec);
3221                           TREE_TYPE (t) = type;
3222                         }
3223                     }
3224                   TREE_VEC_ELT (a, i) = t;
3225                 }
3226             }
3227         }
3228
3229       if (length > 1)
3230         TREE_VEC_ELT (args, --l) = a;
3231       else
3232         args = a;
3233     }
3234
3235   return args;
3236 }
3237
3238 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3239    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3240    a member template.  Used by push_template_decl below.  */
3241
3242 static tree
3243 build_template_decl (tree decl, tree parms, bool member_template_p)
3244 {
3245   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3246   DECL_TEMPLATE_PARMS (tmpl) = parms;
3247   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3248   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3249   if (DECL_LANG_SPECIFIC (decl))
3250     {
3251       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3252       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3253       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3254       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3255       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3256       if (DECL_OVERLOADED_OPERATOR_P (decl))
3257         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3258                                       DECL_OVERLOADED_OPERATOR_P (decl));
3259     }
3260
3261   return tmpl;
3262 }
3263
3264 struct template_parm_data
3265 {
3266   /* The level of the template parameters we are currently
3267      processing.  */
3268   int level;
3269
3270   /* The index of the specialization argument we are currently
3271      processing.  */
3272   int current_arg;
3273
3274   /* An array whose size is the number of template parameters.  The
3275      elements are nonzero if the parameter has been used in any one
3276      of the arguments processed so far.  */
3277   int* parms;
3278
3279   /* An array whose size is the number of template arguments.  The
3280      elements are nonzero if the argument makes use of template
3281      parameters of this level.  */
3282   int* arg_uses_template_parms;
3283 };
3284
3285 /* Subroutine of push_template_decl used to see if each template
3286    parameter in a partial specialization is used in the explicit
3287    argument list.  If T is of the LEVEL given in DATA (which is
3288    treated as a template_parm_data*), then DATA->PARMS is marked
3289    appropriately.  */
3290
3291 static int
3292 mark_template_parm (tree t, void* data)
3293 {
3294   int level;
3295   int idx;
3296   struct template_parm_data* tpd = (struct template_parm_data*) data;
3297
3298   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3299     {
3300       level = TEMPLATE_PARM_LEVEL (t);
3301       idx = TEMPLATE_PARM_IDX (t);
3302     }
3303   else
3304     {
3305       level = TEMPLATE_TYPE_LEVEL (t);
3306       idx = TEMPLATE_TYPE_IDX (t);
3307     }
3308
3309   if (level == tpd->level)
3310     {
3311       tpd->parms[idx] = 1;
3312       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3313     }
3314
3315   /* Return zero so that for_each_template_parm will continue the
3316      traversal of the tree; we want to mark *every* template parm.  */
3317   return 0;
3318 }
3319
3320 /* Process the partial specialization DECL.  */
3321
3322 static tree
3323 process_partial_specialization (tree decl)
3324 {
3325   tree type = TREE_TYPE (decl);
3326   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3327   tree specargs = CLASSTYPE_TI_ARGS (type);
3328   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3329   tree inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3330   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3331   int nargs = TREE_VEC_LENGTH (inner_args);
3332   int ntparms = TREE_VEC_LENGTH (inner_parms);
3333   int  i;
3334   int did_error_intro = 0;
3335   struct template_parm_data tpd;
3336   struct template_parm_data tpd2;
3337
3338   /* We check that each of the template parameters given in the
3339      partial specialization is used in the argument list to the
3340      specialization.  For example:
3341
3342        template <class T> struct S;
3343        template <class T> struct S<T*>;
3344
3345      The second declaration is OK because `T*' uses the template
3346      parameter T, whereas
3347
3348        template <class T> struct S<int>;
3349
3350      is no good.  Even trickier is:
3351
3352        template <class T>
3353        struct S1
3354        {
3355           template <class U>
3356           struct S2;
3357           template <class U>
3358           struct S2<T>;
3359        };
3360
3361      The S2<T> declaration is actually invalid; it is a
3362      full-specialization.  Of course,
3363
3364           template <class U>
3365           struct S2<T (*)(U)>;
3366
3367      or some such would have been OK.  */
3368   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3369   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3370   memset (tpd.parms, 0, sizeof (int) * ntparms);
3371
3372   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3373   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3374   for (i = 0; i < nargs; ++i)
3375     {
3376       tpd.current_arg = i;
3377       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3378                               &mark_template_parm,
3379                               &tpd,
3380                               NULL);
3381     }
3382   for (i = 0; i < ntparms; ++i)
3383     if (tpd.parms[i] == 0)
3384       {
3385         /* One of the template parms was not used in the
3386            specialization.  */
3387         if (!did_error_intro)
3388           {
3389             error ("template parameters not used in partial specialization:");
3390             did_error_intro = 1;
3391           }
3392
3393         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3394       }
3395
3396   /* [temp.class.spec]
3397
3398      The argument list of the specialization shall not be identical to
3399      the implicit argument list of the primary template.  */
3400   if (comp_template_args
3401       (inner_args,
3402        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3403                                                    (maintmpl)))))
3404     error ("partial specialization %qT does not specialize any template arguments", type);
3405
3406   /* [temp.class.spec]
3407
3408      A partially specialized non-type argument expression shall not
3409      involve template parameters of the partial specialization except
3410      when the argument expression is a simple identifier.
3411
3412      The type of a template parameter corresponding to a specialized
3413      non-type argument shall not be dependent on a parameter of the
3414      specialization. 
3415
3416      Also, we verify that pack expansions only occur at the
3417      end of the argument list.  */
3418   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3419   tpd2.parms = 0;
3420   for (i = 0; i < nargs; ++i)
3421     {
3422       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3423       tree arg = TREE_VEC_ELT (inner_args, i);
3424       tree packed_args = NULL_TREE;
3425       int j, len = 1;
3426
3427       if (ARGUMENT_PACK_P (arg))
3428         {
3429           /* Extract the arguments from the argument pack. We'll be
3430              iterating over these in the following loop.  */
3431           packed_args = ARGUMENT_PACK_ARGS (arg);
3432           len = TREE_VEC_LENGTH (packed_args);
3433         }
3434
3435       for (j = 0; j < len; j++)
3436         {
3437           if (packed_args)
3438             /* Get the Jth argument in the parameter pack.  */
3439             arg = TREE_VEC_ELT (packed_args, j);
3440
3441           if (PACK_EXPANSION_P (arg))
3442             {
3443               /* Pack expansions must come at the end of the
3444                  argument list.  */
3445               if ((packed_args && j < len - 1)
3446                   || (!packed_args && i < nargs - 1))
3447                 {
3448                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3449                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3450                   else
3451                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3452
3453                   if (packed_args)
3454                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3455                 }
3456             }
3457
3458           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3459             /* We only care about the pattern.  */
3460             arg = PACK_EXPANSION_PATTERN (arg);
3461
3462           if (/* These first two lines are the `non-type' bit.  */
3463               !TYPE_P (arg)
3464               && TREE_CODE (arg) != TEMPLATE_DECL
3465               /* This next line is the `argument expression is not just a
3466                  simple identifier' condition and also the `specialized
3467                  non-type argument' bit.  */
3468               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3469             {
3470               if ((!packed_args && tpd.arg_uses_template_parms[i])
3471                   || (packed_args && uses_template_parms (arg)))
3472                 error ("template argument %qE involves template parameter(s)",
3473                        arg);
3474               else 
3475                 {
3476                   /* Look at the corresponding template parameter,
3477                      marking which template parameters its type depends
3478                      upon.  */
3479                   tree type = TREE_TYPE (parm);
3480
3481                   if (!tpd2.parms)
3482                     {
3483                       /* We haven't yet initialized TPD2.  Do so now.  */
3484                       tpd2.arg_uses_template_parms 
3485                         = (int *) alloca (sizeof (int) * nargs);
3486                       /* The number of parameters here is the number in the
3487                          main template, which, as checked in the assertion
3488                          above, is NARGS.  */
3489                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3490                       tpd2.level = 
3491                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3492                     }
3493
3494                   /* Mark the template parameters.  But this time, we're
3495                      looking for the template parameters of the main
3496                      template, not in the specialization.  */
3497                   tpd2.current_arg = i;
3498                   tpd2.arg_uses_template_parms[i] = 0;
3499                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3500                   for_each_template_parm (type,
3501                                           &mark_template_parm,
3502                                           &tpd2,
3503                                           NULL);
3504
3505                   if (tpd2.arg_uses_template_parms [i])
3506                     {
3507                       /* The type depended on some template parameters.
3508                          If they are fully specialized in the
3509                          specialization, that's OK.  */
3510                       int j;
3511                       for (j = 0; j < nargs; ++j)
3512                         if (tpd2.parms[j] != 0
3513                             && tpd.arg_uses_template_parms [j])
3514                           {
3515                             error ("type %qT of template argument %qE depends "
3516                                    "on template parameter(s)", 
3517                                    type,
3518                                    arg);
3519                             break;
3520                           }
3521                     }
3522                 }
3523             }
3524         }
3525     }
3526
3527   if (retrieve_specialization (maintmpl, specargs,
3528                                /*class_specializations_p=*/true))
3529     /* We've already got this specialization.  */
3530     return decl;
3531
3532   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3533     = tree_cons (specargs, inner_parms,
3534                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3535   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3536   return decl;
3537 }
3538
3539 /* Check that a template declaration's use of default arguments is not
3540    invalid.  Here, PARMS are the template parameters.  IS_PRIMARY is
3541    nonzero if DECL is the thing declared by a primary template.
3542    IS_PARTIAL is nonzero if DECL is a partial specialization.
3543    
3544
3545    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3546    declaration (but not a definition); 1 indicates a declaration, 2
3547    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3548    emitted for extraneous default arguments.
3549
3550    Returns TRUE if there were no errors found, FALSE otherwise. */
3551
3552 bool
3553 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3554                          int is_partial, int is_friend_decl)
3555 {
3556   const char *msg;
3557   int last_level_to_check;
3558   tree parm_level;
3559   bool no_errors = true;
3560
3561   /* [temp.param]
3562
3563      A default template-argument shall not be specified in a
3564      function template declaration or a function template definition, nor
3565      in the template-parameter-list of the definition of a member of a
3566      class template.  */
3567
3568   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3569     /* You can't have a function template declaration in a local
3570        scope, nor you can you define a member of a class template in a
3571        local scope.  */
3572     return true;
3573
3574   if (current_class_type
3575       && !TYPE_BEING_DEFINED (current_class_type)
3576       && DECL_LANG_SPECIFIC (decl)
3577       /* If this is either a friend defined in the scope of the class
3578          or a member function.  */
3579       && (DECL_FUNCTION_MEMBER_P (decl)
3580           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3581           : DECL_FRIEND_CONTEXT (decl)
3582           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3583           : false)
3584       /* And, if it was a member function, it really was defined in
3585          the scope of the class.  */
3586       && (!DECL_FUNCTION_MEMBER_P (decl)
3587           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3588     /* We already checked these parameters when the template was
3589        declared, so there's no need to do it again now.  This function
3590        was defined in class scope, but we're processing it's body now
3591        that the class is complete.  */
3592     return true;
3593
3594   /* Core issue 226 (C++0x only): the following only applies to class
3595      templates.  */
3596   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3597     {
3598       /* [temp.param]
3599
3600          If a template-parameter has a default template-argument, all
3601          subsequent template-parameters shall have a default
3602          template-argument supplied.  */
3603       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3604         {
3605           tree inner_parms = TREE_VALUE (parm_level);
3606           int ntparms = TREE_VEC_LENGTH (inner_parms);
3607           int seen_def_arg_p = 0;
3608           int i;
3609
3610           for (i = 0; i < ntparms; ++i)
3611             {
3612               tree parm = TREE_VEC_ELT (inner_parms, i);
3613
3614               if (parm == error_mark_node)
3615                 continue;
3616
3617               if (TREE_PURPOSE (parm))
3618                 seen_def_arg_p = 1;
3619               else if (seen_def_arg_p)
3620                 {
3621                   error ("no default argument for %qD", TREE_VALUE (parm));
3622                   /* For better subsequent error-recovery, we indicate that
3623                      there should have been a default argument.  */
3624                   TREE_PURPOSE (parm) = error_mark_node;
3625                   no_errors = false;
3626                 }
3627             }
3628         }
3629     }
3630
3631   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3632       || is_partial 
3633       || !is_primary
3634       || is_friend_decl)
3635     /* For an ordinary class template, default template arguments are
3636        allowed at the innermost level, e.g.:
3637          template <class T = int>
3638          struct S {};
3639        but, in a partial specialization, they're not allowed even
3640        there, as we have in [temp.class.spec]:
3641
3642          The template parameter list of a specialization shall not
3643          contain default template argument values.
3644
3645        So, for a partial specialization, or for a function template
3646        (in C++98/C++03), we look at all of them.  */
3647     ;
3648   else
3649     /* But, for a primary class template that is not a partial
3650        specialization we look at all template parameters except the
3651        innermost ones.  */
3652     parms = TREE_CHAIN (parms);
3653
3654   /* Figure out what error message to issue.  */
3655   if (is_friend_decl == 2)
3656     msg = "default template arguments may not be used in function template friend re-declaration";
3657   else if (is_friend_decl)
3658     msg = "default template arguments may not be used in function template friend declarations";
3659   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3660     msg = "default template arguments may not be used in function templates";
3661   else if (is_partial)
3662     msg = "default template arguments may not be used in partial specializations";
3663   else
3664     msg = "default argument for template parameter for class enclosing %qD";
3665
3666   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3667     /* If we're inside a class definition, there's no need to
3668        examine the parameters to the class itself.  On the one
3669        hand, they will be checked when the class is defined, and,
3670        on the other, default arguments are valid in things like:
3671          template <class T = double>
3672          struct S { template <class U> void f(U); };
3673        Here the default argument for `S' has no bearing on the
3674        declaration of `f'.  */
3675     last_level_to_check = template_class_depth (current_class_type) + 1;
3676   else
3677     /* Check everything.  */
3678     last_level_to_check = 0;
3679
3680   for (parm_level = parms;
3681        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3682        parm_level = TREE_CHAIN (parm_level))
3683     {
3684       tree inner_parms = TREE_VALUE (parm_level);
3685       int i;
3686       int ntparms;
3687
3688       ntparms = TREE_VEC_LENGTH (inner_parms);
3689       for (i = 0; i < ntparms; ++i)
3690         {
3691           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3692             continue;
3693
3694           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3695             {
3696               if (msg)
3697                 {
3698                   no_errors = false;
3699                   if (is_friend_decl == 2)
3700                     return no_errors;
3701
3702                   error (msg, decl);
3703                   msg = 0;
3704                 }
3705
3706               /* Clear out the default argument so that we are not
3707                  confused later.  */
3708               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3709             }
3710         }
3711
3712       /* At this point, if we're still interested in issuing messages,
3713          they must apply to classes surrounding the object declared.  */
3714       if (msg)
3715         msg = "default argument for template parameter for class enclosing %qD";
3716     }
3717
3718   return no_errors;
3719 }
3720
3721 /* Worker for push_template_decl_real, called via
3722    for_each_template_parm.  DATA is really an int, indicating the
3723    level of the parameters we are interested in.  If T is a template
3724    parameter of that level, return nonzero.  */
3725
3726 static int
3727 template_parm_this_level_p (tree t, void* data)
3728 {
3729   int this_level = *(int *)data;
3730   int level;
3731
3732   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3733     level = TEMPLATE_PARM_LEVEL (t);
3734   else
3735     level = TEMPLATE_TYPE_LEVEL (t);
3736   return level == this_level;
3737 }
3738
3739 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3740    parameters given by current_template_args, or reuses a
3741    previously existing one, if appropriate.  Returns the DECL, or an
3742    equivalent one, if it is replaced via a call to duplicate_decls.
3743
3744    If IS_FRIEND is true, DECL is a friend declaration.  */
3745
3746 tree
3747 push_template_decl_real (tree decl, bool is_friend)
3748 {
3749   tree tmpl;
3750   tree args;
3751   tree info;
3752   tree ctx;
3753   int primary;
3754   int is_partial;
3755   int new_template_p = 0;
3756   /* True if the template is a member template, in the sense of
3757      [temp.mem].  */
3758   bool member_template_p = false;
3759
3760   if (decl == error_mark_node)
3761     return decl;
3762
3763   /* See if this is a partial specialization.  */
3764   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3765                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3766                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3767
3768   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3769     is_friend = true;
3770
3771   if (is_friend)
3772     /* For a friend, we want the context of the friend function, not
3773        the type of which it is a friend.  */
3774     ctx = DECL_CONTEXT (decl);
3775   else if (CP_DECL_CONTEXT (decl)
3776            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3777     /* In the case of a virtual function, we want the class in which
3778        it is defined.  */
3779     ctx = CP_DECL_CONTEXT (decl);
3780   else
3781     /* Otherwise, if we're currently defining some class, the DECL
3782        is assumed to be a member of the class.  */
3783     ctx = current_scope ();
3784
3785   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3786     ctx = NULL_TREE;
3787
3788   if (!DECL_CONTEXT (decl))
3789     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3790
3791   /* See if this is a primary template.  */
3792   if (is_friend && ctx)
3793     /* A friend template that specifies a class context, i.e.
3794          template <typename T> friend void A<T>::f();
3795        is not primary.  */
3796     primary = 0;
3797   else
3798     primary = template_parm_scope_p ();
3799
3800   if (primary)
3801     {
3802       if (DECL_CLASS_SCOPE_P (decl))
3803         member_template_p = true;
3804       if (TREE_CODE (decl) == TYPE_DECL
3805           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3806         error ("template class without a name");
3807       else if (TREE_CODE (decl) == FUNCTION_DECL)
3808         {
3809           if (DECL_DESTRUCTOR_P (decl))
3810             {
3811               /* [temp.mem]
3812
3813                  A destructor shall not be a member template.  */
3814               error ("destructor %qD declared as member template", decl);
3815               return error_mark_node;
3816             }
3817           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3818               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3819                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3820                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3821                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3822                       == void_list_node)))
3823             {
3824               /* [basic.stc.dynamic.allocation]
3825
3826                  An allocation function can be a function
3827                  template. ... Template allocation functions shall
3828                  have two or more parameters.  */
3829               error ("invalid template declaration of %qD", decl);
3830               return error_mark_node;
3831             }
3832         }
3833       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3834                && CLASS_TYPE_P (TREE_TYPE (decl)))
3835         /* OK */;
3836       else
3837         {
3838           error ("template declaration of %q#D", decl);
3839           return error_mark_node;
3840         }
3841     }
3842
3843   /* Check to see that the rules regarding the use of default
3844      arguments are not being violated.  */
3845   check_default_tmpl_args (decl, current_template_parms,
3846                            primary, is_partial, /*is_friend_decl=*/0);
3847
3848   /* Ensure that there are no parameter packs in the type of this
3849      declaration that have not been expanded.  */
3850   if (TREE_CODE (decl) == FUNCTION_DECL)
3851     {
3852       /* Check each of the arguments individually to see if there are
3853          any bare parameter packs.  */
3854       tree type = TREE_TYPE (decl);
3855       tree arg = DECL_ARGUMENTS (decl);
3856       tree argtype = TYPE_ARG_TYPES (type);
3857
3858       while (arg && argtype)
3859         {
3860           if (!FUNCTION_PARAMETER_PACK_P (arg)
3861               && !check_for_bare_parameter_packs (&TREE_TYPE (arg)))
3862             {
3863             /* This is a PARM_DECL that contains unexpanded parameter
3864                packs. We have already complained about this in the
3865                check_for_bare_parameter_packs call, so just replace
3866                these types with ERROR_MARK_NODE.  */
3867               TREE_TYPE (arg) = error_mark_node;
3868               TREE_VALUE (argtype) = error_mark_node;
3869             }
3870
3871           arg = TREE_CHAIN (arg);
3872           argtype = TREE_CHAIN (argtype);
3873         }
3874
3875       /* Check for bare parameter packs in the return type and the
3876          exception specifiers.  */
3877       if (!check_for_bare_parameter_packs (&TREE_TYPE (type)))
3878         /* Errors were already issued, set return type to int
3879            as the frontend doesn't expect error_mark_node as
3880            the return type.  */
3881         TREE_TYPE (type) = integer_type_node;
3882       check_for_bare_parameter_packs (&TYPE_RAISES_EXCEPTIONS (type));
3883     }
3884   else if (!check_for_bare_parameter_packs (&TREE_TYPE (decl)))
3885     return error_mark_node;
3886
3887   if (is_partial)
3888     return process_partial_specialization (decl);
3889
3890   /* A primary class template can only have one parameter pack, at the
3891      end of the template parameter list.  */
3892   if (primary && TREE_CODE (decl) == TYPE_DECL)
3893     {
3894       tree inner_parms 
3895         = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3896       int i, len = TREE_VEC_LENGTH (inner_parms);
3897       for (i = 0; i < len - 1; i++)
3898         {
3899           tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
3900
3901           if (template_parameter_pack_p (parm))
3902             {
3903               if (TREE_CODE (parm) == PARM_DECL)
3904                 error ("parameter pack %qE must be at the end of the"
3905                        " template parameter list", parm);
3906               else
3907                 error ("parameter pack %qT must be at the end of the"
3908                        " template parameter list", TREE_TYPE (parm));
3909
3910               TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) = error_mark_node;
3911             }
3912         }
3913     }
3914
3915   args = current_template_args ();
3916
3917   if (!ctx
3918       || TREE_CODE (ctx) == FUNCTION_DECL
3919       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3920       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3921     {
3922       if (DECL_LANG_SPECIFIC (decl)
3923           && DECL_TEMPLATE_INFO (decl)
3924           && DECL_TI_TEMPLATE (decl))
3925         tmpl = DECL_TI_TEMPLATE (decl);
3926       /* If DECL is a TYPE_DECL for a class-template, then there won't
3927          be DECL_LANG_SPECIFIC.  The information equivalent to
3928          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3929       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3930                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3931                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3932         {
3933           /* Since a template declaration already existed for this
3934              class-type, we must be redeclaring it here.  Make sure
3935              that the redeclaration is valid.  */
3936           redeclare_class_template (TREE_TYPE (decl),
3937                                     current_template_parms);
3938           /* We don't need to create a new TEMPLATE_DECL; just use the
3939              one we already had.  */
3940           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3941         }
3942       else
3943         {
3944           tmpl = build_template_decl (decl, current_template_parms,
3945                                       member_template_p);
3946           new_template_p = 1;
3947
3948           if (DECL_LANG_SPECIFIC (decl)
3949               && DECL_TEMPLATE_SPECIALIZATION (decl))
3950             {
3951               /* A specialization of a member template of a template
3952                  class.  */
3953               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3954               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3955               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3956             }
3957         }
3958     }
3959   else
3960     {
3961       tree a, t, current, parms;
3962       int i;
3963       tree tinfo = get_template_info (decl);
3964
3965       if (!tinfo)
3966         {
3967           error ("template definition of non-template %q#D", decl);
3968           return decl;
3969         }
3970
3971       tmpl = TI_TEMPLATE (tinfo);
3972
3973       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3974           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3975           && DECL_TEMPLATE_SPECIALIZATION (decl)
3976           && DECL_MEMBER_TEMPLATE_P (tmpl))
3977         {
3978           tree new_tmpl;
3979
3980           /* The declaration is a specialization of a member
3981              template, declared outside the class.  Therefore, the
3982              innermost template arguments will be NULL, so we
3983              replace them with the arguments determined by the
3984              earlier call to check_explicit_specialization.  */
3985           args = DECL_TI_ARGS (decl);
3986
3987           new_tmpl
3988             = build_template_decl (decl, current_template_parms,
3989                                    member_template_p);
3990           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3991           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3992           DECL_TI_TEMPLATE (decl) = new_tmpl;
3993           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3994           DECL_TEMPLATE_INFO (new_tmpl)
3995             = tree_cons (tmpl, args, NULL_TREE);
3996
3997           register_specialization (new_tmpl,
3998                                    most_general_template (tmpl),
3999                                    args,
4000                                    is_friend);
4001           return decl;
4002         }
4003
4004       /* Make sure the template headers we got make sense.  */
4005
4006       parms = DECL_TEMPLATE_PARMS (tmpl);
4007       i = TMPL_PARMS_DEPTH (parms);
4008       if (TMPL_ARGS_DEPTH (args) != i)
4009         {
4010           error ("expected %d levels of template parms for %q#D, got %d",
4011                  i, decl, TMPL_ARGS_DEPTH (args));
4012         }
4013       else
4014         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4015           {
4016             a = TMPL_ARGS_LEVEL (args, i);
4017             t = INNERMOST_TEMPLATE_PARMS (parms);
4018
4019             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4020               {
4021                 if (current == decl)
4022                   error ("got %d template parameters for %q#D",
4023                          TREE_VEC_LENGTH (a), decl);
4024                 else
4025                   error ("got %d template parameters for %q#T",
4026                          TREE_VEC_LENGTH (a), current);
4027                 error ("  but %d required", TREE_VEC_LENGTH (t));
4028                 return error_mark_node;
4029               }
4030
4031             if (current == decl)
4032               current = ctx;
4033             else
4034               current = (TYPE_P (current)
4035                          ? TYPE_CONTEXT (current)
4036                          : DECL_CONTEXT (current));
4037           }
4038
4039       /* Check that the parms are used in the appropriate qualifying scopes
4040          in the declarator.  */
4041       if (!comp_template_args
4042           (TI_ARGS (tinfo),
4043            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4044         {
4045           error ("\
4046 template arguments to %qD do not match original template %qD",
4047                  decl, DECL_TEMPLATE_RESULT (tmpl));
4048           if (!uses_template_parms (TI_ARGS (tinfo)))
4049             inform ("use template<> for an explicit specialization");
4050           /* Avoid crash in import_export_decl.  */
4051           DECL_INTERFACE_KNOWN (decl) = 1;
4052           return error_mark_node;
4053         }
4054     }
4055
4056   DECL_TEMPLATE_RESULT (tmpl) = decl;
4057   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4058
4059   /* Push template declarations for global functions and types.  Note
4060      that we do not try to push a global template friend declared in a
4061      template class; such a thing may well depend on the template
4062      parameters of the class.  */
4063   if (new_template_p && !ctx
4064       && !(is_friend && template_class_depth (current_class_type) > 0))
4065     {
4066       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4067       if (tmpl == error_mark_node)
4068         return error_mark_node;
4069
4070       /* Hide template friend classes that haven't been declared yet.  */
4071       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4072         {
4073           DECL_ANTICIPATED (tmpl) = 1;
4074           DECL_FRIEND_P (tmpl) = 1;
4075         }
4076     }
4077
4078   if (primary)
4079     {
4080       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4081       int i;
4082
4083       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4084       if (DECL_CONV_FN_P (tmpl))
4085         {
4086           int depth = TMPL_PARMS_DEPTH (parms);
4087
4088           /* It is a conversion operator. See if the type converted to
4089              depends on innermost template operands.  */
4090
4091           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4092                                          depth))
4093             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4094         }
4095
4096       /* Give template template parms a DECL_CONTEXT of the template
4097          for which they are a parameter.  */
4098       parms = INNERMOST_TEMPLATE_PARMS (parms);
4099       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4100         {
4101           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4102           if (TREE_CODE (parm) == TEMPLATE_DECL)
4103             DECL_CONTEXT (parm) = tmpl;
4104         }
4105     }
4106
4107   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4108      back to its most general template.  If TMPL is a specialization,
4109      ARGS may only have the innermost set of arguments.  Add the missing
4110      argument levels if necessary.  */
4111   if (DECL_TEMPLATE_INFO (tmpl))
4112     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4113
4114   info = tree_cons (tmpl, args, NULL_TREE);
4115
4116   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4117     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4118   else if (DECL_LANG_SPECIFIC (decl))
4119     DECL_TEMPLATE_INFO (decl) = info;
4120
4121   return DECL_TEMPLATE_RESULT (tmpl);
4122 }
4123
4124 tree
4125 push_template_decl (tree decl)
4126 {
4127   return push_template_decl_real (decl, false);
4128 }
4129
4130 /* Called when a class template TYPE is redeclared with the indicated
4131    template PARMS, e.g.:
4132
4133      template <class T> struct S;
4134      template <class T> struct S {};  */
4135
4136 bool
4137 redeclare_class_template (tree type, tree parms)
4138 {
4139   tree tmpl;
4140   tree tmpl_parms;
4141   int i;
4142
4143   if (!TYPE_TEMPLATE_INFO (type))
4144     {
4145       error ("%qT is not a template type", type);
4146       return false;
4147     }
4148
4149   tmpl = TYPE_TI_TEMPLATE (type);
4150   if (!PRIMARY_TEMPLATE_P (tmpl))
4151     /* The type is nested in some template class.  Nothing to worry
4152        about here; there are no new template parameters for the nested
4153        type.  */
4154     return true;
4155
4156   if (!parms)
4157     {
4158       error ("template specifiers not specified in declaration of %qD",
4159              tmpl);
4160       return false;
4161     }
4162
4163   parms = INNERMOST_TEMPLATE_PARMS (parms);
4164   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4165
4166   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4167     {
4168       error ("redeclared with %d template parameter(s)", 
4169              TREE_VEC_LENGTH (parms));
4170       inform ("previous declaration %q+D used %d template parameter(s)", 
4171              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4172       return false;
4173     }
4174
4175   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4176     {
4177       tree tmpl_parm;
4178       tree parm;
4179       tree tmpl_default;
4180       tree parm_default;
4181
4182       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4183           || TREE_VEC_ELT (parms, i) == error_mark_node)
4184         continue;
4185
4186       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4187       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4188       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4189       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4190
4191       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4192          TEMPLATE_DECL.  */
4193       if (tmpl_parm != error_mark_node
4194            && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4195            || (TREE_CODE (tmpl_parm) != TYPE_DECL
4196                && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))))
4197         {
4198           error ("template parameter %q+#D", tmpl_parm);
4199           error ("redeclared here as %q#D", parm);
4200           return false;
4201         }
4202
4203       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4204         {
4205           /* We have in [temp.param]:
4206
4207              A template-parameter may not be given default arguments
4208              by two different declarations in the same scope.  */
4209           error ("redefinition of default argument for %q#D", parm);
4210           inform ("%Joriginal definition appeared here", tmpl_parm);
4211           return false;
4212         }
4213
4214       if (parm_default != NULL_TREE)
4215         /* Update the previous template parameters (which are the ones
4216            that will really count) with the new default value.  */
4217         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4218       else if (tmpl_default != NULL_TREE)
4219         /* Update the new parameters, too; they'll be used as the
4220            parameters for any members.  */
4221         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4222     }
4223
4224     return true;
4225 }
4226
4227 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4228    (possibly simplified) expression.  */
4229
4230 tree
4231 fold_non_dependent_expr (tree expr)
4232 {
4233   if (expr == NULL_TREE)
4234     return NULL_TREE;
4235
4236   /* If we're in a template, but EXPR isn't value dependent, simplify
4237      it.  We're supposed to treat:
4238
4239        template <typename T> void f(T[1 + 1]);
4240        template <typename T> void f(T[2]);
4241
4242      as two declarations of the same function, for example.  */
4243   if (processing_template_decl
4244       && !type_dependent_expression_p (expr)
4245       && !value_dependent_expression_p (expr))
4246     {
4247       HOST_WIDE_INT saved_processing_template_decl;
4248
4249       saved_processing_template_decl = processing_template_decl;
4250       processing_template_decl = 0;
4251       expr = tsubst_copy_and_build (expr,
4252                                     /*args=*/NULL_TREE,
4253                                     tf_error,
4254                                     /*in_decl=*/NULL_TREE,
4255                                     /*function_p=*/false,
4256                                     /*integral_constant_expression_p=*/true);
4257       processing_template_decl = saved_processing_template_decl;
4258     }
4259   return expr;
4260 }
4261
4262 /* EXPR is an expression which is used in a constant-expression context.
4263    For instance, it could be a VAR_DECL with a constant initializer.
4264    Extract the innest constant expression.
4265
4266    This is basically a more powerful version of
4267    integral_constant_value, which can be used also in templates where
4268    initializers can maintain a syntactic rather than semantic form
4269    (even if they are non-dependent, for access-checking purposes).  */
4270
4271 static tree
4272 fold_decl_constant_value (tree expr)
4273 {
4274   tree const_expr = expr;
4275   do
4276     {
4277       expr = fold_non_dependent_expr (const_expr);
4278       const_expr = integral_constant_value (expr);
4279     }
4280   while (expr != const_expr);
4281
4282   return expr;
4283 }
4284
4285 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4286    must be a function or a pointer-to-function type, as specified
4287    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4288    and check that the resulting function has external linkage.  */
4289
4290 static tree
4291 convert_nontype_argument_function (tree type, tree expr)
4292 {
4293   tree fns = expr;
4294   tree fn, fn_no_ptr;
4295
4296   fn = instantiate_type (type, fns, tf_none);
4297   if (fn == error_mark_node)
4298     return error_mark_node;
4299
4300   fn_no_ptr = fn;
4301   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4302     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4303   if (TREE_CODE (fn_no_ptr) == BASELINK)
4304     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4305  
4306   /* [temp.arg.nontype]/1
4307
4308      A template-argument for a non-type, non-template template-parameter
4309      shall be one of:
4310      [...]
4311      -- the address of an object or function with external linkage.  */
4312   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4313     {
4314       error ("%qE is not a valid template argument for type %qT "
4315              "because function %qD has not external linkage",
4316              expr, type, fn_no_ptr);
4317       return NULL_TREE;
4318     }
4319
4320   return fn;
4321 }
4322
4323 /* Attempt to convert the non-type template parameter EXPR to the
4324    indicated TYPE.  If the conversion is successful, return the
4325    converted value.  If the conversion is unsuccessful, return
4326    NULL_TREE if we issued an error message, or error_mark_node if we
4327    did not.  We issue error messages for out-and-out bad template
4328    parameters, but not simply because the conversion failed, since we
4329    might be just trying to do argument deduction.  Both TYPE and EXPR
4330    must be non-dependent.
4331
4332    The conversion follows the special rules described in
4333    [temp.arg.nontype], and it is much more strict than an implicit
4334    conversion.
4335
4336    This function is called twice for each template argument (see
4337    lookup_template_class for a more accurate description of this
4338    problem). This means that we need to handle expressions which
4339    are not valid in a C++ source, but can be created from the
4340    first call (for instance, casts to perform conversions). These
4341    hacks can go away after we fix the double coercion problem.  */
4342
4343 static tree
4344 convert_nontype_argument (tree type, tree expr)
4345 {
4346   tree expr_type;
4347
4348   /* Detect immediately string literals as invalid non-type argument.
4349      This special-case is not needed for correctness (we would easily
4350      catch this later), but only to provide better diagnostic for this
4351      common user mistake. As suggested by DR 100, we do not mention
4352      linkage issues in the diagnostic as this is not the point.  */
4353   if (TREE_CODE (expr) == STRING_CST)
4354     {
4355       error ("%qE is not a valid template argument for type %qT "
4356              "because string literals can never be used in this context",
4357              expr, type);
4358       return NULL_TREE;
4359     }
4360
4361   /* If we are in a template, EXPR may be non-dependent, but still
4362      have a syntactic, rather than semantic, form.  For example, EXPR
4363      might be a SCOPE_REF, rather than the VAR_DECL to which the
4364      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4365      so that access checking can be performed when the template is
4366      instantiated -- but here we need the resolved form so that we can
4367      convert the argument.  */
4368   expr = fold_non_dependent_expr (expr);
4369   if (error_operand_p (expr))
4370     return error_mark_node;
4371   expr_type = TREE_TYPE (expr);
4372
4373   /* HACK: Due to double coercion, we can get a
4374      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4375      which is the tree that we built on the first call (see
4376      below when coercing to reference to object or to reference to
4377      function). We just strip everything and get to the arg.
4378      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4379      for examples.  */
4380   if (TREE_CODE (expr) == NOP_EXPR)
4381     {
4382       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4383         {
4384           /* ??? Maybe we could use convert_from_reference here, but we
4385              would need to relax its constraints because the NOP_EXPR
4386              could actually change the type to something more cv-qualified,
4387              and this is not folded by convert_from_reference.  */
4388           tree addr = TREE_OPERAND (expr, 0);
4389           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4390           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4391           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4392           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4393                       (TREE_TYPE (expr_type),
4394                        TREE_TYPE (TREE_TYPE (addr))));
4395
4396           expr = TREE_OPERAND (addr, 0);
4397           expr_type = TREE_TYPE (expr);
4398         }
4399
4400       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4401          parameter is a pointer to object, through decay and
4402          qualification conversion. Let's strip everything.  */
4403       else if (TYPE_PTROBV_P (type))
4404         {
4405           STRIP_NOPS (expr);
4406           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4407           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4408           /* Skip the ADDR_EXPR only if it is part of the decay for
4409              an array. Otherwise, it is part of the original argument
4410              in the source code.  */
4411           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4412             expr = TREE_OPERAND (expr, 0);
4413           expr_type = TREE_TYPE (expr);
4414         }
4415     }
4416
4417   /* [temp.arg.nontype]/5, bullet 1
4418
4419      For a non-type template-parameter of integral or enumeration type,
4420      integral promotions (_conv.prom_) and integral conversions
4421      (_conv.integral_) are applied.  */
4422   if (INTEGRAL_TYPE_P (type))
4423     {
4424       if (!INTEGRAL_TYPE_P (expr_type))
4425         return error_mark_node;
4426
4427       expr = fold_decl_constant_value (expr);
4428       /* Notice that there are constant expressions like '4 % 0' which
4429          do not fold into integer constants.  */
4430       if (TREE_CODE (expr) != INTEGER_CST)
4431         {
4432           error ("%qE is not a valid template argument for type %qT "
4433                  "because it is a non-constant expression", expr, type);
4434           return NULL_TREE;
4435         }
4436
4437       /* At this point, an implicit conversion does what we want,
4438          because we already know that the expression is of integral
4439          type.  */
4440       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4441       if (expr == error_mark_node)
4442         return error_mark_node;
4443
4444       /* Conversion was allowed: fold it to a bare integer constant.  */
4445       expr = fold (expr);
4446     }
4447   /* [temp.arg.nontype]/5, bullet 2
4448
4449      For a non-type template-parameter of type pointer to object,
4450      qualification conversions (_conv.qual_) and the array-to-pointer
4451      conversion (_conv.array_) are applied.  */
4452   else if (TYPE_PTROBV_P (type))
4453     {
4454       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4455
4456          A template-argument for a non-type, non-template template-parameter
4457          shall be one of: [...]
4458
4459          -- the name of a non-type template-parameter;
4460          -- the address of an object or function with external linkage, [...]
4461             expressed as "& id-expression" where the & is optional if the name
4462             refers to a function or array, or if the corresponding
4463             template-parameter is a reference.
4464
4465         Here, we do not care about functions, as they are invalid anyway
4466         for a parameter of type pointer-to-object.  */
4467
4468       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4469         /* Non-type template parameters are OK.  */
4470         ;
4471       else if (TREE_CODE (expr) != ADDR_EXPR
4472                && TREE_CODE (expr_type) != ARRAY_TYPE)
4473         {
4474           if (TREE_CODE (expr) == VAR_DECL)
4475             {
4476               error ("%qD is not a valid template argument "
4477                      "because %qD is a variable, not the address of "
4478                      "a variable",
4479                      expr, expr);
4480               return NULL_TREE;
4481             }
4482           /* Other values, like integer constants, might be valid
4483              non-type arguments of some other type.  */
4484           return error_mark_node;
4485         }
4486       else
4487         {
4488           tree decl;
4489
4490           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4491                   ? TREE_OPERAND (expr, 0) : expr);
4492           if (TREE_CODE (decl) != VAR_DECL)
4493             {
4494               error ("%qE is not a valid template argument of type %qT "
4495                      "because %qE is not a variable",
4496                      expr, type, decl);
4497               return NULL_TREE;
4498             }
4499           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4500             {
4501               error ("%qE is not a valid template argument of type %qT "
4502                      "because %qD does not have external linkage",
4503                      expr, type, decl);
4504               return NULL_TREE;
4505             }
4506         }
4507
4508       expr = decay_conversion (expr);
4509       if (expr == error_mark_node)
4510         return error_mark_node;
4511
4512       expr = perform_qualification_conversions (type, expr);
4513       if (expr == error_mark_node)
4514         return error_mark_node;
4515     }
4516   /* [temp.arg.nontype]/5, bullet 3
4517
4518      For a non-type template-parameter of type reference to object, no
4519      conversions apply. The type referred to by the reference may be more
4520      cv-qualified than the (otherwise identical) type of the
4521      template-argument. The template-parameter is bound directly to the
4522      template-argument, which must be an lvalue.  */
4523   else if (TYPE_REF_OBJ_P (type))
4524     {
4525       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4526                                                       expr_type))
4527         return error_mark_node;
4528
4529       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4530         {
4531           error ("%qE is not a valid template argument for type %qT "
4532                  "because of conflicts in cv-qualification", expr, type);
4533           return NULL_TREE;
4534         }
4535
4536       if (!real_lvalue_p (expr))
4537         {
4538           error ("%qE is not a valid template argument for type %qT "
4539                  "because it is not an lvalue", expr, type);
4540           return NULL_TREE;
4541         }
4542
4543       /* [temp.arg.nontype]/1
4544
4545          A template-argument for a non-type, non-template template-parameter
4546          shall be one of: [...]
4547
4548          -- the address of an object or function with external linkage.  */
4549       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4550         {
4551           error ("%qE is not a valid template argument for type %qT "
4552                  "because object %qD has not external linkage",
4553                  expr, type, expr);
4554           return NULL_TREE;
4555         }
4556
4557       expr = build_nop (type, build_address (expr));
4558     }
4559   /* [temp.arg.nontype]/5, bullet 4
4560
4561      For a non-type template-parameter of type pointer to function, only
4562      the function-to-pointer conversion (_conv.func_) is applied. If the
4563      template-argument represents a set of overloaded functions (or a
4564      pointer to such), the matching function is selected from the set
4565      (_over.over_).  */
4566   else if (TYPE_PTRFN_P (type))
4567     {
4568       /* If the argument is a template-id, we might not have enough
4569          context information to decay the pointer.  */
4570       if (!type_unknown_p (expr_type))
4571         {
4572           expr = decay_conversion (expr);
4573           if (expr == error_mark_node)
4574             return error_mark_node;
4575         }
4576
4577       expr = convert_nontype_argument_function (type, expr);
4578       if (!expr || expr == error_mark_node)
4579         return expr;
4580     }
4581   /* [temp.arg.nontype]/5, bullet 5
4582
4583      For a non-type template-parameter of type reference to function, no
4584      conversions apply. If the template-argument represents a set of
4585      overloaded functions, the matching function is selected from the set
4586      (_over.over_).  */
4587   else if (TYPE_REFFN_P (type))
4588     {
4589       if (TREE_CODE (expr) == ADDR_EXPR)
4590         {
4591           error ("%qE is not a valid template argument for type %qT "
4592                  "because it is a pointer", expr, type);
4593           inform ("try using %qE instead", TREE_OPERAND (expr, 0));
4594           return NULL_TREE;
4595         }
4596
4597       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4598       if (!expr || expr == error_mark_node)
4599         return expr;
4600
4601       expr = build_nop (type, build_address (expr));
4602     }
4603   /* [temp.arg.nontype]/5, bullet 6
4604
4605      For a non-type template-parameter of type pointer to member function,
4606      no conversions apply. If the template-argument represents a set of
4607      overloaded member functions, the matching member function is selected
4608      from the set (_over.over_).  */
4609   else if (TYPE_PTRMEMFUNC_P (type))
4610     {
4611       expr = instantiate_type (type, expr, tf_none);
4612       if (expr == error_mark_node)
4613         return error_mark_node;
4614
4615       /* There is no way to disable standard conversions in
4616          resolve_address_of_overloaded_function (called by
4617          instantiate_type). It is possible that the call succeeded by
4618          converting &B::I to &D::I (where B is a base of D), so we need
4619          to reject this conversion here.
4620
4621          Actually, even if there was a way to disable standard conversions,
4622          it would still be better to reject them here so that we can
4623          provide a superior diagnostic.  */
4624       if (!same_type_p (TREE_TYPE (expr), type))
4625         {
4626           /* Make sure we are just one standard conversion off.  */
4627           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4628           error ("%qE is not a valid template argument for type %qT "
4629                  "because it is of type %qT", expr, type,
4630                  TREE_TYPE (expr));
4631           inform ("standard conversions are not allowed in this context");
4632           return NULL_TREE;
4633         }
4634     }
4635   /* [temp.arg.nontype]/5, bullet 7
4636
4637      For a non-type template-parameter of type pointer to data member,
4638      qualification conversions (_conv.qual_) are applied.  */
4639   else if (TYPE_PTRMEM_P (type))
4640     {
4641       expr = perform_qualification_conversions (type, expr);
4642       if (expr == error_mark_node)
4643         return expr;
4644     }
4645   /* A template non-type parameter must be one of the above.  */
4646   else
4647     gcc_unreachable ();
4648
4649   /* Sanity check: did we actually convert the argument to the
4650      right type?  */
4651   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4652   return expr;
4653 }
4654
4655
4656 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4657    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4658    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4659    or PARM_DECL.
4660
4661    Consider the example:
4662      template <class T> class A;
4663      template<template <class U> class TT> class B;
4664
4665    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4666    the parameters to A, and OUTER_ARGS contains A.  */
4667
4668 static int
4669 coerce_template_template_parms (tree parm_parms,
4670                                 tree arg_parms,
4671                                 tsubst_flags_t complain,
4672                                 tree in_decl,
4673                                 tree outer_args)
4674 {
4675   int nparms, nargs, i;
4676   tree parm, arg;
4677
4678   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4679   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4680
4681   nparms = TREE_VEC_LENGTH (parm_parms);
4682   nargs = TREE_VEC_LENGTH (arg_parms);
4683
4684   if (nargs != nparms)
4685     return 0;
4686
4687   for (i = 0; i < nparms; ++i)
4688     {
4689       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4690           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4691         continue;
4692
4693       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4694       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4695
4696       if (arg == NULL_TREE || arg == error_mark_node
4697           || parm == NULL_TREE || parm == error_mark_node)
4698         return 0;
4699
4700       if (TREE_CODE (arg) != TREE_CODE (parm))
4701         return 0;
4702
4703       switch (TREE_CODE (parm))
4704         {
4705         case TEMPLATE_DECL:
4706           /* We encounter instantiations of templates like
4707                template <template <template <class> class> class TT>
4708                class C;  */
4709           {
4710             tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4711             tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4712
4713             if (!coerce_template_template_parms
4714                 (parmparm, argparm, complain, in_decl, outer_args))
4715               return 0;
4716           }
4717           /* Fall through.  */
4718
4719         case TYPE_DECL:
4720           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))
4721               != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg)))
4722             /* One is a parameter pack, the other is not.  */
4723             return 0;
4724           break;
4725
4726         case PARM_DECL:
4727           /* The tsubst call is used to handle cases such as
4728
4729                template <int> class C {};
4730                template <class T, template <T> class TT> class D {};
4731                D<int, C> d;
4732
4733              i.e. the parameter list of TT depends on earlier parameters.  */
4734           if (!dependent_type_p (TREE_TYPE (arg))
4735               && !same_type_p
4736                     (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4737                              TREE_TYPE (arg)))
4738             return 0;
4739
4740           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4741               != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg)))
4742             /* One is a parameter pack, the other is not.  */
4743             return 0;
4744           break;
4745
4746         default:
4747           gcc_unreachable ();
4748         }
4749     }
4750   return 1;
4751 }
4752
4753 /* Convert the indicated template ARG as necessary to match the
4754    indicated template PARM.  Returns the converted ARG, or
4755    error_mark_node if the conversion was unsuccessful.  Error and
4756    warning messages are issued under control of COMPLAIN.  This
4757    conversion is for the Ith parameter in the parameter list.  ARGS is
4758    the full set of template arguments deduced so far.  */
4759
4760 static tree
4761 convert_template_argument (tree parm,
4762                            tree arg,
4763                            tree args,
4764                            tsubst_flags_t complain,
4765                            int i,
4766                            tree in_decl)
4767 {
4768   tree orig_arg;
4769   tree val;
4770   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4771
4772   if (TREE_CODE (arg) == TREE_LIST
4773       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4774     {
4775       /* The template argument was the name of some
4776          member function.  That's usually
4777          invalid, but static members are OK.  In any
4778          case, grab the underlying fields/functions
4779          and issue an error later if required.  */
4780       orig_arg = TREE_VALUE (arg);
4781       TREE_TYPE (arg) = unknown_type_node;
4782     }
4783
4784   orig_arg = arg;
4785
4786   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4787   requires_type = (TREE_CODE (parm) == TYPE_DECL
4788                    || requires_tmpl_type);
4789
4790   /* When determining whether an argument pack expansion is a template,
4791      look at the pattern.  */
4792   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
4793     arg = PACK_EXPANSION_PATTERN (arg);
4794
4795   is_tmpl_type = 
4796     ((TREE_CODE (arg) == TEMPLATE_DECL
4797       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
4798      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4799      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
4800
4801   if (is_tmpl_type
4802       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4803           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4804     arg = TYPE_STUB_DECL (arg);
4805
4806   is_type = TYPE_P (arg) || is_tmpl_type;
4807
4808   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4809       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4810     {
4811       pedwarn ("to refer to a type member of a template parameter, "
4812                "use %<typename %E%>", orig_arg);
4813
4814       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
4815                                      TREE_OPERAND (arg, 1),
4816                                      typename_type,
4817                                      complain & tf_error);
4818       arg = orig_arg;
4819       is_type = 1;
4820     }
4821   if (is_type != requires_type)
4822     {
4823       if (in_decl)
4824         {
4825           if (complain & tf_error)
4826             {
4827               error ("type/value mismatch at argument %d in template "
4828                      "parameter list for %qD",
4829                      i + 1, in_decl);
4830               if (is_type)
4831                 error ("  expected a constant of type %qT, got %qT",
4832                        TREE_TYPE (parm),
4833                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
4834               else if (requires_tmpl_type)
4835                 error ("  expected a class template, got %qE", orig_arg);
4836               else
4837                 error ("  expected a type, got %qE", orig_arg);
4838             }
4839         }
4840       return error_mark_node;
4841     }
4842   if (is_tmpl_type ^ requires_tmpl_type)
4843     {
4844       if (in_decl && (complain & tf_error))
4845         {
4846           error ("type/value mismatch at argument %d in template "
4847                  "parameter list for %qD",
4848                  i + 1, in_decl);
4849           if (is_tmpl_type)
4850             error ("  expected a type, got %qT", DECL_NAME (arg));
4851           else
4852             error ("  expected a class template, got %qT", orig_arg);
4853         }
4854       return error_mark_node;
4855     }
4856
4857   if (is_type)
4858     {
4859       if (requires_tmpl_type)
4860         {
4861           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
4862             /* The number of argument required is not known yet.
4863                Just accept it for now.  */
4864             val = TREE_TYPE (arg);
4865           else
4866             {
4867               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4868               tree argparm;
4869
4870               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4871
4872               if (coerce_template_template_parms (parmparm, argparm,
4873                                                   complain, in_decl,
4874                                                   args))
4875                 {
4876                   val = orig_arg;
4877
4878                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
4879                      TEMPLATE_DECL.  */
4880                   if (val != error_mark_node)
4881                     {
4882                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
4883                         val = TREE_TYPE (val);
4884                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
4885                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
4886                         {
4887                           val = TREE_TYPE (arg);
4888                           val = make_pack_expansion (val);
4889                         }
4890                     }
4891                 }
4892               else
4893                 {
4894                   if (in_decl && (complain & tf_error))
4895                     {
4896                       error ("type/value mismatch at argument %d in "
4897                              "template parameter list for %qD",
4898                              i + 1, in_decl);
4899                       error ("  expected a template of type %qD, got %qD",
4900                              parm, orig_arg);
4901                     }
4902
4903                   val = error_mark_node;
4904                 }
4905             }
4906         }
4907       else
4908         val = orig_arg;
4909       /* We only form one instance of each template specialization.
4910          Therefore, if we use a non-canonical variant (i.e., a
4911          typedef), any future messages referring to the type will use
4912          the typedef, which is confusing if those future uses do not
4913          themselves also use the typedef.  */
4914       if (TYPE_P (val))
4915         val = canonical_type_variant (val);
4916     }
4917   else
4918     {
4919       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
4920
4921       if (invalid_nontype_parm_type_p (t, complain))
4922         return error_mark_node;
4923
4924       if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
4925         /* We used to call digest_init here.  However, digest_init
4926            will report errors, which we don't want when complain
4927            is zero.  More importantly, digest_init will try too
4928            hard to convert things: for example, `0' should not be
4929            converted to pointer type at this point according to
4930            the standard.  Accepting this is not merely an
4931            extension, since deciding whether or not these
4932            conversions can occur is part of determining which
4933            function template to call, or whether a given explicit
4934            argument specification is valid.  */
4935         val = convert_nontype_argument (t, orig_arg);
4936       else
4937         val = orig_arg;
4938
4939       if (val == NULL_TREE)
4940         val = error_mark_node;
4941       else if (val == error_mark_node && (complain & tf_error))
4942         error ("could not convert template argument %qE to %qT",  orig_arg, t);
4943     }
4944
4945   return val;
4946 }
4947
4948 /* Coerces the remaining template arguments in INNER_ARGS (from
4949    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
4950    Returns the coerced argument pack. PARM_IDX is the position of this
4951    parameter in the template parameter list. ARGS is the original
4952    template argument list.  */
4953 static tree
4954 coerce_template_parameter_pack (tree parms,
4955                                 int parm_idx,
4956                                 tree args,
4957                                 tree inner_args,
4958                                 int arg_idx,
4959                                 tree new_args,
4960                                 int* lost,
4961                                 tree in_decl,
4962                                 tsubst_flags_t complain)
4963 {
4964   tree parm = TREE_VEC_ELT (parms, parm_idx);
4965   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
4966   tree packed_args;
4967   tree argument_pack;
4968   tree packed_types = NULL_TREE;
4969
4970   if (arg_idx > nargs)
4971     arg_idx = nargs;
4972
4973   packed_args = make_tree_vec (nargs - arg_idx);
4974
4975   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
4976       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
4977     {
4978       /* When the template parameter is a non-type template
4979          parameter pack whose type uses parameter packs, we need
4980          to look at each of the template arguments
4981          separately. Build a vector of the types for these
4982          non-type template parameters in PACKED_TYPES.  */
4983       tree expansion 
4984         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
4985       packed_types = tsubst_pack_expansion (expansion, args,
4986                                             complain, in_decl);
4987
4988       if (packed_types == error_mark_node)
4989         return error_mark_node;
4990
4991       /* Check that we have the right number of arguments.  */
4992       if (arg_idx < nargs
4993           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
4994           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
4995         {
4996           int needed_parms 
4997             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
4998           error ("wrong number of template arguments (%d, should be %d)",
4999                  nargs, needed_parms);
5000           return error_mark_node;
5001         }
5002
5003       /* If we aren't able to check the actual arguments now
5004          (because they haven't been expanded yet), we can at least
5005          verify that all of the types used for the non-type
5006          template parameter pack are, in fact, valid for non-type
5007          template parameters.  */
5008       if (arg_idx < nargs 
5009           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5010         {
5011           int j, len = TREE_VEC_LENGTH (packed_types);
5012           for (j = 0; j < len; ++j)
5013             {
5014               tree t = TREE_VEC_ELT (packed_types, j);
5015               if (invalid_nontype_parm_type_p (t, complain))
5016                 return error_mark_node;
5017             }
5018         }
5019     }
5020
5021   /* Convert the remaining arguments, which will be a part of the
5022      parameter pack "parm".  */
5023   for (; arg_idx < nargs; ++arg_idx)
5024     {
5025       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5026       tree actual_parm = TREE_VALUE (parm);
5027
5028       if (packed_types && !PACK_EXPANSION_P (arg))
5029         {
5030           /* When we have a vector of types (corresponding to the
5031              non-type template parameter pack that uses parameter
5032              packs in its type, as mention above), and the
5033              argument is not an expansion (which expands to a
5034              currently unknown number of arguments), clone the
5035              parm and give it the next type in PACKED_TYPES.  */
5036           actual_parm = copy_node (actual_parm);
5037           TREE_TYPE (actual_parm) = 
5038             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5039         }
5040
5041       if (arg != error_mark_node)
5042         arg = convert_template_argument (actual_parm, 
5043                                          arg, new_args, complain, parm_idx,
5044                                          in_decl);
5045       if (arg == error_mark_node)
5046         (*lost)++;
5047       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5048     }
5049
5050   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5051       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5052     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5053   else
5054     {
5055       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5056       TREE_TYPE (argument_pack) 
5057         = tsubst (TREE_TYPE (TREE_VALUE (parm)), args, complain, in_decl);
5058       TREE_CONSTANT (argument_pack) = 1;
5059     }
5060
5061   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5062   return argument_pack;
5063 }
5064
5065 /* Convert all template arguments to their appropriate types, and
5066    return a vector containing the innermost resulting template
5067    arguments.  If any error occurs, return error_mark_node. Error and
5068    warning messages are issued under control of COMPLAIN.
5069
5070    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5071    for arguments not specified in ARGS.  Otherwise, if
5072    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5073    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5074    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5075    ARGS.  */
5076
5077 static tree
5078 coerce_template_parms (tree parms,
5079                        tree args,
5080                        tree in_decl,
5081                        tsubst_flags_t complain,
5082                        bool require_all_args,
5083                        bool use_default_args)
5084 {
5085   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5086   tree inner_args;
5087   tree new_args;
5088   tree new_inner_args;
5089   bool saved_skip_evaluation;
5090
5091   /* When used as a boolean value, indicates whether this is a
5092      variadic template parameter list. Since it's an int, we can also
5093      subtract it from nparms to get the number of non-variadic
5094      parameters.  */
5095   int variadic_p = 0;
5096
5097   inner_args 
5098     = expand_template_argument_pack (INNERMOST_TEMPLATE_ARGS (args));
5099
5100   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5101   nparms = TREE_VEC_LENGTH (parms);
5102
5103   /* Determine if there are any parameter packs.  */
5104   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5105     {
5106       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5107       if (template_parameter_pack_p (tparm))
5108         {
5109           variadic_p = 1;
5110           break;
5111         }
5112     }
5113
5114   if ((nargs > nparms - variadic_p && !variadic_p)
5115       || (nargs < nparms - variadic_p
5116           && require_all_args
5117           && (!use_default_args
5118               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5119                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5120     {
5121       if (complain & tf_error)
5122         {
5123           const char *or_more = "";
5124           if (variadic_p)
5125             {
5126               or_more = " or more";
5127               --nparms;
5128             }
5129
5130           error ("wrong number of template arguments (%d, should be %d%s)",
5131                  nargs, nparms, or_more);
5132
5133           if (in_decl)
5134             error ("provided for %q+D", in_decl);
5135         }
5136
5137       return error_mark_node;
5138     }
5139
5140   /* We need to evaluate the template arguments, even though this
5141      template-id may be nested within a "sizeof".  */
5142   saved_skip_evaluation = skip_evaluation;
5143   skip_evaluation = false;
5144   new_inner_args = make_tree_vec (nparms);
5145   new_args = add_outermost_template_args (args, new_inner_args);
5146   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5147     {
5148       tree arg;
5149       tree parm;
5150
5151       /* Get the Ith template parameter.  */
5152       parm = TREE_VEC_ELT (parms, parm_idx);
5153  
5154       if (parm == error_mark_node)
5155       {
5156         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5157         continue;
5158       }
5159
5160       /* Calculate the next argument.  */
5161       if (template_parameter_pack_p (TREE_VALUE (parm)))
5162         {
5163           /* All remaining arguments will be placed in the
5164              template parameter pack PARM.  */
5165           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5166                                                 inner_args, arg_idx,
5167                                                 new_args, &lost,
5168                                                 in_decl, complain);
5169           
5170           /* Store this argument.  */
5171           if (arg == error_mark_node)
5172             lost++;
5173           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5174
5175           /* We are done with all of the arguments.  */
5176           arg_idx = nargs;
5177
5178           continue;
5179         }
5180       else if (arg_idx < nargs)
5181         {
5182           arg = TREE_VEC_ELT (inner_args, arg_idx);
5183
5184           if (arg && PACK_EXPANSION_P (arg))
5185             {
5186               /* If ARG is a pack expansion, but PARM is not a
5187                  template parameter pack (if it were, we would have
5188                  handled it above), we're trying to expand into a
5189                  fixed-length argument list.  */
5190               if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5191                 error ("cannot expand %<%E%> into a fixed-length "
5192                        "argument list", arg);
5193               else
5194                 error ("cannot expand %<%T%> into a fixed-length "
5195                        "argument list", arg);
5196               return error_mark_node;
5197             }
5198         }
5199       else if (require_all_args)
5200         /* There must be a default arg in this case.  */
5201         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5202                                    complain, in_decl);
5203       else
5204         break;
5205
5206       if (arg == error_mark_node)
5207         {
5208           if (complain & tf_error)
5209             error ("template argument %d is invalid", arg_idx + 1);
5210         }
5211       else if (!arg)
5212         /* This only occurs if there was an error in the template
5213            parameter list itself (which we would already have
5214            reported) that we are trying to recover from, e.g., a class
5215            template with a parameter list such as
5216            template<typename..., typename>.  */
5217         return error_mark_node;
5218       else
5219         arg = convert_template_argument (TREE_VALUE (parm),
5220                                          arg, new_args, complain, 
5221                                          parm_idx, in_decl);
5222
5223       if (arg == error_mark_node)
5224         lost++;
5225       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5226     }
5227   skip_evaluation = saved_skip_evaluation;
5228
5229   if (lost)
5230     return error_mark_node;
5231
5232   return new_inner_args;
5233 }
5234
5235 /* Returns 1 if template args OT and NT are equivalent.  */
5236
5237 static int
5238 template_args_equal (tree ot, tree nt)
5239 {
5240   if (nt == ot)
5241     return 1;
5242
5243   if (TREE_CODE (nt) == TREE_VEC)
5244     /* For member templates */
5245     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5246   else if (PACK_EXPANSION_P (ot))
5247     return PACK_EXPANSION_P (nt) 
5248       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5249                               PACK_EXPANSION_PATTERN (nt));
5250   else if (TYPE_P (nt))
5251     return TYPE_P (ot) && same_type_p (ot, nt);
5252   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5253     return 0;
5254   else
5255     return cp_tree_equal (ot, nt);
5256 }
5257
5258 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5259    of template arguments.  Returns 0 otherwise.  */
5260
5261 int
5262 comp_template_args (tree oldargs, tree newargs)
5263 {
5264   int i;
5265
5266   oldargs = expand_template_argument_pack (oldargs);
5267   newargs = expand_template_argument_pack (newargs);
5268
5269   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5270     return 0;
5271
5272   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5273     {
5274       tree nt = TREE_VEC_ELT (newargs, i);
5275       tree ot = TREE_VEC_ELT (oldargs, i);
5276
5277       if (! template_args_equal (ot, nt))
5278         return 0;
5279     }
5280   return 1;
5281 }
5282
5283 static void
5284 add_pending_template (tree d)
5285 {
5286   tree ti = (TYPE_P (d)
5287              ? CLASSTYPE_TEMPLATE_INFO (d)
5288              : DECL_TEMPLATE_INFO (d));
5289   struct pending_template *pt;
5290   int level;
5291
5292   if (TI_PENDING_TEMPLATE_FLAG (ti))
5293     return;
5294
5295   /* We are called both from instantiate_decl, where we've already had a
5296      tinst_level pushed, and instantiate_template, where we haven't.
5297      Compensate.  */
5298   level = !current_tinst_level || current_tinst_level->decl != d;
5299
5300   if (level)
5301     push_tinst_level (d);
5302
5303   pt = GGC_NEW (struct pending_template);
5304   pt->next = NULL;
5305   pt->tinst = current_tinst_level;
5306   if (last_pending_template)
5307     last_pending_template->next = pt;
5308   else
5309     pending_templates = pt;
5310
5311   last_pending_template = pt;
5312
5313   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5314
5315   if (level)
5316     pop_tinst_level ();
5317 }
5318
5319
5320 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5321    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5322    documentation for TEMPLATE_ID_EXPR.  */
5323
5324 tree
5325 lookup_template_function (tree fns, tree arglist)
5326 {
5327   tree type;
5328
5329   if (fns == error_mark_node || arglist == error_mark_node)
5330     return error_mark_node;
5331
5332   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5333   gcc_assert (fns && (is_overloaded_fn (fns)
5334                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5335
5336   if (BASELINK_P (fns))
5337     {
5338       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5339                                          unknown_type_node,
5340                                          BASELINK_FUNCTIONS (fns),
5341                                          arglist);
5342       return fns;
5343     }
5344
5345   type = TREE_TYPE (fns);
5346   if (TREE_CODE (fns) == OVERLOAD || !type)
5347     type = unknown_type_node;
5348
5349   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5350 }
5351
5352 /* Within the scope of a template class S<T>, the name S gets bound
5353    (in build_self_reference) to a TYPE_DECL for the class, not a
5354    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5355    or one of its enclosing classes, and that type is a template,
5356    return the associated TEMPLATE_DECL.  Otherwise, the original
5357    DECL is returned.  */
5358
5359 tree
5360 maybe_get_template_decl_from_type_decl (tree decl)
5361 {
5362   return (decl != NULL_TREE
5363           && TREE_CODE (decl) == TYPE_DECL
5364           && DECL_ARTIFICIAL (decl)
5365           && CLASS_TYPE_P (TREE_TYPE (decl))
5366           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5367     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5368 }
5369
5370 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5371    parameters, find the desired type.
5372
5373    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5374
5375    IN_DECL, if non-NULL, is the template declaration we are trying to
5376    instantiate.
5377
5378    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5379    the class we are looking up.
5380
5381    Issue error and warning messages under control of COMPLAIN.
5382
5383    If the template class is really a local class in a template
5384    function, then the FUNCTION_CONTEXT is the function in which it is
5385    being instantiated.
5386
5387    ??? Note that this function is currently called *twice* for each
5388    template-id: the first time from the parser, while creating the
5389    incomplete type (finish_template_type), and the second type during the
5390    real instantiation (instantiate_template_class). This is surely something
5391    that we want to avoid. It also causes some problems with argument
5392    coercion (see convert_nontype_argument for more information on this).  */
5393
5394 tree
5395 lookup_template_class (tree d1,
5396                        tree arglist,
5397                        tree in_decl,
5398                        tree context,
5399                        int entering_scope,
5400                        tsubst_flags_t complain)
5401 {
5402   tree template = NULL_TREE, parmlist;
5403   tree t;
5404
5405   timevar_push (TV_NAME_LOOKUP);
5406
5407   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5408     {
5409       tree value = innermost_non_namespace_value (d1);
5410       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5411         template = value;
5412       else
5413         {
5414           if (context)
5415             push_decl_namespace (context);
5416           template = lookup_name (d1);
5417           template = maybe_get_template_decl_from_type_decl (template);
5418           if (context)
5419             pop_decl_namespace ();
5420         }
5421       if (template)
5422         context = DECL_CONTEXT (template);
5423     }
5424   else if (TREE_CODE (d1) == TYPE_DECL && IS_AGGR_TYPE (TREE_TYPE (d1)))
5425     {
5426       tree type = TREE_TYPE (d1);
5427
5428       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5429          an implicit typename for the second A.  Deal with it.  */
5430       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5431         type = TREE_TYPE (type);
5432
5433       if (CLASSTYPE_TEMPLATE_INFO (type))
5434         {
5435           template = CLASSTYPE_TI_TEMPLATE (type);
5436           d1 = DECL_NAME (template);
5437         }
5438     }
5439   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5440            || (TYPE_P (d1) && IS_AGGR_TYPE (d1)))
5441     {
5442       template = TYPE_TI_TEMPLATE (d1);
5443       d1 = DECL_NAME (template);
5444     }
5445   else if (TREE_CODE (d1) == TEMPLATE_DECL
5446            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5447     {
5448       template = d1;
5449       d1 = DECL_NAME (template);
5450       context = DECL_CONTEXT (template);
5451     }
5452
5453   /* Issue an error message if we didn't find a template.  */
5454   if (! template)
5455     {
5456       if (complain & tf_error)
5457         error ("%qT is not a template", d1);
5458       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5459     }
5460
5461   if (TREE_CODE (template) != TEMPLATE_DECL
5462          /* Make sure it's a user visible template, if it was named by
5463             the user.  */
5464       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (template)
5465           && !PRIMARY_TEMPLATE_P (template)))
5466     {
5467       if (complain & tf_error)
5468         {
5469           error ("non-template type %qT used as a template", d1);
5470           if (in_decl)
5471             error ("for template declaration %q+D", in_decl);
5472         }
5473       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5474     }
5475
5476   complain &= ~tf_user;
5477
5478   if (DECL_TEMPLATE_TEMPLATE_PARM_P (template))
5479     {
5480       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5481          template arguments */
5482
5483       tree parm;
5484       tree arglist2;
5485       tree outer;
5486
5487       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (template);
5488
5489       /* Consider an example where a template template parameter declared as
5490
5491            template <class T, class U = std::allocator<T> > class TT
5492
5493          The template parameter level of T and U are one level larger than
5494          of TT.  To proper process the default argument of U, say when an
5495          instantiation `TT<int>' is seen, we need to build the full
5496          arguments containing {int} as the innermost level.  Outer levels,
5497          available when not appearing as default template argument, can be
5498          obtained from the arguments of the enclosing template.
5499
5500          Suppose that TT is later substituted with std::vector.  The above
5501          instantiation is `TT<int, std::allocator<T> >' with TT at
5502          level 1, and T at level 2, while the template arguments at level 1
5503          becomes {std::vector} and the inner level 2 is {int}.  */
5504
5505       outer = DECL_CONTEXT (template);
5506       if (outer)
5507         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5508       else if (current_template_parms)
5509         /* This is an argument of the current template, so we haven't set
5510            DECL_CONTEXT yet.  */
5511         outer = current_template_args ();
5512
5513       if (outer)
5514         arglist = add_to_template_args (outer, arglist);
5515
5516       arglist2 = coerce_template_parms (parmlist, arglist, template,
5517                                         complain,
5518                                         /*require_all_args=*/true,
5519                                         /*use_default_args=*/true);
5520       if (arglist2 == error_mark_node
5521           || (!uses_template_parms (arglist2)
5522               && check_instantiated_args (template, arglist2, complain)))
5523         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5524
5525       parm = bind_template_template_parm (TREE_TYPE (template), arglist2);
5526       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5527     }
5528   else
5529     {
5530       tree template_type = TREE_TYPE (template);
5531       tree gen_tmpl;
5532       tree type_decl;
5533       tree found = NULL_TREE;
5534       int arg_depth;
5535       int parm_depth;
5536       int is_partial_instantiation;
5537
5538       gen_tmpl = most_general_template (template);
5539       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5540       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5541       arg_depth = TMPL_ARGS_DEPTH (arglist);
5542
5543       if (arg_depth == 1 && parm_depth > 1)
5544         {
5545           /* We've been given an incomplete set of template arguments.
5546              For example, given:
5547
5548                template <class T> struct S1 {
5549                  template <class U> struct S2 {};
5550                  template <class U> struct S2<U*> {};
5551                 };
5552
5553              we will be called with an ARGLIST of `U*', but the
5554              TEMPLATE will be `template <class T> template
5555              <class U> struct S1<T>::S2'.  We must fill in the missing
5556              arguments.  */
5557           arglist
5558             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (template)),
5559                                            arglist);
5560           arg_depth = TMPL_ARGS_DEPTH (arglist);
5561         }
5562
5563       /* Now we should have enough arguments.  */
5564       gcc_assert (parm_depth == arg_depth);
5565
5566       /* From here on, we're only interested in the most general
5567          template.  */
5568       template = gen_tmpl;
5569
5570       /* Calculate the BOUND_ARGS.  These will be the args that are
5571          actually tsubst'd into the definition to create the
5572          instantiation.  */
5573       if (parm_depth > 1)
5574         {
5575           /* We have multiple levels of arguments to coerce, at once.  */
5576           int i;
5577           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5578
5579           tree bound_args = make_tree_vec (parm_depth);
5580
5581           for (i = saved_depth,
5582                  t = DECL_TEMPLATE_PARMS (template);
5583                i > 0 && t != NULL_TREE;
5584                --i, t = TREE_CHAIN (t))
5585             {
5586               tree a = coerce_template_parms (TREE_VALUE (t),
5587                                               arglist, template,
5588                                               complain,
5589                                               /*require_all_args=*/true,
5590                                               /*use_default_args=*/true);
5591
5592               /* Don't process further if one of the levels fails.  */
5593               if (a == error_mark_node)
5594                 {
5595                   /* Restore the ARGLIST to its full size.  */
5596                   TREE_VEC_LENGTH (arglist) = saved_depth;
5597                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5598                 }
5599
5600               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5601
5602               /* We temporarily reduce the length of the ARGLIST so
5603                  that coerce_template_parms will see only the arguments
5604                  corresponding to the template parameters it is
5605                  examining.  */
5606               TREE_VEC_LENGTH (arglist)--;
5607             }
5608
5609           /* Restore the ARGLIST to its full size.  */
5610           TREE_VEC_LENGTH (arglist) = saved_depth;
5611
5612           arglist = bound_args;
5613         }
5614       else
5615         arglist
5616           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5617                                    INNERMOST_TEMPLATE_ARGS (arglist),
5618                                    template,
5619                                    complain,
5620                                    /*require_all_args=*/true,
5621                                    /*use_default_args=*/true);
5622
5623       if (arglist == error_mark_node)
5624         /* We were unable to bind the arguments.  */
5625         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5626
5627       /* In the scope of a template class, explicit references to the
5628          template class refer to the type of the template, not any
5629          instantiation of it.  For example, in:
5630
5631            template <class T> class C { void f(C<T>); }
5632
5633          the `C<T>' is just the same as `C'.  Outside of the
5634          class, however, such a reference is an instantiation.  */
5635       if (comp_template_args (TYPE_TI_ARGS (template_type),
5636                               arglist))
5637         {
5638           found = template_type;
5639
5640           if (!entering_scope && PRIMARY_TEMPLATE_P (template))
5641             {
5642               tree ctx;
5643
5644               for (ctx = current_class_type;
5645                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5646                    ctx = (TYPE_P (ctx)
5647                           ? TYPE_CONTEXT (ctx)
5648                           : DECL_CONTEXT (ctx)))
5649                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5650                   goto found_ctx;
5651
5652               /* We're not in the scope of the class, so the
5653                  TEMPLATE_TYPE is not the type we want after all.  */
5654               found = NULL_TREE;
5655             found_ctx:;
5656             }
5657         }
5658       if (found)
5659         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5660
5661       /* If we already have this specialization, return it.  */
5662       found = retrieve_specialization (template, arglist,
5663                                        /*class_specializations_p=*/false);
5664       if (found)
5665         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5666
5667       /* This type is a "partial instantiation" if any of the template
5668          arguments still involve template parameters.  Note that we set
5669          IS_PARTIAL_INSTANTIATION for partial specializations as
5670          well.  */
5671       is_partial_instantiation = uses_template_parms (arglist);
5672
5673       /* If the deduced arguments are invalid, then the binding
5674          failed.  */
5675       if (!is_partial_instantiation
5676           && check_instantiated_args (template,
5677                                       INNERMOST_TEMPLATE_ARGS (arglist),
5678                                       complain))
5679         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5680
5681       if (!is_partial_instantiation
5682           && !PRIMARY_TEMPLATE_P (template)
5683           && TREE_CODE (CP_DECL_CONTEXT (template)) == NAMESPACE_DECL)
5684         {
5685           found = xref_tag_from_type (TREE_TYPE (template),
5686                                       DECL_NAME (template),
5687                                       /*tag_scope=*/ts_global);
5688           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5689         }
5690
5691       context = tsubst (DECL_CONTEXT (template), arglist,
5692                         complain, in_decl);
5693       if (!context)
5694         context = global_namespace;
5695
5696       /* Create the type.  */
5697       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5698         {
5699           if (!is_partial_instantiation)
5700             {
5701               set_current_access_from_decl (TYPE_NAME (template_type));
5702               t = start_enum (TYPE_IDENTIFIER (template_type));
5703             }
5704           else
5705             /* We don't want to call start_enum for this type, since
5706                the values for the enumeration constants may involve
5707                template parameters.  And, no one should be interested
5708                in the enumeration constants for such a type.  */
5709             t = make_node (ENUMERAL_TYPE);
5710         }
5711       else
5712         {
5713           t = make_aggr_type (TREE_CODE (template_type));
5714           CLASSTYPE_DECLARED_CLASS (t)
5715             = CLASSTYPE_DECLARED_CLASS (template_type);
5716           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5717           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5718
5719           /* A local class.  Make sure the decl gets registered properly.  */
5720           if (context == current_function_decl)
5721             pushtag (DECL_NAME (template), t, /*tag_scope=*/ts_current);
5722
5723           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5724             /* This instantiation is another name for the primary
5725                template type. Set the TYPE_CANONICAL field
5726                appropriately. */
5727             TYPE_CANONICAL (t) = template_type;
5728           else if (any_template_arguments_need_structural_equality_p (arglist))
5729             /* Some of the template arguments require structural
5730                equality testing, so this template class requires
5731                structural equality testing. */
5732             SET_TYPE_STRUCTURAL_EQUALITY (t);
5733         }
5734
5735       /* If we called start_enum or pushtag above, this information
5736          will already be set up.  */
5737       if (!TYPE_NAME (t))
5738         {
5739           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5740
5741           type_decl = create_implicit_typedef (DECL_NAME (template), t);
5742           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5743           TYPE_STUB_DECL (t) = type_decl;
5744           DECL_SOURCE_LOCATION (type_decl)
5745             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5746         }
5747       else
5748         type_decl = TYPE_NAME (t);
5749
5750       TREE_PRIVATE (type_decl)
5751         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5752       TREE_PROTECTED (type_decl)
5753         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5754       DECL_IN_SYSTEM_HEADER (type_decl)
5755         = DECL_IN_SYSTEM_HEADER (template);
5756       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5757         {
5758           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5759           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5760         }
5761
5762       /* Set up the template information.  We have to figure out which
5763          template is the immediate parent if this is a full
5764          instantiation.  */
5765       if (parm_depth == 1 || is_partial_instantiation
5766           || !PRIMARY_TEMPLATE_P (template))
5767         /* This case is easy; there are no member templates involved.  */
5768         found = template;
5769       else
5770         {
5771           /* This is a full instantiation of a member template.  Look
5772              for a partial instantiation of which this is an instance.  */
5773
5774           for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
5775                found; found = TREE_CHAIN (found))
5776             {
5777               int success;
5778               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5779
5780               /* We only want partial instantiations, here, not
5781                  specializations or full instantiations.  */
5782               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5783                   || !uses_template_parms (TREE_VALUE (found)))
5784                 continue;
5785
5786               /* Temporarily reduce by one the number of levels in the
5787                  ARGLIST and in FOUND so as to avoid comparing the
5788                  last set of arguments.  */
5789               TREE_VEC_LENGTH (arglist)--;
5790               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
5791
5792               /* See if the arguments match.  If they do, then TMPL is
5793                  the partial instantiation we want.  */
5794               success = comp_template_args (TREE_PURPOSE (found), arglist);
5795
5796               /* Restore the argument vectors to their full size.  */
5797               TREE_VEC_LENGTH (arglist)++;
5798               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
5799
5800               if (success)
5801                 {
5802                   found = tmpl;
5803                   break;
5804                 }
5805             }
5806
5807           if (!found)
5808             {
5809               /* There was no partial instantiation. This happens
5810                  where C<T> is a member template of A<T> and it's used
5811                  in something like
5812
5813                   template <typename T> struct B { A<T>::C<int> m; };
5814                   B<float>;
5815
5816                  Create the partial instantiation.
5817                */
5818               TREE_VEC_LENGTH (arglist)--;
5819               found = tsubst (template, arglist, complain, NULL_TREE);
5820               TREE_VEC_LENGTH (arglist)++;
5821             }
5822         }
5823
5824       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
5825       DECL_TEMPLATE_INSTANTIATIONS (template)
5826         = tree_cons (arglist, t,
5827                      DECL_TEMPLATE_INSTANTIATIONS (template));
5828
5829       if (TREE_CODE (t) == ENUMERAL_TYPE
5830           && !is_partial_instantiation)
5831         /* Now that the type has been registered on the instantiations
5832            list, we set up the enumerators.  Because the enumeration
5833            constants may involve the enumeration type itself, we make
5834            sure to register the type first, and then create the
5835            constants.  That way, doing tsubst_expr for the enumeration
5836            constants won't result in recursive calls here; we'll find
5837            the instantiation and exit above.  */
5838         tsubst_enum (template_type, t, arglist);
5839
5840       if (is_partial_instantiation)
5841         /* If the type makes use of template parameters, the
5842            code that generates debugging information will crash.  */
5843         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
5844
5845       /* Possibly limit visibility based on template args.  */
5846       TREE_PUBLIC (type_decl) = 1;
5847       determine_visibility (type_decl);
5848
5849       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
5850     }
5851   timevar_pop (TV_NAME_LOOKUP);
5852 }
5853 \f
5854 struct pair_fn_data
5855 {
5856   tree_fn_t fn;
5857   void *data;
5858   struct pointer_set_t *visited;
5859 };
5860
5861 /* Called from for_each_template_parm via walk_tree.  */
5862
5863 static tree
5864 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
5865 {
5866   tree t = *tp;
5867   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
5868   tree_fn_t fn = pfd->fn;
5869   void *data = pfd->data;
5870
5871   if (TYPE_P (t)
5872       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited))
5873     return error_mark_node;
5874
5875   switch (TREE_CODE (t))
5876     {
5877     case RECORD_TYPE:
5878       if (TYPE_PTRMEMFUNC_P (t))
5879         break;
5880       /* Fall through.  */
5881
5882     case UNION_TYPE:
5883     case ENUMERAL_TYPE:
5884       if (!TYPE_TEMPLATE_INFO (t))
5885         *walk_subtrees = 0;
5886       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
5887                                        fn, data, pfd->visited))
5888         return error_mark_node;
5889       break;
5890
5891     case INTEGER_TYPE:
5892       if (for_each_template_parm (TYPE_MIN_VALUE (t),
5893                                   fn, data, pfd->visited)
5894           || for_each_template_parm (TYPE_MAX_VALUE (t),
5895                                      fn, data, pfd->visited))
5896         return error_mark_node;
5897       break;
5898
5899     case METHOD_TYPE:
5900       /* Since we're not going to walk subtrees, we have to do this
5901          explicitly here.  */
5902       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
5903                                   pfd->visited))
5904         return error_mark_node;
5905       /* Fall through.  */
5906
5907     case FUNCTION_TYPE:
5908       /* Check the return type.  */
5909       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited))
5910         return error_mark_node;
5911
5912       /* Check the parameter types.  Since default arguments are not
5913          instantiated until they are needed, the TYPE_ARG_TYPES may
5914          contain expressions that involve template parameters.  But,
5915          no-one should be looking at them yet.  And, once they're
5916          instantiated, they don't contain template parameters, so
5917          there's no point in looking at them then, either.  */
5918       {
5919         tree parm;
5920
5921         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
5922           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
5923                                       pfd->visited))
5924             return error_mark_node;
5925
5926         /* Since we've already handled the TYPE_ARG_TYPES, we don't
5927            want walk_tree walking into them itself.  */
5928         *walk_subtrees = 0;
5929       }
5930       break;
5931
5932     case TYPEOF_TYPE:
5933       if (for_each_template_parm (TYPE_FIELDS (t), fn, data,
5934                                   pfd->visited))
5935         return error_mark_node;
5936       break;
5937
5938     case FUNCTION_DECL:
5939     case VAR_DECL:
5940       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
5941           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
5942                                      pfd->visited))
5943         return error_mark_node;
5944       /* Fall through.  */
5945
5946     case PARM_DECL:
5947     case CONST_DECL:
5948       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
5949           && for_each_template_parm (DECL_INITIAL (t), fn, data,
5950                                      pfd->visited))
5951         return error_mark_node;
5952       if (DECL_CONTEXT (t)
5953           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
5954                                      pfd->visited))
5955         return error_mark_node;
5956       break;
5957
5958     case BOUND_TEMPLATE_TEMPLATE_PARM:
5959       /* Record template parameters such as `T' inside `TT<T>'.  */
5960       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited))
5961         return error_mark_node;
5962       /* Fall through.  */
5963
5964     case TEMPLATE_TEMPLATE_PARM:
5965     case TEMPLATE_TYPE_PARM:
5966     case TEMPLATE_PARM_INDEX:
5967       if (fn && (*fn)(t, data))
5968         return error_mark_node;
5969       else if (!fn)
5970         return error_mark_node;
5971       break;
5972
5973     case TEMPLATE_DECL:
5974       /* A template template parameter is encountered.  */
5975       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
5976           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited))
5977         return error_mark_node;
5978
5979       /* Already substituted template template parameter */
5980       *walk_subtrees = 0;
5981       break;
5982
5983     case TYPENAME_TYPE:
5984       if (!fn
5985           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
5986                                      data, pfd->visited))
5987         return error_mark_node;
5988       break;
5989
5990     case CONSTRUCTOR:
5991       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
5992           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
5993                                      (TREE_TYPE (t)), fn, data,
5994                                      pfd->visited))
5995         return error_mark_node;
5996       break;
5997
5998     case INDIRECT_REF:
5999     case COMPONENT_REF:
6000       /* If there's no type, then this thing must be some expression
6001          involving template parameters.  */
6002       if (!fn && !TREE_TYPE (t))
6003         return error_mark_node;
6004       break;
6005
6006     case MODOP_EXPR:
6007     case CAST_EXPR:
6008     case REINTERPRET_CAST_EXPR:
6009     case CONST_CAST_EXPR:
6010     case STATIC_CAST_EXPR:
6011     case DYNAMIC_CAST_EXPR:
6012     case ARROW_EXPR:
6013     case DOTSTAR_EXPR:
6014     case TYPEID_EXPR:
6015     case PSEUDO_DTOR_EXPR:
6016       if (!fn)
6017         return error_mark_node;
6018       break;
6019
6020     default:
6021       break;
6022     }
6023
6024   /* We didn't find any template parameters we liked.  */
6025   return NULL_TREE;
6026 }
6027
6028 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6029    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6030    call FN with the parameter and the DATA.
6031    If FN returns nonzero, the iteration is terminated, and
6032    for_each_template_parm returns 1.  Otherwise, the iteration
6033    continues.  If FN never returns a nonzero value, the value
6034    returned by for_each_template_parm is 0.  If FN is NULL, it is
6035    considered to be the function which always returns 1.  */
6036
6037 static int
6038 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6039                         struct pointer_set_t *visited)
6040 {
6041   struct pair_fn_data pfd;
6042   int result;
6043
6044   /* Set up.  */
6045   pfd.fn = fn;
6046   pfd.data = data;
6047
6048   /* Walk the tree.  (Conceptually, we would like to walk without
6049      duplicates, but for_each_template_parm_r recursively calls
6050      for_each_template_parm, so we would need to reorganize a fair
6051      bit to use walk_tree_without_duplicates, so we keep our own
6052      visited list.)  */
6053   if (visited)
6054     pfd.visited = visited;
6055   else
6056     pfd.visited = pointer_set_create ();
6057   result = cp_walk_tree (&t,
6058                          for_each_template_parm_r,
6059                          &pfd,
6060                          pfd.visited) != NULL_TREE;
6061
6062   /* Clean up.  */
6063   if (!visited)
6064     {
6065       pointer_set_destroy (pfd.visited);
6066       pfd.visited = 0;
6067     }
6068
6069   return result;
6070 }
6071
6072 /* Returns true if T depends on any template parameter.  */
6073
6074 int
6075 uses_template_parms (tree t)
6076 {
6077   bool dependent_p;
6078   int saved_processing_template_decl;
6079
6080   saved_processing_template_decl = processing_template_decl;
6081   if (!saved_processing_template_decl)
6082     processing_template_decl = 1;
6083   if (TYPE_P (t))
6084     dependent_p = dependent_type_p (t);
6085   else if (TREE_CODE (t) == TREE_VEC)
6086     dependent_p = any_dependent_template_arguments_p (t);
6087   else if (TREE_CODE (t) == TREE_LIST)
6088     dependent_p = (uses_template_parms (TREE_VALUE (t))
6089                    || uses_template_parms (TREE_CHAIN (t)));
6090   else if (TREE_CODE (t) == TYPE_DECL)
6091     dependent_p = dependent_type_p (TREE_TYPE (t));
6092   else if (DECL_P (t)
6093            || EXPR_P (t)
6094            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6095            || TREE_CODE (t) == OVERLOAD
6096            || TREE_CODE (t) == BASELINK
6097            || TREE_CODE (t) == IDENTIFIER_NODE
6098            || TREE_CODE (t) == TRAIT_EXPR
6099            || CONSTANT_CLASS_P (t))
6100     dependent_p = (type_dependent_expression_p (t)
6101                    || value_dependent_expression_p (t));
6102   else
6103     {
6104       gcc_assert (t == error_mark_node);
6105       dependent_p = false;
6106     }
6107
6108   processing_template_decl = saved_processing_template_decl;
6109
6110   return dependent_p;
6111 }
6112
6113 /* Returns true if T depends on any template parameter with level LEVEL.  */
6114
6115 int
6116 uses_template_parms_level (tree t, int level)
6117 {
6118   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL);
6119 }
6120
6121 static int tinst_depth;
6122 extern int max_tinst_depth;
6123 #ifdef GATHER_STATISTICS
6124 int depth_reached;
6125 #endif
6126 static int tinst_level_tick;
6127 static int last_template_error_tick;
6128
6129 /* We're starting to instantiate D; record the template instantiation context
6130    for diagnostics and to restore it later.  */
6131
6132 static int
6133 push_tinst_level (tree d)
6134 {
6135   struct tinst_level *new;
6136
6137   if (tinst_depth >= max_tinst_depth)
6138     {
6139       /* If the instantiation in question still has unbound template parms,
6140          we don't really care if we can't instantiate it, so just return.
6141          This happens with base instantiation for implicit `typename'.  */
6142       if (uses_template_parms (d))
6143         return 0;
6144
6145       last_template_error_tick = tinst_level_tick;
6146       error ("template instantiation depth exceeds maximum of %d (use "
6147              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6148              max_tinst_depth, d);
6149
6150       print_instantiation_context ();
6151
6152       return 0;
6153     }
6154
6155   new = GGC_NEW (struct tinst_level);
6156   new->decl = d;
6157   new->locus = input_location;
6158   new->in_system_header_p = in_system_header;
6159   new->next = current_tinst_level;
6160   current_tinst_level = new;
6161
6162   ++tinst_depth;
6163 #ifdef GATHER_STATISTICS
6164   if (tinst_depth > depth_reached)
6165     depth_reached = tinst_depth;
6166 #endif
6167
6168   ++tinst_level_tick;
6169   return 1;
6170 }
6171
6172 /* We're done instantiating this template; return to the instantiation
6173    context.  */
6174
6175 static void
6176 pop_tinst_level (void)
6177 {
6178   /* Restore the filename and line number stashed away when we started
6179      this instantiation.  */
6180   input_location = current_tinst_level->locus;
6181   in_system_header = current_tinst_level->in_system_header_p;
6182   current_tinst_level = current_tinst_level->next;
6183   --tinst_depth;
6184   ++tinst_level_tick;
6185 }
6186
6187 /* We're instantiating a deferred template; restore the template
6188    instantiation context in which the instantiation was requested, which
6189    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6190
6191 static tree
6192 reopen_tinst_level (struct tinst_level *level)
6193 {
6194   struct tinst_level *t;
6195
6196   tinst_depth = 0;
6197   for (t = level; t; t = t->next)
6198     ++tinst_depth;
6199
6200   current_tinst_level = level;
6201   pop_tinst_level ();
6202   return level->decl;
6203 }
6204
6205 /* Returns the TINST_LEVEL which gives the original instantiation
6206    context.  */
6207
6208 struct tinst_level *
6209 outermost_tinst_level (void)
6210 {
6211   struct tinst_level *level = current_tinst_level;
6212   if (level)
6213     while (level->next)
6214       level = level->next;
6215   return level;
6216 }
6217
6218 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6219    vector of template arguments, as for tsubst.
6220
6221    Returns an appropriate tsubst'd friend declaration.  */
6222
6223 static tree
6224 tsubst_friend_function (tree decl, tree args)
6225 {
6226   tree new_friend;
6227
6228   if (TREE_CODE (decl) == FUNCTION_DECL
6229       && DECL_TEMPLATE_INSTANTIATION (decl)
6230       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6231     /* This was a friend declared with an explicit template
6232        argument list, e.g.:
6233
6234        friend void f<>(T);
6235
6236        to indicate that f was a template instantiation, not a new
6237        function declaration.  Now, we have to figure out what
6238        instantiation of what template.  */
6239     {
6240       tree template_id, arglist, fns;
6241       tree new_args;
6242       tree tmpl;
6243       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6244
6245       /* Friend functions are looked up in the containing namespace scope.
6246          We must enter that scope, to avoid finding member functions of the
6247          current cless with same name.  */
6248       push_nested_namespace (ns);
6249       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6250                          tf_warning_or_error, NULL_TREE,
6251                          /*integral_constant_expression_p=*/false);
6252       pop_nested_namespace (ns);
6253       arglist = tsubst (DECL_TI_ARGS (decl), args,
6254                         tf_warning_or_error, NULL_TREE);
6255       template_id = lookup_template_function (fns, arglist);
6256
6257       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6258       tmpl = determine_specialization (template_id, new_friend,
6259                                        &new_args,
6260                                        /*need_member_template=*/0,
6261                                        TREE_VEC_LENGTH (args),
6262                                        tsk_none);
6263       return instantiate_template (tmpl, new_args, tf_error);
6264     }
6265
6266   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6267
6268   /* The NEW_FRIEND will look like an instantiation, to the
6269      compiler, but is not an instantiation from the point of view of
6270      the language.  For example, we might have had:
6271
6272      template <class T> struct S {
6273        template <class U> friend void f(T, U);
6274      };
6275
6276      Then, in S<int>, template <class U> void f(int, U) is not an
6277      instantiation of anything.  */
6278   if (new_friend == error_mark_node)
6279     return error_mark_node;
6280
6281   DECL_USE_TEMPLATE (new_friend) = 0;
6282   if (TREE_CODE (decl) == TEMPLATE_DECL)
6283     {
6284       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6285       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6286         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6287     }
6288
6289   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6290      is not a template instantiation and should not be mangled like
6291      one.  Therefore, we forget the mangling here; we'll recompute it
6292      later if we need it.  */
6293   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6294     {
6295       SET_DECL_RTL (new_friend, NULL_RTX);
6296       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6297     }
6298
6299   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6300     {
6301       tree old_decl;
6302       tree new_friend_template_info;
6303       tree new_friend_result_template_info;
6304       tree ns;
6305       int  new_friend_is_defn;
6306
6307       /* We must save some information from NEW_FRIEND before calling
6308          duplicate decls since that function will free NEW_FRIEND if
6309          possible.  */
6310       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6311       new_friend_is_defn =
6312             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6313                            (template_for_substitution (new_friend)))
6314              != NULL_TREE);
6315       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6316         {
6317           /* This declaration is a `primary' template.  */
6318           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6319
6320           new_friend_result_template_info
6321             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6322         }
6323       else
6324         new_friend_result_template_info = NULL_TREE;
6325
6326       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6327       if (new_friend_is_defn)
6328         DECL_INITIAL (new_friend) = error_mark_node;
6329
6330       /* Inside pushdecl_namespace_level, we will push into the
6331          current namespace. However, the friend function should go
6332          into the namespace of the template.  */
6333       ns = decl_namespace_context (new_friend);
6334       push_nested_namespace (ns);
6335       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6336       pop_nested_namespace (ns);
6337
6338       if (old_decl == error_mark_node)
6339         return error_mark_node;
6340
6341       if (old_decl != new_friend)
6342         {
6343           /* This new friend declaration matched an existing
6344              declaration.  For example, given:
6345
6346                template <class T> void f(T);
6347                template <class U> class C {
6348                  template <class T> friend void f(T) {}
6349                };
6350
6351              the friend declaration actually provides the definition
6352              of `f', once C has been instantiated for some type.  So,
6353              old_decl will be the out-of-class template declaration,
6354              while new_friend is the in-class definition.
6355
6356              But, if `f' was called before this point, the
6357              instantiation of `f' will have DECL_TI_ARGS corresponding
6358              to `T' but not to `U', references to which might appear
6359              in the definition of `f'.  Previously, the most general
6360              template for an instantiation of `f' was the out-of-class
6361              version; now it is the in-class version.  Therefore, we
6362              run through all specialization of `f', adding to their
6363              DECL_TI_ARGS appropriately.  In particular, they need a
6364              new set of outer arguments, corresponding to the
6365              arguments for this class instantiation.
6366
6367              The same situation can arise with something like this:
6368
6369                friend void f(int);
6370                template <class T> class C {
6371                  friend void f(T) {}
6372                };
6373
6374              when `C<int>' is instantiated.  Now, `f(int)' is defined
6375              in the class.  */
6376
6377           if (!new_friend_is_defn)
6378             /* On the other hand, if the in-class declaration does
6379                *not* provide a definition, then we don't want to alter
6380                existing definitions.  We can just leave everything
6381                alone.  */
6382             ;
6383           else
6384             {
6385               /* Overwrite whatever template info was there before, if
6386                  any, with the new template information pertaining to
6387                  the declaration.  */
6388               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6389
6390               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6391                 reregister_specialization (new_friend,
6392                                            most_general_template (old_decl),
6393                                            old_decl);
6394               else
6395                 {
6396                   tree t;
6397                   tree new_friend_args;
6398
6399                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6400                     = new_friend_result_template_info;
6401
6402                   new_friend_args = TI_ARGS (new_friend_template_info);
6403                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6404                        t != NULL_TREE;
6405                        t = TREE_CHAIN (t))
6406                     {
6407                       tree spec = TREE_VALUE (t);
6408
6409                       DECL_TI_ARGS (spec)
6410                         = add_outermost_template_args (new_friend_args,
6411                                                        DECL_TI_ARGS (spec));
6412                     }
6413
6414                   /* Now, since specializations are always supposed to
6415                      hang off of the most general template, we must move
6416                      them.  */
6417                   t = most_general_template (old_decl);
6418                   if (t != old_decl)
6419                     {
6420                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6421                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6422                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6423                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6424                     }
6425                 }
6426             }
6427
6428           /* The information from NEW_FRIEND has been merged into OLD_DECL
6429              by duplicate_decls.  */
6430           new_friend = old_decl;
6431         }
6432     }
6433   else
6434     {
6435       tree context = DECL_CONTEXT (new_friend);
6436       bool dependent_p;
6437
6438       /* In the code
6439            template <class T> class C {
6440              template <class U> friend void C1<U>::f (); // case 1
6441              friend void C2<T>::f ();                    // case 2
6442            };
6443          we only need to make sure CONTEXT is a complete type for
6444          case 2.  To distinguish between the two cases, we note that
6445          CONTEXT of case 1 remains dependent type after tsubst while
6446          this isn't true for case 2.  */
6447       ++processing_template_decl;
6448       dependent_p = dependent_type_p (context);
6449       --processing_template_decl;
6450
6451       if (!dependent_p
6452           && !complete_type_or_else (context, NULL_TREE))
6453         return error_mark_node;
6454
6455       if (COMPLETE_TYPE_P (context))
6456         {
6457           /* Check to see that the declaration is really present, and,
6458              possibly obtain an improved declaration.  */
6459           tree fn = check_classfn (context,
6460                                    new_friend, NULL_TREE);
6461
6462           if (fn)
6463             new_friend = fn;
6464         }
6465     }
6466
6467   return new_friend;
6468 }
6469
6470 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6471    template arguments, as for tsubst.
6472
6473    Returns an appropriate tsubst'd friend type or error_mark_node on
6474    failure.  */
6475
6476 static tree
6477 tsubst_friend_class (tree friend_tmpl, tree args)
6478 {
6479   tree friend_type;
6480   tree tmpl;
6481   tree context;
6482
6483   context = DECL_CONTEXT (friend_tmpl);
6484
6485   if (context)
6486     {
6487       if (TREE_CODE (context) == NAMESPACE_DECL)
6488         push_nested_namespace (context);
6489       else
6490         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6491     }
6492
6493   /* Look for a class template declaration.  We look for hidden names
6494      because two friend declarations of the same template are the
6495      same.  For example, in:
6496
6497        struct A { 
6498          template <typename> friend class F;
6499        };
6500        template <typename> struct B { 
6501          template <typename> friend class F;
6502        };
6503
6504      both F templates are the same.  */
6505   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6506                            /*block_p=*/true, 0, 
6507                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6508
6509   /* But, if we don't find one, it might be because we're in a
6510      situation like this:
6511
6512        template <class T>
6513        struct S {
6514          template <class U>
6515          friend struct S;
6516        };
6517
6518      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6519      for `S<int>', not the TEMPLATE_DECL.  */
6520   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6521     {
6522       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6523       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6524     }
6525
6526   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6527     {
6528       /* The friend template has already been declared.  Just
6529          check to see that the declarations match, and install any new
6530          default parameters.  We must tsubst the default parameters,
6531          of course.  We only need the innermost template parameters
6532          because that is all that redeclare_class_template will look
6533          at.  */
6534       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6535           > TMPL_ARGS_DEPTH (args))
6536         {
6537           tree parms;
6538           location_t saved_input_location;
6539           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6540                                          args, tf_warning_or_error);
6541
6542           saved_input_location = input_location;
6543           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6544           redeclare_class_template (TREE_TYPE (tmpl), parms);
6545           input_location = saved_input_location;
6546           
6547         }
6548
6549       friend_type = TREE_TYPE (tmpl);
6550     }
6551   else
6552     {
6553       /* The friend template has not already been declared.  In this
6554          case, the instantiation of the template class will cause the
6555          injection of this template into the global scope.  */
6556       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6557       if (tmpl == error_mark_node)
6558         return error_mark_node;
6559
6560       /* The new TMPL is not an instantiation of anything, so we
6561          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6562          the new type because that is supposed to be the corresponding
6563          template decl, i.e., TMPL.  */
6564       DECL_USE_TEMPLATE (tmpl) = 0;
6565       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6566       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6567       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6568         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6569
6570       /* Inject this template into the global scope.  */
6571       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6572     }
6573
6574   if (context)
6575     {
6576       if (TREE_CODE (context) == NAMESPACE_DECL)
6577         pop_nested_namespace (context);
6578       else
6579         pop_nested_class ();
6580     }
6581
6582   return friend_type;
6583 }
6584
6585 /* Returns zero if TYPE cannot be completed later due to circularity.
6586    Otherwise returns one.  */
6587
6588 static int
6589 can_complete_type_without_circularity (tree type)
6590 {
6591   if (type == NULL_TREE || type == error_mark_node)
6592     return 0;
6593   else if (COMPLETE_TYPE_P (type))
6594     return 1;
6595   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6596     return can_complete_type_without_circularity (TREE_TYPE (type));
6597   else if (CLASS_TYPE_P (type)
6598            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6599     return 0;
6600   else
6601     return 1;
6602 }
6603
6604 /* Apply any attributes which had to be deferred until instantiation
6605    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6606    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6607
6608 static void
6609 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6610                                 tree args, tsubst_flags_t complain, tree in_decl)
6611 {
6612   tree last_dep = NULL_TREE;
6613   tree t;
6614   tree *p;
6615
6616   for (t = attributes; t; t = TREE_CHAIN (t))
6617     if (ATTR_IS_DEPENDENT (t))
6618       {
6619         last_dep = t;
6620         attributes = copy_list (attributes);
6621         break;
6622       }
6623
6624   if (DECL_P (*decl_p))
6625     {
6626       if (TREE_TYPE (*decl_p) == error_mark_node)
6627         return;
6628       p = &DECL_ATTRIBUTES (*decl_p);
6629     }
6630   else
6631     p = &TYPE_ATTRIBUTES (*decl_p);
6632
6633   if (last_dep)
6634     {
6635       tree late_attrs = NULL_TREE;
6636       tree *q = &late_attrs;
6637
6638       for (*p = attributes; *p; )
6639         {
6640           t = *p;
6641           if (ATTR_IS_DEPENDENT (t))
6642             {
6643               *p = TREE_CHAIN (t);
6644               TREE_CHAIN (t) = NULL_TREE;
6645               TREE_VALUE (t)
6646                 = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6647                                /*integral_constant_expression_p=*/false);
6648               *q = t;
6649               q = &TREE_CHAIN (t);
6650             }
6651           else
6652             p = &TREE_CHAIN (t);
6653         }
6654
6655       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
6656     }
6657 }
6658
6659 tree
6660 instantiate_class_template (tree type)
6661 {
6662   tree template, args, pattern, t, member;
6663   tree typedecl;
6664   tree pbinfo;
6665   tree base_list;
6666
6667   if (type == error_mark_node)
6668     return error_mark_node;
6669
6670   if (TYPE_BEING_DEFINED (type)
6671       || COMPLETE_TYPE_P (type)
6672       || dependent_type_p (type))
6673     return type;
6674
6675   /* Figure out which template is being instantiated.  */
6676   template = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6677   gcc_assert (TREE_CODE (template) == TEMPLATE_DECL);
6678
6679   /* Determine what specialization of the original template to
6680      instantiate.  */
6681   t = most_specialized_class (type, template);
6682   if (t == error_mark_node)
6683     {
6684       TYPE_BEING_DEFINED (type) = 1;
6685       return error_mark_node;
6686     }
6687   else if (t)
6688     {
6689       /* This TYPE is actually an instantiation of a partial
6690          specialization.  We replace the innermost set of ARGS with
6691          the arguments appropriate for substitution.  For example,
6692          given:
6693
6694            template <class T> struct S {};
6695            template <class T> struct S<T*> {};
6696
6697          and supposing that we are instantiating S<int*>, ARGS will
6698          presently be {int*} -- but we need {int}.  */
6699       pattern = TREE_TYPE (t);
6700       args = TREE_PURPOSE (t);
6701     }
6702   else
6703     {
6704       pattern = TREE_TYPE (template);
6705       args = CLASSTYPE_TI_ARGS (type);
6706     }
6707
6708   /* If the template we're instantiating is incomplete, then clearly
6709      there's nothing we can do.  */
6710   if (!COMPLETE_TYPE_P (pattern))
6711     return type;
6712
6713   /* If we've recursively instantiated too many templates, stop.  */
6714   if (! push_tinst_level (type))
6715     return type;
6716
6717   /* Now we're really doing the instantiation.  Mark the type as in
6718      the process of being defined.  */
6719   TYPE_BEING_DEFINED (type) = 1;
6720
6721   /* We may be in the middle of deferred access check.  Disable
6722      it now.  */
6723   push_deferring_access_checks (dk_no_deferred);
6724
6725   push_to_top_level ();
6726
6727   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
6728
6729   /* Set the input location to the template definition. This is needed
6730      if tsubsting causes an error.  */
6731   typedecl = TYPE_MAIN_DECL (type);
6732   input_location = DECL_SOURCE_LOCATION (typedecl);
6733   in_system_header = DECL_IN_SYSTEM_HEADER (typedecl);
6734
6735   TYPE_HAS_CONSTRUCTOR (type) = TYPE_HAS_CONSTRUCTOR (pattern);
6736   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
6737   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
6738   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
6739   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
6740   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
6741   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
6742   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
6743   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
6744   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
6745   TYPE_PACKED (type) = TYPE_PACKED (pattern);
6746   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
6747   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
6748   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
6749   if (ANON_AGGR_TYPE_P (pattern))
6750     SET_ANON_AGGR_TYPE_P (type);
6751   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
6752     {
6753       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
6754       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
6755     }
6756
6757   pbinfo = TYPE_BINFO (pattern);
6758
6759   /* We should never instantiate a nested class before its enclosing
6760      class; we need to look up the nested class by name before we can
6761      instantiate it, and that lookup should instantiate the enclosing
6762      class.  */
6763   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
6764               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
6765               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
6766
6767   base_list = NULL_TREE;
6768   if (BINFO_N_BASE_BINFOS (pbinfo))
6769     {
6770       tree pbase_binfo;
6771       tree context = TYPE_CONTEXT (type);
6772       tree pushed_scope;
6773       int i;
6774
6775       /* We must enter the scope containing the type, as that is where
6776          the accessibility of types named in dependent bases are
6777          looked up from.  */
6778       pushed_scope = push_scope (context ? context : global_namespace);
6779
6780       /* Substitute into each of the bases to determine the actual
6781          basetypes.  */
6782       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
6783         {
6784           tree base;
6785           tree access = BINFO_BASE_ACCESS (pbinfo, i);
6786           tree expanded_bases = NULL_TREE;
6787           int idx, len = 1;
6788
6789           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
6790             {
6791               expanded_bases = 
6792                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
6793                                        args, tf_error, NULL_TREE);
6794               if (expanded_bases == error_mark_node)
6795                 continue;
6796
6797               len = TREE_VEC_LENGTH (expanded_bases);
6798             }
6799
6800           for (idx = 0; idx < len; idx++)
6801             {
6802               if (expanded_bases)
6803                 /* Extract the already-expanded base class.  */
6804                 base = TREE_VEC_ELT (expanded_bases, idx);
6805               else
6806                 /* Substitute to figure out the base class.  */
6807                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
6808                                NULL_TREE);
6809
6810               if (base == error_mark_node)
6811                 continue;
6812
6813               base_list = tree_cons (access, base, base_list);
6814               if (BINFO_VIRTUAL_P (pbase_binfo))
6815                 TREE_TYPE (base_list) = integer_type_node;
6816             }
6817         }
6818
6819       /* The list is now in reverse order; correct that.  */
6820       base_list = nreverse (base_list);
6821
6822       if (pushed_scope)
6823         pop_scope (pushed_scope);
6824     }
6825   /* Now call xref_basetypes to set up all the base-class
6826      information.  */
6827   xref_basetypes (type, base_list);
6828
6829   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
6830                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
6831                                   args, tf_error, NULL_TREE);
6832
6833   /* Now that our base classes are set up, enter the scope of the
6834      class, so that name lookups into base classes, etc. will work
6835      correctly.  This is precisely analogous to what we do in
6836      begin_class_definition when defining an ordinary non-template
6837      class, except we also need to push the enclosing classes.  */
6838   push_nested_class (type);
6839
6840   /* Now members are processed in the order of declaration.  */
6841   for (member = CLASSTYPE_DECL_LIST (pattern);
6842        member; member = TREE_CHAIN (member))
6843     {
6844       tree t = TREE_VALUE (member);
6845
6846       if (TREE_PURPOSE (member))
6847         {
6848           if (TYPE_P (t))
6849             {
6850               /* Build new CLASSTYPE_NESTED_UTDS.  */
6851
6852               tree newtag;
6853               bool class_template_p;
6854
6855               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
6856                                   && TYPE_LANG_SPECIFIC (t)
6857                                   && CLASSTYPE_IS_TEMPLATE (t));
6858               /* If the member is a class template, then -- even after
6859                  substitution -- there may be dependent types in the
6860                  template argument list for the class.  We increment
6861                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
6862                  that function will assume that no types are dependent
6863                  when outside of a template.  */
6864               if (class_template_p)
6865                 ++processing_template_decl;
6866               newtag = tsubst (t, args, tf_error, NULL_TREE);
6867               if (class_template_p)
6868                 --processing_template_decl;
6869               if (newtag == error_mark_node)
6870                 continue;
6871
6872               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
6873                 {
6874                   tree name = TYPE_IDENTIFIER (t);
6875
6876                   if (class_template_p)
6877                     /* Unfortunately, lookup_template_class sets
6878                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
6879                        instantiation (i.e., for the type of a member
6880                        template class nested within a template class.)
6881                        This behavior is required for
6882                        maybe_process_partial_specialization to work
6883                        correctly, but is not accurate in this case;
6884                        the TAG is not an instantiation of anything.
6885                        (The corresponding TEMPLATE_DECL is an
6886                        instantiation, but the TYPE is not.) */
6887                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
6888
6889                   /* Now, we call pushtag to put this NEWTAG into the scope of
6890                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
6891                      pushtag calling push_template_decl.  We don't have to do
6892                      this for enums because it will already have been done in
6893                      tsubst_enum.  */
6894                   if (name)
6895                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
6896                   pushtag (name, newtag, /*tag_scope=*/ts_current);
6897                 }
6898             }
6899           else if (TREE_CODE (t) == FUNCTION_DECL
6900                    || DECL_FUNCTION_TEMPLATE_P (t))
6901             {
6902               /* Build new TYPE_METHODS.  */
6903               tree r;
6904
6905               if (TREE_CODE (t) == TEMPLATE_DECL)
6906                 ++processing_template_decl;
6907               r = tsubst (t, args, tf_error, NULL_TREE);
6908               if (TREE_CODE (t) == TEMPLATE_DECL)
6909                 --processing_template_decl;
6910               set_current_access_from_decl (r);
6911               finish_member_declaration (r);
6912             }
6913           else
6914             {
6915               /* Build new TYPE_FIELDS.  */
6916               if (TREE_CODE (t) == STATIC_ASSERT)
6917                 {
6918                   tree condition = 
6919                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
6920                                  tf_warning_or_error, NULL_TREE,
6921                                  /*integral_constant_expression_p=*/true);
6922                   finish_static_assert (condition,
6923                                         STATIC_ASSERT_MESSAGE (t), 
6924                                         STATIC_ASSERT_SOURCE_LOCATION (t),
6925                                         /*member_p=*/true);
6926                 }
6927               else if (TREE_CODE (t) != CONST_DECL)
6928                 {
6929                   tree r;
6930
6931                   /* The the file and line for this declaration, to
6932                      assist in error message reporting.  Since we
6933                      called push_tinst_level above, we don't need to
6934                      restore these.  */
6935                   input_location = DECL_SOURCE_LOCATION (t);
6936
6937                   if (TREE_CODE (t) == TEMPLATE_DECL)
6938                     ++processing_template_decl;
6939                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
6940                   if (TREE_CODE (t) == TEMPLATE_DECL)
6941                     --processing_template_decl;
6942                   if (TREE_CODE (r) == VAR_DECL)
6943                     {
6944                       /* In [temp.inst]:
6945
6946                            [t]he initialization (and any associated
6947                            side-effects) of a static data member does
6948                            not occur unless the static data member is
6949                            itself used in a way that requires the
6950                            definition of the static data member to
6951                            exist.
6952
6953                          Therefore, we do not substitute into the
6954                          initialized for the static data member here.  */
6955                       finish_static_data_member_decl
6956                         (r,
6957                          /*init=*/NULL_TREE,
6958                          /*init_const_expr_p=*/false,
6959                          /*asmspec_tree=*/NULL_TREE,
6960                          /*flags=*/0);
6961                       if (DECL_INITIALIZED_IN_CLASS_P (r))
6962                         check_static_variable_definition (r, TREE_TYPE (r));
6963                     }
6964                   else if (TREE_CODE (r) == FIELD_DECL)
6965                     {
6966                       /* Determine whether R has a valid type and can be
6967                          completed later.  If R is invalid, then it is
6968                          replaced by error_mark_node so that it will not be
6969                          added to TYPE_FIELDS.  */
6970                       tree rtype = TREE_TYPE (r);
6971                       if (can_complete_type_without_circularity (rtype))
6972                         complete_type (rtype);
6973
6974                       if (!COMPLETE_TYPE_P (rtype))
6975                         {
6976                           cxx_incomplete_type_error (r, rtype);
6977                           r = error_mark_node;
6978                         }
6979                     }
6980
6981                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
6982                      such a thing will already have been added to the field
6983                      list by tsubst_enum in finish_member_declaration in the
6984                      CLASSTYPE_NESTED_UTDS case above.  */
6985                   if (!(TREE_CODE (r) == TYPE_DECL
6986                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
6987                         && DECL_ARTIFICIAL (r)))
6988                     {
6989                       set_current_access_from_decl (r);
6990                       finish_member_declaration (r);
6991                     }
6992                 }
6993             }
6994         }
6995       else
6996         {
6997           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
6998             {
6999               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7000
7001               tree friend_type = t;
7002               bool adjust_processing_template_decl = false;
7003
7004               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7005                 {
7006                   /* template <class T> friend class C;  */
7007                   friend_type = tsubst_friend_class (friend_type, args);
7008                   adjust_processing_template_decl = true;
7009                 }
7010               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7011                 {
7012                   /* template <class T> friend class C::D;  */
7013                   friend_type = tsubst (friend_type, args,
7014                                         tf_warning_or_error, NULL_TREE);
7015                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7016                     friend_type = TREE_TYPE (friend_type);
7017                   adjust_processing_template_decl = true;
7018                 }
7019               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7020                 {
7021                   /* This could be either
7022
7023                        friend class T::C;
7024
7025                      when dependent_type_p is false or
7026
7027                        template <class U> friend class T::C;
7028
7029                      otherwise.  */
7030                   friend_type = tsubst (friend_type, args,
7031                                         tf_warning_or_error, NULL_TREE);
7032                   /* Bump processing_template_decl for correct
7033                      dependent_type_p calculation.  */
7034                   ++processing_template_decl;
7035                   if (dependent_type_p (friend_type))
7036                     adjust_processing_template_decl = true;
7037                   --processing_template_decl;
7038                 }
7039               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7040                        && hidden_name_p (TYPE_NAME (friend_type)))
7041                 {
7042                   /* friend class C;
7043
7044                      where C hasn't been declared yet.  Let's lookup name
7045                      from namespace scope directly, bypassing any name that
7046                      come from dependent base class.  */
7047                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7048
7049                   /* The call to xref_tag_from_type does injection for friend
7050                      classes.  */
7051                   push_nested_namespace (ns);
7052                   friend_type =
7053                     xref_tag_from_type (friend_type, NULL_TREE,
7054                                         /*tag_scope=*/ts_current);
7055                   pop_nested_namespace (ns);
7056                 }
7057               else if (uses_template_parms (friend_type))
7058                 /* friend class C<T>;  */
7059                 friend_type = tsubst (friend_type, args,
7060                                       tf_warning_or_error, NULL_TREE);
7061               /* Otherwise it's
7062
7063                    friend class C;
7064
7065                  where C is already declared or
7066
7067                    friend class C<int>;
7068
7069                  We don't have to do anything in these cases.  */
7070
7071               if (adjust_processing_template_decl)
7072                 /* Trick make_friend_class into realizing that the friend
7073                    we're adding is a template, not an ordinary class.  It's
7074                    important that we use make_friend_class since it will
7075                    perform some error-checking and output cross-reference
7076                    information.  */
7077                 ++processing_template_decl;
7078
7079               if (friend_type != error_mark_node)
7080                 make_friend_class (type, friend_type, /*complain=*/false);
7081
7082               if (adjust_processing_template_decl)
7083                 --processing_template_decl;
7084             }
7085           else
7086             {
7087               /* Build new DECL_FRIENDLIST.  */
7088               tree r;
7089
7090               /* The the file and line for this declaration, to
7091                  assist in error message reporting.  Since we
7092                  called push_tinst_level above, we don't need to
7093                  restore these.  */
7094               input_location = DECL_SOURCE_LOCATION (t);
7095
7096               if (TREE_CODE (t) == TEMPLATE_DECL)
7097                 {
7098                   ++processing_template_decl;
7099                   push_deferring_access_checks (dk_no_check);
7100                 }
7101
7102               r = tsubst_friend_function (t, args);
7103               add_friend (type, r, /*complain=*/false);
7104               if (TREE_CODE (t) == TEMPLATE_DECL)
7105                 {
7106                   pop_deferring_access_checks ();
7107                   --processing_template_decl;
7108                 }
7109             }
7110         }
7111     }
7112
7113   /* Set the file and line number information to whatever is given for
7114      the class itself.  This puts error messages involving generated
7115      implicit functions at a predictable point, and the same point
7116      that would be used for non-template classes.  */
7117   input_location = DECL_SOURCE_LOCATION (typedecl);
7118
7119   unreverse_member_declarations (type);
7120   finish_struct_1 (type);
7121   TYPE_BEING_DEFINED (type) = 0;
7122
7123   /* Now that the class is complete, instantiate default arguments for
7124      any member functions.  We don't do this earlier because the
7125      default arguments may reference members of the class.  */
7126   if (!PRIMARY_TEMPLATE_P (template))
7127     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7128       if (TREE_CODE (t) == FUNCTION_DECL
7129           /* Implicitly generated member functions will not have template
7130              information; they are not instantiations, but instead are
7131              created "fresh" for each instantiation.  */
7132           && DECL_TEMPLATE_INFO (t))
7133         tsubst_default_arguments (t);
7134
7135   pop_nested_class ();
7136   pop_from_top_level ();
7137   pop_deferring_access_checks ();
7138   pop_tinst_level ();
7139
7140   /* The vtable for a template class can be emitted in any translation
7141      unit in which the class is instantiated.  When there is no key
7142      method, however, finish_struct_1 will already have added TYPE to
7143      the keyed_classes list.  */
7144   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7145     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7146
7147   return type;
7148 }
7149
7150 static tree
7151 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7152 {
7153   tree r;
7154
7155   if (!t)
7156     r = t;
7157   else if (TYPE_P (t))
7158     r = tsubst (t, args, complain, in_decl);
7159   else
7160     {
7161       r = tsubst_expr (t, args, complain, in_decl,
7162                        /*integral_constant_expression_p=*/true);
7163       r = fold_non_dependent_expr (r);
7164     }
7165   return r;
7166 }
7167
7168 /* Substitute ARGS into T, which is an pack expansion
7169    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7170    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7171    (if only a partial substitution could be performed) or
7172    ERROR_MARK_NODE if there was an error.  */
7173 tree
7174 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7175                        tree in_decl)
7176 {
7177   tree pattern;
7178   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7179   tree first_arg_pack; int i, len = -1;
7180   tree result;
7181   int incomplete = 0;
7182
7183   gcc_assert (PACK_EXPANSION_P (t));
7184   pattern = PACK_EXPANSION_PATTERN (t);
7185
7186   /* Determine the argument packs that will instantiate the parameter
7187      packs used in the expansion expression. While we're at it,
7188      compute the number of arguments to be expanded and make sure it
7189      is consistent.  */
7190   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7191        pack = TREE_CHAIN (pack))
7192     {
7193       tree parm_pack = TREE_VALUE (pack);
7194       tree arg_pack = NULL_TREE;
7195       tree orig_arg = NULL_TREE;
7196
7197       if (TREE_CODE (parm_pack) == PARM_DECL)
7198         {
7199           if (local_specializations)
7200             arg_pack = retrieve_local_specialization (parm_pack);
7201         }
7202       else
7203         {
7204           int level, idx, levels;
7205           template_parm_level_and_index (parm_pack, &level, &idx);
7206
7207           levels = TMPL_ARGS_DEPTH (args);
7208           if (level <= levels)
7209             arg_pack = TMPL_ARG (args, level, idx);
7210         }
7211
7212       orig_arg = arg_pack;
7213       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7214         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7215       
7216       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7217         /* This can only happen if we forget to expand an argument
7218            pack somewhere else. Just return an error, silently.  */
7219         {
7220           result = make_tree_vec (1);
7221           TREE_VEC_ELT (result, 0) = error_mark_node;
7222           return result;
7223         }
7224
7225       if (arg_pack
7226           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7227           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7228         {
7229           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7230           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7231           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7232               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7233             /* The argument pack that the parameter maps to is just an
7234                expansion of the parameter itself, such as one would
7235                find in the implicit typedef of a class inside the
7236                class itself.  Consider this parameter "unsubstituted",
7237                so that we will maintain the outer pack expansion.  */
7238             arg_pack = NULL_TREE;
7239         }
7240           
7241       if (arg_pack)
7242         {
7243           int my_len = 
7244             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7245
7246           /* It's all-or-nothing with incomplete argument packs.  */
7247           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7248             return error_mark_node;
7249           
7250           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7251             incomplete = 1;
7252
7253           if (len < 0)
7254             {
7255               len = my_len;
7256               first_arg_pack = arg_pack;
7257             }
7258           else if (len != my_len)
7259             {
7260               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7261                 error ("mismatched argument pack lengths while expanding "
7262                        "%<%T%>",
7263                        pattern);
7264               else
7265                 error ("mismatched argument pack lengths while expanding "
7266                        "%<%E%>",
7267                        pattern);
7268               return error_mark_node;
7269             }
7270
7271           /* Keep track of the parameter packs and their corresponding
7272              argument packs.  */
7273           packs = tree_cons (parm_pack, arg_pack, packs);
7274           TREE_TYPE (packs) = orig_arg;
7275         }
7276       else
7277         /* We can't substitute for this parameter pack.  */
7278         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7279                                          TREE_VALUE (pack),
7280                                          unsubstituted_packs);
7281     }
7282
7283   /* We cannot expand this expansion expression, because we don't have
7284      all of the argument packs we need. Substitute into the pattern
7285      and return a PACK_EXPANSION_*. The caller will need to deal with
7286      that.  */
7287   if (unsubstituted_packs)
7288     return make_pack_expansion (tsubst (pattern, args, complain, 
7289                                         in_decl));
7290
7291   /* We could not find any argument packs that work.  */
7292   if (len < 0)
7293     return error_mark_node;
7294
7295   /* For each argument in each argument pack, substitute into the
7296      pattern.  */
7297   result = make_tree_vec (len + incomplete);
7298   for (i = 0; i < len + incomplete; ++i)
7299     {
7300       /* For parameter pack, change the substitution of the parameter
7301          pack to the ith argument in its argument pack, then expand
7302          the pattern.  */
7303       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7304         {
7305           tree parm = TREE_PURPOSE (pack);
7306
7307           if (TREE_CODE (parm) == PARM_DECL)
7308             {
7309               /* Select the Ith argument from the pack.  */
7310               tree arg = make_node (ARGUMENT_PACK_SELECT);
7311               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7312               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7313               mark_used (parm);
7314               register_local_specialization (arg, parm);
7315             }
7316           else
7317             {
7318               tree value = parm;
7319               int idx, level;
7320               template_parm_level_and_index (parm, &level, &idx);
7321               
7322               if (i < len) 
7323                 {
7324                   /* Select the Ith argument from the pack. */
7325                   value = make_node (ARGUMENT_PACK_SELECT);
7326                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7327                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7328                 }
7329
7330               /* Update the corresponding argument.  */
7331               TMPL_ARG (args, level, idx) = value;
7332             }
7333         }
7334
7335       /* Substitute into the PATTERN with the altered arguments.  */
7336       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7337         TREE_VEC_ELT (result, i) = 
7338           tsubst_expr (pattern, args, complain, in_decl,
7339                        /*integral_constant_expression_p=*/false);
7340       else
7341         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7342
7343       if (i == len)
7344         /* When we have incomplete argument packs, the last "expanded"
7345            result is itself a pack expansion, which allows us
7346            to deduce more arguments.  */
7347         TREE_VEC_ELT (result, i) = 
7348           make_pack_expansion (TREE_VEC_ELT (result, i));
7349
7350       if (TREE_VEC_ELT (result, i) == error_mark_node)
7351         {
7352           result = error_mark_node;
7353           break;
7354         }
7355     }
7356   
7357   /* Update ARGS to restore the substitution from parameter packs to
7358      their argument packs.  */
7359   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7360     {
7361       tree parm = TREE_PURPOSE (pack);
7362
7363       if (TREE_CODE (parm) == PARM_DECL)
7364         register_local_specialization (TREE_TYPE (pack), parm);
7365       else
7366         {
7367           int idx, level;
7368           template_parm_level_and_index (parm, &level, &idx);
7369           
7370           /* Update the corresponding argument.  */
7371           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7372             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7373               TREE_TYPE (pack);
7374           else
7375             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7376         }
7377     }
7378
7379   return result;
7380 }
7381
7382 /* Substitute ARGS into the vector or list of template arguments T.  */
7383
7384 static tree
7385 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7386 {
7387   tree orig_t = t;
7388   int len = TREE_VEC_LENGTH (t);
7389   int need_new = 0, i, expanded_len_adjust = 0, out;
7390   tree *elts = (tree *) alloca (len * sizeof (tree));
7391
7392   for (i = 0; i < len; i++)
7393     {
7394       tree orig_arg = TREE_VEC_ELT (t, i);
7395       tree new_arg;
7396
7397       if (TREE_CODE (orig_arg) == TREE_VEC)
7398         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7399       else if (PACK_EXPANSION_P (orig_arg))
7400         {
7401           /* Substitute into an expansion expression.  */
7402           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7403
7404           if (TREE_CODE (new_arg) == TREE_VEC)
7405             /* Add to the expanded length adjustment the number of
7406                expanded arguments. We subtract one from this
7407                measurement, because the argument pack expression
7408                itself is already counted as 1 in
7409                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7410                the argument pack is empty.  */
7411             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7412         }
7413       else if (ARGUMENT_PACK_P (orig_arg))
7414         {
7415           /* Substitute into each of the arguments.  */
7416           new_arg = make_node (TREE_CODE (orig_arg));
7417           
7418           SET_ARGUMENT_PACK_ARGS (
7419             new_arg,
7420             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7421                                   args, complain, in_decl));
7422
7423           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7424             new_arg = error_mark_node;
7425
7426           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7427             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7428                                           complain, in_decl);
7429             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7430
7431             if (TREE_TYPE (new_arg) == error_mark_node)
7432               new_arg = error_mark_node;
7433           }
7434         }
7435       else
7436         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7437
7438       if (new_arg == error_mark_node)
7439         return error_mark_node;
7440
7441       elts[i] = new_arg;
7442       if (new_arg != orig_arg)
7443         need_new = 1;
7444     }
7445
7446   if (!need_new)
7447     return t;
7448
7449   /* Make space for the expanded arguments coming from template
7450      argument packs.  */
7451   t = make_tree_vec (len + expanded_len_adjust);
7452   for (i = 0, out = 0; i < len; i++)
7453     {
7454       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7455            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7456           && TREE_CODE (elts[i]) == TREE_VEC)
7457         {
7458           int idx;
7459
7460           /* Now expand the template argument pack "in place".  */
7461           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7462             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7463         }
7464       else
7465         {
7466           TREE_VEC_ELT (t, out) = elts[i];
7467           out++;
7468         }
7469     }
7470
7471   return t;
7472 }
7473
7474 /* Return the result of substituting ARGS into the template parameters
7475    given by PARMS.  If there are m levels of ARGS and m + n levels of
7476    PARMS, then the result will contain n levels of PARMS.  For
7477    example, if PARMS is `template <class T> template <class U>
7478    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7479    result will be `template <int*, double, class V>'.  */
7480
7481 static tree
7482 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7483 {
7484   tree r = NULL_TREE;
7485   tree* new_parms;
7486
7487   /* When substituting into a template, we must set
7488      PROCESSING_TEMPLATE_DECL as the template parameters may be
7489      dependent if they are based on one-another, and the dependency
7490      predicates are short-circuit outside of templates.  */
7491   ++processing_template_decl;
7492
7493   for (new_parms = &r;
7494        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7495        new_parms = &(TREE_CHAIN (*new_parms)),
7496          parms = TREE_CHAIN (parms))
7497     {
7498       tree new_vec =
7499         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7500       int i;
7501
7502       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7503         {
7504           tree tuple;
7505           tree default_value;
7506           tree parm_decl;
7507
7508           if (parms == error_mark_node)
7509             continue;
7510
7511           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7512
7513           if (tuple == error_mark_node)
7514             continue;
7515
7516           default_value = TREE_PURPOSE (tuple);
7517           parm_decl = TREE_VALUE (tuple);
7518
7519           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7520           if (TREE_CODE (parm_decl) == PARM_DECL
7521               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7522             parm_decl = error_mark_node;
7523           default_value = tsubst_template_arg (default_value, args,
7524                                                complain, NULL_TREE);
7525
7526           tuple = build_tree_list (default_value, parm_decl);
7527           TREE_VEC_ELT (new_vec, i) = tuple;
7528         }
7529
7530       *new_parms =
7531         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7532                              - TMPL_ARGS_DEPTH (args)),
7533                    new_vec, NULL_TREE);
7534     }
7535
7536   --processing_template_decl;
7537
7538   return r;
7539 }
7540
7541 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7542    type T.  If T is not an aggregate or enumeration type, it is
7543    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7544    ENTERING_SCOPE is nonzero, T is the context for a template which
7545    we are presently tsubst'ing.  Return the substituted value.  */
7546
7547 static tree
7548 tsubst_aggr_type (tree t,
7549                   tree args,
7550                   tsubst_flags_t complain,
7551                   tree in_decl,
7552                   int entering_scope)
7553 {
7554   if (t == NULL_TREE)
7555     return NULL_TREE;
7556
7557   switch (TREE_CODE (t))
7558     {
7559     case RECORD_TYPE:
7560       if (TYPE_PTRMEMFUNC_P (t))
7561         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7562
7563       /* Else fall through.  */
7564     case ENUMERAL_TYPE:
7565     case UNION_TYPE:
7566       if (TYPE_TEMPLATE_INFO (t))
7567         {
7568           tree argvec;
7569           tree context;
7570           tree r;
7571           bool saved_skip_evaluation;
7572
7573           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7574           saved_skip_evaluation = skip_evaluation;
7575           skip_evaluation = false;
7576
7577           /* First, determine the context for the type we are looking
7578              up.  */
7579           context = TYPE_CONTEXT (t);
7580           if (context)
7581             context = tsubst_aggr_type (context, args, complain,
7582                                         in_decl, /*entering_scope=*/1);
7583
7584           /* Then, figure out what arguments are appropriate for the
7585              type we are trying to find.  For example, given:
7586
7587                template <class T> struct S;
7588                template <class T, class U> void f(T, U) { S<U> su; }
7589
7590              and supposing that we are instantiating f<int, double>,
7591              then our ARGS will be {int, double}, but, when looking up
7592              S we only want {double}.  */
7593           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7594                                          complain, in_decl);
7595           if (argvec == error_mark_node)
7596             r = error_mark_node;
7597           else
7598             {
7599               r = lookup_template_class (t, argvec, in_decl, context,
7600                                          entering_scope, complain);
7601               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7602             }
7603
7604           skip_evaluation = saved_skip_evaluation;
7605
7606           return r;
7607         }
7608       else
7609         /* This is not a template type, so there's nothing to do.  */
7610         return t;
7611
7612     default:
7613       return tsubst (t, args, complain, in_decl);
7614     }
7615 }
7616
7617 /* Substitute into the default argument ARG (a default argument for
7618    FN), which has the indicated TYPE.  */
7619
7620 tree
7621 tsubst_default_argument (tree fn, tree type, tree arg)
7622 {
7623   tree saved_class_ptr = NULL_TREE;
7624   tree saved_class_ref = NULL_TREE;
7625
7626   /* This default argument came from a template.  Instantiate the
7627      default argument here, not in tsubst.  In the case of
7628      something like:
7629
7630        template <class T>
7631        struct S {
7632          static T t();
7633          void f(T = t());
7634        };
7635
7636      we must be careful to do name lookup in the scope of S<T>,
7637      rather than in the current class.  */
7638   push_access_scope (fn);
7639   /* The "this" pointer is not valid in a default argument.  */
7640   if (cfun)
7641     {
7642       saved_class_ptr = current_class_ptr;
7643       cp_function_chain->x_current_class_ptr = NULL_TREE;
7644       saved_class_ref = current_class_ref;
7645       cp_function_chain->x_current_class_ref = NULL_TREE;
7646     }
7647
7648   push_deferring_access_checks(dk_no_deferred);
7649   /* The default argument expression may cause implicitly defined
7650      member functions to be synthesized, which will result in garbage
7651      collection.  We must treat this situation as if we were within
7652      the body of function so as to avoid collecting live data on the
7653      stack.  */
7654   ++function_depth;
7655   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
7656                      tf_warning_or_error, NULL_TREE,
7657                      /*integral_constant_expression_p=*/false);
7658   --function_depth;
7659   pop_deferring_access_checks();
7660
7661   /* Restore the "this" pointer.  */
7662   if (cfun)
7663     {
7664       cp_function_chain->x_current_class_ptr = saved_class_ptr;
7665       cp_function_chain->x_current_class_ref = saved_class_ref;
7666     }
7667
7668   pop_access_scope (fn);
7669
7670   /* Make sure the default argument is reasonable.  */
7671   arg = check_default_argument (type, arg);
7672
7673   return arg;
7674 }
7675
7676 /* Substitute into all the default arguments for FN.  */
7677
7678 static void
7679 tsubst_default_arguments (tree fn)
7680 {
7681   tree arg;
7682   tree tmpl_args;
7683
7684   tmpl_args = DECL_TI_ARGS (fn);
7685
7686   /* If this function is not yet instantiated, we certainly don't need
7687      its default arguments.  */
7688   if (uses_template_parms (tmpl_args))
7689     return;
7690
7691   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
7692        arg;
7693        arg = TREE_CHAIN (arg))
7694     if (TREE_PURPOSE (arg))
7695       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
7696                                                     TREE_VALUE (arg),
7697                                                     TREE_PURPOSE (arg));
7698 }
7699
7700 /* Substitute the ARGS into the T, which is a _DECL.  Return the
7701    result of the substitution.  Issue error and warning messages under
7702    control of COMPLAIN.  */
7703
7704 static tree
7705 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
7706 {
7707   location_t saved_loc;
7708   tree r = NULL_TREE;
7709   tree in_decl = t;
7710
7711   /* Set the filename and linenumber to improve error-reporting.  */
7712   saved_loc = input_location;
7713   input_location = DECL_SOURCE_LOCATION (t);
7714
7715   switch (TREE_CODE (t))
7716     {
7717     case TEMPLATE_DECL:
7718       {
7719         /* We can get here when processing a member function template,
7720            member class template, and template template parameter of
7721            a template class.  */
7722         tree decl = DECL_TEMPLATE_RESULT (t);
7723         tree spec;
7724         tree tmpl_args;
7725         tree full_args;
7726
7727         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
7728           {
7729             /* Template template parameter is treated here.  */
7730             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7731             if (new_type == error_mark_node)
7732               return error_mark_node;
7733
7734             r = copy_decl (t);
7735             TREE_CHAIN (r) = NULL_TREE;
7736             TREE_TYPE (r) = new_type;
7737             DECL_TEMPLATE_RESULT (r)
7738               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
7739             DECL_TEMPLATE_PARMS (r)
7740               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
7741                                        complain);
7742             TYPE_NAME (new_type) = r;
7743             break;
7744           }
7745
7746         /* We might already have an instance of this template.
7747            The ARGS are for the surrounding class type, so the
7748            full args contain the tsubst'd args for the context,
7749            plus the innermost args from the template decl.  */
7750         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
7751           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
7752           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
7753         /* Because this is a template, the arguments will still be
7754            dependent, even after substitution.  If
7755            PROCESSING_TEMPLATE_DECL is not set, the dependency
7756            predicates will short-circuit.  */
7757         ++processing_template_decl;
7758         full_args = tsubst_template_args (tmpl_args, args,
7759                                           complain, in_decl);
7760         --processing_template_decl;
7761         if (full_args == error_mark_node)
7762           return error_mark_node;
7763
7764         /* tsubst_template_args doesn't copy the vector if
7765            nothing changed.  But, *something* should have
7766            changed.  */
7767         gcc_assert (full_args != tmpl_args);
7768
7769         spec = retrieve_specialization (t, full_args,
7770                                         /*class_specializations_p=*/true);
7771         if (spec != NULL_TREE)
7772           {
7773             r = spec;
7774             break;
7775           }
7776
7777         /* Make a new template decl.  It will be similar to the
7778            original, but will record the current template arguments.
7779            We also create a new function declaration, which is just
7780            like the old one, but points to this new template, rather
7781            than the old one.  */
7782         r = copy_decl (t);
7783         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
7784         TREE_CHAIN (r) = NULL_TREE;
7785
7786         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
7787
7788         if (TREE_CODE (decl) == TYPE_DECL)
7789           {
7790             tree new_type;
7791             ++processing_template_decl;
7792             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7793             --processing_template_decl;
7794             if (new_type == error_mark_node)
7795               return error_mark_node;
7796
7797             TREE_TYPE (r) = new_type;
7798             CLASSTYPE_TI_TEMPLATE (new_type) = r;
7799             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
7800             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
7801             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
7802           }
7803         else
7804           {
7805             tree new_decl;
7806             ++processing_template_decl;
7807             new_decl = tsubst (decl, args, complain, in_decl);
7808             --processing_template_decl;
7809             if (new_decl == error_mark_node)
7810               return error_mark_node;
7811
7812             DECL_TEMPLATE_RESULT (r) = new_decl;
7813             DECL_TI_TEMPLATE (new_decl) = r;
7814             TREE_TYPE (r) = TREE_TYPE (new_decl);
7815             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
7816             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
7817           }
7818
7819         SET_DECL_IMPLICIT_INSTANTIATION (r);
7820         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
7821         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
7822
7823         /* The template parameters for this new template are all the
7824            template parameters for the old template, except the
7825            outermost level of parameters.  */
7826         DECL_TEMPLATE_PARMS (r)
7827           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
7828                                    complain);
7829
7830         if (PRIMARY_TEMPLATE_P (t))
7831           DECL_PRIMARY_TEMPLATE (r) = r;
7832
7833         if (TREE_CODE (decl) != TYPE_DECL)
7834           /* Record this non-type partial instantiation.  */
7835           register_specialization (r, t,
7836                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
7837                                    false);
7838       }
7839       break;
7840
7841     case FUNCTION_DECL:
7842       {
7843         tree ctx;
7844         tree argvec = NULL_TREE;
7845         tree *friends;
7846         tree gen_tmpl;
7847         tree type;
7848         int member;
7849         int args_depth;
7850         int parms_depth;
7851
7852         /* Nobody should be tsubst'ing into non-template functions.  */
7853         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
7854
7855         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
7856           {
7857             tree spec;
7858             bool dependent_p;
7859
7860             /* If T is not dependent, just return it.  We have to
7861                increment PROCESSING_TEMPLATE_DECL because
7862                value_dependent_expression_p assumes that nothing is
7863                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
7864             ++processing_template_decl;
7865             dependent_p = value_dependent_expression_p (t);
7866             --processing_template_decl;
7867             if (!dependent_p)
7868               return t;
7869
7870             /* Calculate the most general template of which R is a
7871                specialization, and the complete set of arguments used to
7872                specialize R.  */
7873             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
7874             argvec = tsubst_template_args (DECL_TI_ARGS
7875                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
7876                                            args, complain, in_decl);
7877
7878             /* Check to see if we already have this specialization.  */
7879             spec = retrieve_specialization (gen_tmpl, argvec,
7880                                             /*class_specializations_p=*/false);
7881
7882             if (spec)
7883               {
7884                 r = spec;
7885                 break;
7886               }
7887
7888             /* We can see more levels of arguments than parameters if
7889                there was a specialization of a member template, like
7890                this:
7891
7892                  template <class T> struct S { template <class U> void f(); }
7893                  template <> template <class U> void S<int>::f(U);
7894
7895                Here, we'll be substituting into the specialization,
7896                because that's where we can find the code we actually
7897                want to generate, but we'll have enough arguments for
7898                the most general template.
7899
7900                We also deal with the peculiar case:
7901
7902                  template <class T> struct S {
7903                    template <class U> friend void f();
7904                  };
7905                  template <class U> void f() {}
7906                  template S<int>;
7907                  template void f<double>();
7908
7909                Here, the ARGS for the instantiation of will be {int,
7910                double}.  But, we only need as many ARGS as there are
7911                levels of template parameters in CODE_PATTERN.  We are
7912                careful not to get fooled into reducing the ARGS in
7913                situations like:
7914
7915                  template <class T> struct S { template <class U> void f(U); }
7916                  template <class T> template <> void S<T>::f(int) {}
7917
7918                which we can spot because the pattern will be a
7919                specialization in this case.  */
7920             args_depth = TMPL_ARGS_DEPTH (args);
7921             parms_depth =
7922               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
7923             if (args_depth > parms_depth
7924                 && !DECL_TEMPLATE_SPECIALIZATION (t))
7925               args = get_innermost_template_args (args, parms_depth);
7926           }
7927         else
7928           {
7929             /* This special case arises when we have something like this:
7930
7931                  template <class T> struct S {
7932                    friend void f<int>(int, double);
7933                  };
7934
7935                Here, the DECL_TI_TEMPLATE for the friend declaration
7936                will be an IDENTIFIER_NODE.  We are being called from
7937                tsubst_friend_function, and we want only to create a
7938                new decl (R) with appropriate types so that we can call
7939                determine_specialization.  */
7940             gen_tmpl = NULL_TREE;
7941           }
7942
7943         if (DECL_CLASS_SCOPE_P (t))
7944           {
7945             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
7946               member = 2;
7947             else
7948               member = 1;
7949             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
7950                                     complain, t, /*entering_scope=*/1);
7951           }
7952         else
7953           {
7954             member = 0;
7955             ctx = DECL_CONTEXT (t);
7956           }
7957         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7958         if (type == error_mark_node)
7959           return error_mark_node;
7960
7961         /* We do NOT check for matching decls pushed separately at this
7962            point, as they may not represent instantiations of this
7963            template, and in any case are considered separate under the
7964            discrete model.  */
7965         r = copy_decl (t);
7966         DECL_USE_TEMPLATE (r) = 0;
7967         TREE_TYPE (r) = type;
7968         /* Clear out the mangled name and RTL for the instantiation.  */
7969         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
7970         SET_DECL_RTL (r, NULL_RTX);
7971         DECL_INITIAL (r) = NULL_TREE;
7972         DECL_CONTEXT (r) = ctx;
7973
7974         if (member && DECL_CONV_FN_P (r))
7975           /* Type-conversion operator.  Reconstruct the name, in
7976              case it's the name of one of the template's parameters.  */
7977           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
7978
7979         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
7980                                      complain, t);
7981         DECL_RESULT (r) = NULL_TREE;
7982
7983         TREE_STATIC (r) = 0;
7984         TREE_PUBLIC (r) = TREE_PUBLIC (t);
7985         DECL_EXTERNAL (r) = 1;
7986         /* If this is an instantiation of a function with internal
7987            linkage, we already know what object file linkage will be
7988            assigned to the instantiation.  */
7989         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
7990         DECL_DEFER_OUTPUT (r) = 0;
7991         TREE_CHAIN (r) = NULL_TREE;
7992         DECL_PENDING_INLINE_INFO (r) = 0;
7993         DECL_PENDING_INLINE_P (r) = 0;
7994         DECL_SAVED_TREE (r) = NULL_TREE;
7995         TREE_USED (r) = 0;
7996         if (DECL_CLONED_FUNCTION (r))
7997           {
7998             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
7999                                                args, complain, t);
8000             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
8001             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
8002           }
8003
8004         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8005            this in the special friend case mentioned above where
8006            GEN_TMPL is NULL.  */
8007         if (gen_tmpl)
8008           {
8009             DECL_TEMPLATE_INFO (r)
8010               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8011             SET_DECL_IMPLICIT_INSTANTIATION (r);
8012             register_specialization (r, gen_tmpl, argvec, false);
8013
8014             /* We're not supposed to instantiate default arguments
8015                until they are called, for a template.  But, for a
8016                declaration like:
8017
8018                  template <class T> void f ()
8019                  { extern void g(int i = T()); }
8020
8021                we should do the substitution when the template is
8022                instantiated.  We handle the member function case in
8023                instantiate_class_template since the default arguments
8024                might refer to other members of the class.  */
8025             if (!member
8026                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8027                 && !uses_template_parms (argvec))
8028               tsubst_default_arguments (r);
8029           }
8030         else
8031           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8032
8033         /* Copy the list of befriending classes.  */
8034         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8035              *friends;
8036              friends = &TREE_CHAIN (*friends))
8037           {
8038             *friends = copy_node (*friends);
8039             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8040                                             args, complain,
8041                                             in_decl);
8042           }
8043
8044         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8045           {
8046             maybe_retrofit_in_chrg (r);
8047             if (DECL_CONSTRUCTOR_P (r))
8048               grok_ctor_properties (ctx, r);
8049             /* If this is an instantiation of a member template, clone it.
8050                If it isn't, that'll be handled by
8051                clone_constructors_and_destructors.  */
8052             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8053               clone_function_decl (r, /*update_method_vec_p=*/0);
8054           }
8055         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8056                  && !grok_op_properties (r, (complain & tf_error) != 0))
8057           return error_mark_node;
8058
8059         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8060           SET_DECL_FRIEND_CONTEXT (r,
8061                                    tsubst (DECL_FRIEND_CONTEXT (t),
8062                                             args, complain, in_decl));
8063
8064         /* Possibly limit visibility based on template args.  */
8065         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8066         if (DECL_VISIBILITY_SPECIFIED (t))
8067           {
8068             DECL_VISIBILITY_SPECIFIED (r) = 0;
8069             DECL_ATTRIBUTES (r)
8070               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8071           }
8072         determine_visibility (r);
8073
8074         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8075                                         args, complain, in_decl);
8076       }
8077       break;
8078
8079     case PARM_DECL:
8080       {
8081         tree type = NULL_TREE;
8082         int i, len = 1;
8083         tree expanded_types = NULL_TREE;
8084         tree prev_r = NULL_TREE;
8085         tree first_r = NULL_TREE;
8086
8087         if (FUNCTION_PARAMETER_PACK_P (t))
8088           {
8089             /* If there is a local specialization that isn't a
8090                parameter pack, it means that we're doing a "simple"
8091                substitution from inside tsubst_pack_expansion. Just
8092                return the local specialization (which will be a single
8093                parm).  */
8094             tree spec = NULL_TREE;
8095             if (local_specializations)
8096               spec = retrieve_local_specialization (t);
8097             if (spec 
8098                 && TREE_CODE (spec) == PARM_DECL
8099                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8100               return spec;
8101
8102             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8103                the parameters in this function parameter pack.  */
8104             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8105                                                     complain, in_decl);
8106             if (TREE_CODE (expanded_types) == TREE_VEC)
8107               {
8108                 len = TREE_VEC_LENGTH (expanded_types);
8109
8110                 /* Zero-length parameter packs are boring. Just substitute
8111                    into the chain.  */
8112                 if (len == 0)
8113                   return tsubst (TREE_CHAIN (t), args, complain, 
8114                                  TREE_CHAIN (t));
8115               }
8116             else
8117               {
8118                 /* All we did was update the type. Make a note of that.  */
8119                 type = expanded_types;
8120                 expanded_types = NULL_TREE;
8121               }
8122           }
8123
8124         /* Loop through all of the parameter's we'll build. When T is
8125            a function parameter pack, LEN is the number of expanded
8126            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8127         r = NULL_TREE;
8128         for (i = 0; i < len; ++i)
8129           {
8130             prev_r = r;
8131             r = copy_node (t);
8132             if (DECL_TEMPLATE_PARM_P (t))
8133               SET_DECL_TEMPLATE_PARM_P (r);
8134
8135             if (expanded_types)
8136               /* We're on the Ith parameter of the function parameter
8137                  pack.  */
8138               {
8139                 /* Get the Ith type.  */
8140                 type = TREE_VEC_ELT (expanded_types, i);
8141
8142                 if (DECL_NAME (r))
8143                   /* Rename the parameter to include the index.  */
8144                   DECL_NAME (r) =
8145                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8146               }
8147             else if (!type)
8148               /* We're dealing with a normal parameter.  */
8149               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8150
8151             type = type_decays_to (type);
8152             TREE_TYPE (r) = type;
8153             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8154
8155             if (DECL_INITIAL (r))
8156               {
8157                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8158                   DECL_INITIAL (r) = TREE_TYPE (r);
8159                 else
8160                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8161                                              complain, in_decl);
8162               }
8163
8164             DECL_CONTEXT (r) = NULL_TREE;
8165
8166             if (!DECL_TEMPLATE_PARM_P (r))
8167               DECL_ARG_TYPE (r) = type_passed_as (type);
8168
8169             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8170                                             args, complain, in_decl);
8171
8172             /* Keep track of the first new parameter we
8173                generate. That's what will be returned to the
8174                caller.  */
8175             if (!first_r)
8176               first_r = r;
8177
8178             /* Build a proper chain of parameters when substituting
8179                into a function parameter pack.  */
8180             if (prev_r)
8181               TREE_CHAIN (prev_r) = r;
8182           }
8183
8184         if (TREE_CHAIN (t))
8185           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8186                                    complain, TREE_CHAIN (t));
8187
8188         /* FIRST_R contains the start of the chain we've built.  */
8189         r = first_r;
8190       }
8191       break;
8192
8193     case FIELD_DECL:
8194       {
8195         tree type;
8196
8197         r = copy_decl (t);
8198         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8199         if (type == error_mark_node)
8200           return error_mark_node;
8201         TREE_TYPE (r) = type;
8202         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8203
8204         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8205         DECL_INITIAL (r)
8206           = tsubst_expr (DECL_INITIAL (t), args,
8207                          complain, in_decl,
8208                          /*integral_constant_expression_p=*/true);
8209         /* We don't have to set DECL_CONTEXT here; it is set by
8210            finish_member_declaration.  */
8211         TREE_CHAIN (r) = NULL_TREE;
8212         if (VOID_TYPE_P (type))
8213           error ("instantiation of %q+D as type %qT", r, type);
8214
8215         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8216                                         args, complain, in_decl);
8217       }
8218       break;
8219
8220     case USING_DECL:
8221       /* We reach here only for member using decls.  */
8222       if (DECL_DEPENDENT_P (t))
8223         {
8224           r = do_class_using_decl
8225             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8226              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8227           if (!r)
8228             r = error_mark_node;
8229         }
8230       else
8231         {
8232           r = copy_node (t);
8233           TREE_CHAIN (r) = NULL_TREE;
8234         }
8235       break;
8236
8237     case TYPE_DECL:
8238     case VAR_DECL:
8239       {
8240         tree argvec = NULL_TREE;
8241         tree gen_tmpl = NULL_TREE;
8242         tree spec;
8243         tree tmpl = NULL_TREE;
8244         tree ctx;
8245         tree type = NULL_TREE;
8246         bool local_p;
8247
8248         if (TREE_CODE (t) == TYPE_DECL
8249             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8250           {
8251             /* If this is the canonical decl, we don't have to
8252                mess with instantiations, and often we can't (for
8253                typename, template type parms and such).  Note that
8254                TYPE_NAME is not correct for the above test if
8255                we've copied the type for a typedef.  */
8256             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8257             if (type == error_mark_node)
8258               return error_mark_node;
8259             r = TYPE_NAME (type);
8260             break;
8261           }
8262
8263         /* Check to see if we already have the specialization we
8264            need.  */
8265         spec = NULL_TREE;
8266         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8267           {
8268             /* T is a static data member or namespace-scope entity.
8269                We have to substitute into namespace-scope variables
8270                (even though such entities are never templates) because
8271                of cases like:
8272                
8273                  template <class T> void f() { extern T t; }
8274
8275                where the entity referenced is not known until
8276                instantiation time.  */
8277             local_p = false;
8278             ctx = DECL_CONTEXT (t);
8279             if (DECL_CLASS_SCOPE_P (t))
8280               {
8281                 ctx = tsubst_aggr_type (ctx, args,
8282                                         complain,
8283                                         in_decl, /*entering_scope=*/1);
8284                 /* If CTX is unchanged, then T is in fact the
8285                    specialization we want.  That situation occurs when
8286                    referencing a static data member within in its own
8287                    class.  We can use pointer equality, rather than
8288                    same_type_p, because DECL_CONTEXT is always
8289                    canonical.  */
8290                 if (ctx == DECL_CONTEXT (t))
8291                   spec = t;
8292               }
8293
8294             if (!spec)
8295               {
8296                 tmpl = DECL_TI_TEMPLATE (t);
8297                 gen_tmpl = most_general_template (tmpl);
8298                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8299                 spec = (retrieve_specialization 
8300                         (gen_tmpl, argvec,
8301                          /*class_specializations_p=*/false));
8302               }
8303           }
8304         else
8305           {
8306             /* A local variable.  */
8307             local_p = true;
8308             /* Subsequent calls to pushdecl will fill this in.  */
8309             ctx = NULL_TREE;
8310             spec = retrieve_local_specialization (t);
8311           }
8312         /* If we already have the specialization we need, there is
8313            nothing more to do.  */ 
8314         if (spec)
8315           {
8316             r = spec;
8317             break;
8318           }
8319
8320         /* Create a new node for the specialization we need.  */
8321         r = copy_decl (t);
8322         if (type == NULL_TREE)
8323           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8324         if (TREE_CODE (r) == VAR_DECL)
8325           {
8326             /* Even if the original location is out of scope, the
8327                newly substituted one is not.  */
8328             DECL_DEAD_FOR_LOCAL (r) = 0;
8329             DECL_INITIALIZED_P (r) = 0;
8330             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8331             if (type == error_mark_node)
8332               return error_mark_node;
8333             if (TREE_CODE (type) == FUNCTION_TYPE)
8334               {
8335                 /* It may seem that this case cannot occur, since:
8336
8337                      typedef void f();
8338                      void g() { f x; }
8339
8340                    declares a function, not a variable.  However:
8341       
8342                      typedef void f();
8343                      template <typename T> void g() { T t; }
8344                      template void g<f>();
8345
8346                    is an attempt to declare a variable with function
8347                    type.  */
8348                 error ("variable %qD has function type",
8349                        /* R is not yet sufficiently initialized, so we
8350                           just use its name.  */
8351                        DECL_NAME (r));
8352                 return error_mark_node;
8353               }
8354             type = complete_type (type);
8355             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8356               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8357             type = check_var_type (DECL_NAME (r), type);
8358
8359             if (DECL_HAS_VALUE_EXPR_P (t))
8360               {
8361                 tree ve = DECL_VALUE_EXPR (t);
8362                 ve = tsubst_expr (ve, args, complain, in_decl,
8363                                   /*constant_expression_p=*/false);
8364                 SET_DECL_VALUE_EXPR (r, ve);
8365               }
8366           }
8367         else if (DECL_SELF_REFERENCE_P (t))
8368           SET_DECL_SELF_REFERENCE_P (r);
8369         TREE_TYPE (r) = type;
8370         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8371         DECL_CONTEXT (r) = ctx;
8372         /* Clear out the mangled name and RTL for the instantiation.  */
8373         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8374         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8375           SET_DECL_RTL (r, NULL_RTX);
8376         /* The initializer must not be expanded until it is required;
8377            see [temp.inst].  */
8378         DECL_INITIAL (r) = NULL_TREE;
8379         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8380           SET_DECL_RTL (r, NULL_RTX);
8381         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8382         if (TREE_CODE (r) == VAR_DECL)
8383           {
8384             /* Possibly limit visibility based on template args.  */
8385             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8386             if (DECL_VISIBILITY_SPECIFIED (t))
8387               {
8388                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8389                 DECL_ATTRIBUTES (r)
8390                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8391               }
8392             determine_visibility (r);
8393           }
8394         /* Preserve a typedef that names a type.  */
8395         else if (TREE_CODE (r) == TYPE_DECL
8396                  && DECL_ORIGINAL_TYPE (t)
8397                  && type != error_mark_node)
8398           {
8399             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8400                                              args, complain, in_decl);
8401             TREE_TYPE (r) = type = build_variant_type_copy (type);
8402             TYPE_NAME (type) = r;
8403           }
8404
8405         if (!local_p)
8406           {
8407             /* A static data member declaration is always marked
8408                external when it is declared in-class, even if an
8409                initializer is present.  We mimic the non-template
8410                processing here.  */
8411             DECL_EXTERNAL (r) = 1;
8412
8413             register_specialization (r, gen_tmpl, argvec, false);
8414             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8415             SET_DECL_IMPLICIT_INSTANTIATION (r);
8416           }
8417         else
8418           register_local_specialization (r, t);
8419
8420         TREE_CHAIN (r) = NULL_TREE;
8421
8422         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
8423                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
8424                                         args, complain, in_decl);
8425         layout_decl (r, 0);
8426       }
8427       break;
8428
8429     default:
8430       gcc_unreachable ();
8431     }
8432
8433   /* Restore the file and line information.  */
8434   input_location = saved_loc;
8435
8436   return r;
8437 }
8438
8439 /* Substitute into the ARG_TYPES of a function type.  */
8440
8441 static tree
8442 tsubst_arg_types (tree arg_types,
8443                   tree args,
8444                   tsubst_flags_t complain,
8445                   tree in_decl)
8446 {
8447   tree remaining_arg_types;
8448   tree type = NULL_TREE;
8449   int i = 1;
8450   tree expanded_args = NULL_TREE;
8451   tree default_arg;
8452
8453   if (!arg_types || arg_types == void_list_node)
8454     return arg_types;
8455
8456   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8457                                           args, complain, in_decl);
8458   if (remaining_arg_types == error_mark_node)
8459     return error_mark_node;
8460
8461   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8462     {
8463       /* For a pack expansion, perform substitution on the
8464          entire expression. Later on, we'll handle the arguments
8465          one-by-one.  */
8466       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8467                                             args, complain, in_decl);
8468
8469       if (TREE_CODE (expanded_args) == TREE_VEC)
8470         /* So that we'll spin through the parameters, one by one.  */
8471         i = TREE_VEC_LENGTH (expanded_args);
8472       else
8473         {
8474           /* We only partially substituted into the parameter
8475              pack. Our type is TYPE_PACK_EXPANSION.  */
8476           type = expanded_args;
8477           expanded_args = NULL_TREE;
8478         }
8479     }
8480
8481   while (i > 0) {
8482     --i;
8483     
8484     if (expanded_args)
8485       type = TREE_VEC_ELT (expanded_args, i);
8486     else if (!type)
8487       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8488
8489     if (type == error_mark_node)
8490       return error_mark_node;
8491     if (VOID_TYPE_P (type))
8492       {
8493         if (complain & tf_error)
8494           {
8495             error ("invalid parameter type %qT", type);
8496             if (in_decl)
8497               error ("in declaration %q+D", in_decl);
8498           }
8499         return error_mark_node;
8500     }
8501     
8502     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8503        top-level qualifiers as required.  */
8504     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8505
8506     /* We do not substitute into default arguments here.  The standard
8507        mandates that they be instantiated only when needed, which is
8508        done in build_over_call.  */
8509     default_arg = TREE_PURPOSE (arg_types);
8510
8511     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8512       {
8513         /* We've instantiated a template before its default arguments
8514            have been parsed.  This can happen for a nested template
8515            class, and is not an error unless we require the default
8516            argument in a call of this function.  */
8517         remaining_arg_types = 
8518           tree_cons (default_arg, type, remaining_arg_types);
8519         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8520                        remaining_arg_types);
8521       }
8522     else
8523       remaining_arg_types = 
8524         hash_tree_cons (default_arg, type, remaining_arg_types);
8525   }
8526         
8527   return remaining_arg_types;
8528 }
8529
8530 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8531    *not* handle the exception-specification for FNTYPE, because the
8532    initial substitution of explicitly provided template parameters
8533    during argument deduction forbids substitution into the
8534    exception-specification:
8535
8536      [temp.deduct]
8537
8538      All references in the function type of the function template to  the
8539      corresponding template parameters are replaced by the specified tem-
8540      plate argument values.  If a substitution in a template parameter or
8541      in  the function type of the function template results in an invalid
8542      type, type deduction fails.  [Note: The equivalent  substitution  in
8543      exception specifications is done only when the function is instanti-
8544      ated, at which point a program is  ill-formed  if  the  substitution
8545      results in an invalid type.]  */
8546
8547 static tree
8548 tsubst_function_type (tree t,
8549                       tree args,
8550                       tsubst_flags_t complain,
8551                       tree in_decl)
8552 {
8553   tree return_type;
8554   tree arg_types;
8555   tree fntype;
8556
8557   /* The TYPE_CONTEXT is not used for function/method types.  */
8558   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8559
8560   /* Substitute the return type.  */
8561   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8562   if (return_type == error_mark_node)
8563     return error_mark_node;
8564   /* The standard does not presently indicate that creation of a
8565      function type with an invalid return type is a deduction failure.
8566      However, that is clearly analogous to creating an array of "void"
8567      or a reference to a reference.  This is core issue #486.  */
8568   if (TREE_CODE (return_type) == ARRAY_TYPE
8569       || TREE_CODE (return_type) == FUNCTION_TYPE)
8570     {
8571       if (complain & tf_error)
8572         {
8573           if (TREE_CODE (return_type) == ARRAY_TYPE)
8574             error ("function returning an array");
8575           else
8576             error ("function returning a function");
8577         }
8578       return error_mark_node;
8579     }
8580
8581   /* Substitute the argument types.  */
8582   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8583                                 complain, in_decl);
8584   if (arg_types == error_mark_node)
8585     return error_mark_node;
8586
8587   if (TYPE_QUALS (return_type) != TYPE_UNQUALIFIED
8588       && in_decl != NULL_TREE
8589       && !TREE_NO_WARNING (in_decl)
8590       && (SCALAR_TYPE_P (return_type) || VOID_TYPE_P (return_type)))
8591     warning (OPT_Wreturn_type,
8592             "type qualifiers ignored on function return type");
8593
8594   /* Construct a new type node and return it.  */
8595   if (TREE_CODE (t) == FUNCTION_TYPE)
8596     fntype = build_function_type (return_type, arg_types);
8597   else
8598     {
8599       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8600       if (! IS_AGGR_TYPE (r))
8601         {
8602           /* [temp.deduct]
8603
8604              Type deduction may fail for any of the following
8605              reasons:
8606
8607              -- Attempting to create "pointer to member of T" when T
8608              is not a class type.  */
8609           if (complain & tf_error)
8610             error ("creating pointer to member function of non-class type %qT",
8611                       r);
8612           return error_mark_node;
8613         }
8614
8615       fntype = build_method_type_directly (r, return_type,
8616                                            TREE_CHAIN (arg_types));
8617     }
8618   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
8619   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
8620
8621   return fntype;
8622 }
8623
8624 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
8625    ARGS into that specification, and return the substituted
8626    specification.  If there is no specification, return NULL_TREE.  */
8627
8628 static tree
8629 tsubst_exception_specification (tree fntype,
8630                                 tree args,
8631                                 tsubst_flags_t complain,
8632                                 tree in_decl)
8633 {
8634   tree specs;
8635   tree new_specs;
8636
8637   specs = TYPE_RAISES_EXCEPTIONS (fntype);
8638   new_specs = NULL_TREE;
8639   if (specs)
8640     {
8641       if (! TREE_VALUE (specs))
8642         new_specs = specs;
8643       else
8644         while (specs)
8645           {
8646             tree spec;
8647             int i, len = 1;
8648             tree expanded_specs = NULL_TREE;
8649
8650             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
8651               {
8652                 /* Expand the pack expansion type.  */
8653                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
8654                                                        args, complain,
8655                                                        in_decl);
8656                 len = TREE_VEC_LENGTH (expanded_specs);
8657               }
8658
8659             for (i = 0; i < len; ++i)
8660               {
8661                 if (expanded_specs)
8662                   spec = TREE_VEC_ELT (expanded_specs, i);
8663                 else
8664                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
8665                 if (spec == error_mark_node)
8666                   return spec;
8667                 new_specs = add_exception_specifier (new_specs, spec, 
8668                                                      complain);
8669               }
8670
8671             specs = TREE_CHAIN (specs);
8672           }
8673     }
8674   return new_specs;
8675 }
8676
8677 /* Take the tree structure T and replace template parameters used
8678    therein with the argument vector ARGS.  IN_DECL is an associated
8679    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
8680    Issue error and warning messages under control of COMPLAIN.  Note
8681    that we must be relatively non-tolerant of extensions here, in
8682    order to preserve conformance; if we allow substitutions that
8683    should not be allowed, we may allow argument deductions that should
8684    not succeed, and therefore report ambiguous overload situations
8685    where there are none.  In theory, we could allow the substitution,
8686    but indicate that it should have failed, and allow our caller to
8687    make sure that the right thing happens, but we don't try to do this
8688    yet.
8689
8690    This function is used for dealing with types, decls and the like;
8691    for expressions, use tsubst_expr or tsubst_copy.  */
8692
8693 static tree
8694 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8695 {
8696   tree type, r;
8697
8698   if (t == NULL_TREE || t == error_mark_node
8699       || t == integer_type_node
8700       || t == void_type_node
8701       || t == char_type_node
8702       || t == unknown_type_node
8703       || TREE_CODE (t) == NAMESPACE_DECL)
8704     return t;
8705
8706   if (DECL_P (t))
8707     return tsubst_decl (t, args, complain);
8708
8709   if (TREE_CODE (t) == IDENTIFIER_NODE)
8710     type = IDENTIFIER_TYPE_VALUE (t);
8711   else
8712     type = TREE_TYPE (t);
8713
8714   gcc_assert (type != unknown_type_node);
8715
8716   /* Reuse typedefs.  We need to do this to handle dependent attributes,
8717      such as attribute aligned.  */
8718   if (TYPE_P (t)
8719       && TYPE_NAME (t)
8720       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
8721     {
8722       tree decl = TYPE_NAME (t);
8723       
8724       if (DECL_CLASS_SCOPE_P (decl)
8725           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl)))
8726         {
8727           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
8728           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
8729           r = retrieve_specialization (tmpl, gen_args, false);
8730         }
8731       else if (DECL_FUNCTION_SCOPE_P (decl))
8732         r = retrieve_local_specialization (decl);
8733       else
8734         r = NULL_TREE;
8735         
8736       if (r)
8737         {
8738           r = TREE_TYPE (r);
8739           r = cp_build_qualified_type_real
8740             (r, cp_type_quals (t) | cp_type_quals (r),
8741              complain | tf_ignore_bad_quals);
8742           return r;
8743         }
8744       /* Else we must be instantiating the typedef, so fall through.  */
8745     }
8746
8747   if (type
8748       && TREE_CODE (t) != TYPENAME_TYPE
8749       && TREE_CODE (t) != IDENTIFIER_NODE
8750       && TREE_CODE (t) != FUNCTION_TYPE
8751       && TREE_CODE (t) != METHOD_TYPE)
8752     type = tsubst (type, args, complain, in_decl);
8753   if (type == error_mark_node)
8754     return error_mark_node;
8755
8756   switch (TREE_CODE (t))
8757     {
8758     case RECORD_TYPE:
8759     case UNION_TYPE:
8760     case ENUMERAL_TYPE:
8761       return tsubst_aggr_type (t, args, complain, in_decl,
8762                                /*entering_scope=*/0);
8763
8764     case ERROR_MARK:
8765     case IDENTIFIER_NODE:
8766     case VOID_TYPE:
8767     case REAL_TYPE:
8768     case COMPLEX_TYPE:
8769     case VECTOR_TYPE:
8770     case BOOLEAN_TYPE:
8771     case INTEGER_CST:
8772     case REAL_CST:
8773     case STRING_CST:
8774       return t;
8775
8776     case INTEGER_TYPE:
8777       if (t == integer_type_node)
8778         return t;
8779
8780       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
8781           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
8782         return t;
8783
8784       {
8785         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
8786
8787         max = tsubst_expr (omax, args, complain, in_decl,
8788                            /*integral_constant_expression_p=*/false);
8789         max = fold_decl_constant_value (max);
8790
8791         if (TREE_CODE (max) != INTEGER_CST 
8792             && TREE_CODE (max) != TEMPLATE_PARM_INDEX
8793             && !at_function_scope_p ())
8794           {
8795             if (complain & tf_error)
8796               error ("array bound is not an integer constant");
8797             return error_mark_node;
8798           }
8799
8800         /* [temp.deduct]
8801
8802            Type deduction may fail for any of the following
8803            reasons:
8804
8805              Attempting to create an array with a size that is
8806              zero or negative.  */
8807         if (integer_zerop (max) && !(complain & tf_error))
8808           /* We must fail if performing argument deduction (as
8809              indicated by the state of complain), so that
8810              another substitution can be found.  */
8811           return error_mark_node;
8812         else if (TREE_CODE (max) == INTEGER_CST
8813                  && INT_CST_LT (max, integer_zero_node))
8814           {
8815             if (complain & tf_error)
8816               error ("creating array with negative size (%qE)", max);
8817
8818             return error_mark_node;
8819           }
8820
8821         return compute_array_index_type (NULL_TREE, max);
8822       }
8823
8824     case TEMPLATE_TYPE_PARM:
8825     case TEMPLATE_TEMPLATE_PARM:
8826     case BOUND_TEMPLATE_TEMPLATE_PARM:
8827     case TEMPLATE_PARM_INDEX:
8828       {
8829         int idx;
8830         int level;
8831         int levels;
8832         tree arg = NULL_TREE;
8833
8834         r = NULL_TREE;
8835
8836         gcc_assert (TREE_VEC_LENGTH (args) > 0);
8837         template_parm_level_and_index (t, &level, &idx); 
8838
8839         levels = TMPL_ARGS_DEPTH (args);
8840         if (level <= levels)
8841           {
8842             arg = TMPL_ARG (args, level, idx);
8843
8844             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
8845               /* See through ARGUMENT_PACK_SELECT arguments. */
8846               arg = ARGUMENT_PACK_SELECT_ARG (arg);
8847           }
8848
8849         if (arg == error_mark_node)
8850           return error_mark_node;
8851         else if (arg != NULL_TREE)
8852           {
8853             if (ARGUMENT_PACK_P (arg))
8854               /* If ARG is an argument pack, we don't actually want to
8855                  perform a substitution here, because substitutions
8856                  for argument packs are only done
8857                  element-by-element. We can get to this point when
8858                  substituting the type of a non-type template
8859                  parameter pack, when that type actually contains
8860                  template parameter packs from an outer template, e.g.,
8861
8862                  template<typename... Types> struct A {
8863                    template<Types... Values> struct B { };
8864                  };  */
8865               return t;
8866
8867             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
8868               {
8869                 int quals;
8870                 gcc_assert (TYPE_P (arg));
8871
8872                 /* cv-quals from the template are discarded when
8873                    substituting in a function or reference type.  */
8874                 if (TREE_CODE (arg) == FUNCTION_TYPE
8875                     || TREE_CODE (arg) == METHOD_TYPE
8876                     || TREE_CODE (arg) == REFERENCE_TYPE)
8877                   quals = cp_type_quals (arg);
8878                 else
8879                   quals = cp_type_quals (arg) | cp_type_quals (t);
8880                   
8881                 return cp_build_qualified_type_real
8882                   (arg, quals, complain | tf_ignore_bad_quals);
8883               }
8884             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
8885               {
8886                 /* We are processing a type constructed from a
8887                    template template parameter.  */
8888                 tree argvec = tsubst (TYPE_TI_ARGS (t),
8889                                       args, complain, in_decl);
8890                 if (argvec == error_mark_node)
8891                   return error_mark_node;
8892
8893                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
8894                    are resolving nested-types in the signature of a
8895                    member function templates.  Otherwise ARG is a
8896                    TEMPLATE_DECL and is the real template to be
8897                    instantiated.  */
8898                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
8899                   arg = TYPE_NAME (arg);
8900
8901                 r = lookup_template_class (arg,
8902                                            argvec, in_decl,
8903                                            DECL_CONTEXT (arg),
8904                                             /*entering_scope=*/0,
8905                                            complain);
8906                 return cp_build_qualified_type_real
8907                   (r, TYPE_QUALS (t), complain);
8908               }
8909             else
8910               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
8911               return arg;
8912           }
8913
8914         if (level == 1)
8915           /* This can happen during the attempted tsubst'ing in
8916              unify.  This means that we don't yet have any information
8917              about the template parameter in question.  */
8918           return t;
8919
8920         /* If we get here, we must have been looking at a parm for a
8921            more deeply nested template.  Make a new version of this
8922            template parameter, but with a lower level.  */
8923         switch (TREE_CODE (t))
8924           {
8925           case TEMPLATE_TYPE_PARM:
8926           case TEMPLATE_TEMPLATE_PARM:
8927           case BOUND_TEMPLATE_TEMPLATE_PARM:
8928             if (cp_type_quals (t))
8929               {
8930                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
8931                 r = cp_build_qualified_type_real
8932                   (r, cp_type_quals (t),
8933                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
8934                                ? tf_ignore_bad_quals : 0));
8935               }
8936             else
8937               {
8938                 r = copy_type (t);
8939                 TEMPLATE_TYPE_PARM_INDEX (r)
8940                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
8941                                                 r, levels, args, complain);
8942                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
8943                 TYPE_MAIN_VARIANT (r) = r;
8944                 TYPE_POINTER_TO (r) = NULL_TREE;
8945                 TYPE_REFERENCE_TO (r) = NULL_TREE;
8946
8947                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
8948                   /* We have reduced the level of the template
8949                      template parameter, but not the levels of its
8950                      template parameters, so canonical_type_parameter
8951                      will not be able to find the canonical template
8952                      template parameter for this level. Thus, we
8953                      require structural equality checking to compare
8954                      TEMPLATE_TEMPLATE_PARMs. */
8955                   SET_TYPE_STRUCTURAL_EQUALITY (r);
8956                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
8957                   SET_TYPE_STRUCTURAL_EQUALITY (r);
8958                 else
8959                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
8960
8961                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
8962                   {
8963                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
8964                                           complain, in_decl);
8965                     if (argvec == error_mark_node)
8966                       return error_mark_node;
8967
8968                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
8969                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
8970                   }
8971               }
8972             break;
8973
8974           case TEMPLATE_PARM_INDEX:
8975             r = reduce_template_parm_level (t, type, levels, args, complain);
8976             break;
8977
8978           default:
8979             gcc_unreachable ();
8980           }
8981
8982         return r;
8983       }
8984
8985     case TREE_LIST:
8986       {
8987         tree purpose, value, chain;
8988
8989         if (t == void_list_node)
8990           return t;
8991
8992         purpose = TREE_PURPOSE (t);
8993         if (purpose)
8994           {
8995             purpose = tsubst (purpose, args, complain, in_decl);
8996             if (purpose == error_mark_node)
8997               return error_mark_node;
8998           }
8999         value = TREE_VALUE (t);
9000         if (value)
9001           {
9002             value = tsubst (value, args, complain, in_decl);
9003             if (value == error_mark_node)
9004               return error_mark_node;
9005           }
9006         chain = TREE_CHAIN (t);
9007         if (chain && chain != void_type_node)
9008           {
9009             chain = tsubst (chain, args, complain, in_decl);
9010             if (chain == error_mark_node)
9011               return error_mark_node;
9012           }
9013         if (purpose == TREE_PURPOSE (t)
9014             && value == TREE_VALUE (t)
9015             && chain == TREE_CHAIN (t))
9016           return t;
9017         return hash_tree_cons (purpose, value, chain);
9018       }
9019
9020     case TREE_BINFO:
9021       /* We should never be tsubsting a binfo.  */
9022       gcc_unreachable ();
9023
9024     case TREE_VEC:
9025       /* A vector of template arguments.  */
9026       gcc_assert (!type);
9027       return tsubst_template_args (t, args, complain, in_decl);
9028
9029     case POINTER_TYPE:
9030     case REFERENCE_TYPE:
9031       {
9032         enum tree_code code;
9033
9034         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9035           return t;
9036
9037         code = TREE_CODE (t);
9038
9039
9040         /* [temp.deduct]
9041
9042            Type deduction may fail for any of the following
9043            reasons:
9044
9045            -- Attempting to create a pointer to reference type.
9046            -- Attempting to create a reference to a reference type or
9047               a reference to void.
9048
9049           Core issue 106 says that creating a reference to a reference
9050           during instantiation is no longer a cause for failure. We
9051           only enforce this check in strict C++98 mode.  */
9052         if ((TREE_CODE (type) == REFERENCE_TYPE
9053              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9054             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9055           {
9056             static location_t last_loc;
9057
9058             /* We keep track of the last time we issued this error
9059                message to avoid spewing a ton of messages during a
9060                single bad template instantiation.  */
9061             if (complain & tf_error
9062 #ifdef USE_MAPPED_LOCATION
9063                 && last_loc != input_location
9064 #else
9065                 && (last_loc.line != input_line
9066                     || last_loc.file != input_filename)
9067 #endif
9068                   )
9069               {
9070                 if (TREE_CODE (type) == VOID_TYPE)
9071                   error ("forming reference to void");
9072                 else
9073                   error ("forming %s to reference type %qT",
9074                          (code == POINTER_TYPE) ? "pointer" : "reference",
9075                          type);
9076                 last_loc = input_location;
9077               }
9078
9079             return error_mark_node;
9080           }
9081         else if (code == POINTER_TYPE)
9082           {
9083             r = build_pointer_type (type);
9084             if (TREE_CODE (type) == METHOD_TYPE)
9085               r = build_ptrmemfunc_type (r);
9086           }
9087         else if (TREE_CODE (type) == REFERENCE_TYPE)
9088           /* In C++0x, during template argument substitution, when there is an
9089              attempt to create a reference to a reference type, reference
9090              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9091
9092              "If a template-argument for a template-parameter T names a type
9093              that is a reference to a type A, an attempt to create the type
9094              'lvalue reference to cv T' creates the type 'lvalue reference to
9095              A,' while an attempt to create the type type rvalue reference to
9096              cv T' creates the type T"
9097           */
9098           r = cp_build_reference_type
9099               (TREE_TYPE (type),
9100                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9101         else
9102           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9103         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9104
9105         if (r != error_mark_node)
9106           /* Will this ever be needed for TYPE_..._TO values?  */
9107           layout_type (r);
9108
9109         return r;
9110       }
9111     case OFFSET_TYPE:
9112       {
9113         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9114         if (r == error_mark_node || !IS_AGGR_TYPE (r))
9115           {
9116             /* [temp.deduct]
9117
9118                Type deduction may fail for any of the following
9119                reasons:
9120
9121                -- Attempting to create "pointer to member of T" when T
9122                   is not a class type.  */
9123             if (complain & tf_error)
9124               error ("creating pointer to member of non-class type %qT", r);
9125             return error_mark_node;
9126           }
9127         if (TREE_CODE (type) == REFERENCE_TYPE)
9128           {
9129             if (complain & tf_error)
9130               error ("creating pointer to member reference type %qT", type);
9131             return error_mark_node;
9132           }
9133         if (TREE_CODE (type) == VOID_TYPE)
9134           {
9135             if (complain & tf_error)
9136               error ("creating pointer to member of type void");
9137             return error_mark_node;
9138           }
9139         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9140         if (TREE_CODE (type) == FUNCTION_TYPE)
9141           {
9142             /* The type of the implicit object parameter gets its
9143                cv-qualifiers from the FUNCTION_TYPE. */
9144             tree method_type;
9145             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9146                                                       cp_type_quals (type));
9147             tree memptr;
9148             method_type = build_method_type_directly (this_type,
9149                                                       TREE_TYPE (type),
9150                                                       TYPE_ARG_TYPES (type));
9151             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9152             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9153                                                  complain);
9154           }
9155         else
9156           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9157                                                TYPE_QUALS (t),
9158                                                complain);
9159       }
9160     case FUNCTION_TYPE:
9161     case METHOD_TYPE:
9162       {
9163         tree fntype;
9164         tree specs;
9165         fntype = tsubst_function_type (t, args, complain, in_decl);
9166         if (fntype == error_mark_node)
9167           return error_mark_node;
9168
9169         /* Substitute the exception specification.  */
9170         specs = tsubst_exception_specification (t, args, complain,
9171                                                 in_decl);
9172         if (specs == error_mark_node)
9173           return error_mark_node;
9174         if (specs)
9175           fntype = build_exception_variant (fntype, specs);
9176         return fntype;
9177       }
9178     case ARRAY_TYPE:
9179       {
9180         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9181         if (domain == error_mark_node)
9182           return error_mark_node;
9183
9184         /* As an optimization, we avoid regenerating the array type if
9185            it will obviously be the same as T.  */
9186         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9187           return t;
9188
9189         /* These checks should match the ones in grokdeclarator.
9190
9191            [temp.deduct]
9192
9193            The deduction may fail for any of the following reasons:
9194
9195            -- Attempting to create an array with an element type that
9196               is void, a function type, or a reference type, or [DR337]
9197               an abstract class type.  */
9198         if (TREE_CODE (type) == VOID_TYPE
9199             || TREE_CODE (type) == FUNCTION_TYPE
9200             || TREE_CODE (type) == REFERENCE_TYPE)
9201           {
9202             if (complain & tf_error)
9203               error ("creating array of %qT", type);
9204             return error_mark_node;
9205           }
9206         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9207           {
9208             if (complain & tf_error)
9209               error ("creating array of %qT, which is an abstract class type",
9210                      type);
9211             return error_mark_node;
9212           }
9213
9214         r = build_cplus_array_type (type, domain);
9215
9216         if (TYPE_USER_ALIGN (t))
9217           {
9218             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9219             TYPE_USER_ALIGN (r) = 1;
9220           }
9221
9222         return r;
9223       }
9224
9225     case PLUS_EXPR:
9226     case MINUS_EXPR:
9227       {
9228         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9229         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9230
9231         if (e1 == error_mark_node || e2 == error_mark_node)
9232           return error_mark_node;
9233
9234         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9235       }
9236
9237     case NEGATE_EXPR:
9238     case NOP_EXPR:
9239       {
9240         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9241         if (e == error_mark_node)
9242           return error_mark_node;
9243
9244         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9245       }
9246
9247     case TYPENAME_TYPE:
9248       {
9249         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9250                                      in_decl, /*entering_scope=*/1);
9251         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9252                               complain, in_decl);
9253
9254         if (ctx == error_mark_node || f == error_mark_node)
9255           return error_mark_node;
9256
9257         if (!IS_AGGR_TYPE (ctx))
9258           {
9259             if (complain & tf_error)
9260               error ("%qT is not a class, struct, or union type", ctx);
9261             return error_mark_node;
9262           }
9263         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9264           {
9265             /* Normally, make_typename_type does not require that the CTX
9266                have complete type in order to allow things like:
9267
9268                  template <class T> struct S { typename S<T>::X Y; };
9269
9270                But, such constructs have already been resolved by this
9271                point, so here CTX really should have complete type, unless
9272                it's a partial instantiation.  */
9273             ctx = complete_type (ctx);
9274             if (!COMPLETE_TYPE_P (ctx))
9275               {
9276                 if (complain & tf_error)
9277                   cxx_incomplete_type_error (NULL_TREE, ctx);
9278                 return error_mark_node;
9279               }
9280           }
9281
9282         f = make_typename_type (ctx, f, typename_type,
9283                                 (complain & tf_error) | tf_keep_type_decl);
9284         if (f == error_mark_node)
9285           return f;
9286         if (TREE_CODE (f) == TYPE_DECL)
9287           {
9288             complain |= tf_ignore_bad_quals;
9289             f = TREE_TYPE (f);
9290           }
9291
9292         if (TREE_CODE (f) != TYPENAME_TYPE)
9293           {
9294             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9295               error ("%qT resolves to %qT, which is not an enumeration type",
9296                      t, f);
9297             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9298               error ("%qT resolves to %qT, which is is not a class type",
9299                      t, f);
9300           }
9301
9302         return cp_build_qualified_type_real
9303           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9304       }
9305
9306     case UNBOUND_CLASS_TEMPLATE:
9307       {
9308         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9309                                      in_decl, /*entering_scope=*/1);
9310         tree name = TYPE_IDENTIFIER (t);
9311         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9312
9313         if (ctx == error_mark_node || name == error_mark_node)
9314           return error_mark_node;
9315
9316         if (parm_list)
9317           parm_list = tsubst_template_parms (parm_list, args, complain);
9318         return make_unbound_class_template (ctx, name, parm_list, complain);
9319       }
9320
9321     case INDIRECT_REF:
9322     case ADDR_EXPR:
9323     case CALL_EXPR:
9324       gcc_unreachable ();
9325
9326     case ARRAY_REF:
9327       {
9328         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9329         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9330                                /*integral_constant_expression_p=*/false);
9331         if (e1 == error_mark_node || e2 == error_mark_node)
9332           return error_mark_node;
9333
9334         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9335       }
9336
9337     case SCOPE_REF:
9338       {
9339         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9340         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9341         if (e1 == error_mark_node || e2 == error_mark_node)
9342           return error_mark_node;
9343
9344         return build_qualified_name (/*type=*/NULL_TREE,
9345                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9346       }
9347
9348     case TYPEOF_TYPE:
9349       {
9350         tree type;
9351
9352         type = finish_typeof (tsubst_expr 
9353                               (TYPEOF_TYPE_EXPR (t), args,
9354                                complain, in_decl,
9355                                /*integral_constant_expression_p=*/false));
9356         return cp_build_qualified_type_real (type,
9357                                              cp_type_quals (t)
9358                                              | cp_type_quals (type),
9359                                              complain);
9360       }
9361
9362     case DECLTYPE_TYPE:
9363       {
9364         tree type;
9365
9366         type = 
9367           finish_decltype_type (tsubst_expr 
9368                                 (DECLTYPE_TYPE_EXPR (t), args,
9369                                  complain, in_decl,
9370                                  /*integral_constant_expression_p=*/false),
9371                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9372         return cp_build_qualified_type_real (type,
9373                                              cp_type_quals (t)
9374                                              | cp_type_quals (type),
9375                                              complain);
9376       }
9377
9378     case TYPE_ARGUMENT_PACK:
9379     case NONTYPE_ARGUMENT_PACK:
9380       {
9381         tree r = make_node (TREE_CODE (t));
9382         tree packed_out = 
9383           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9384                                 args,
9385                                 complain,
9386                                 in_decl);
9387         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9388
9389         /* For template nontype argument packs, also substitute into
9390            the type.  */
9391         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9392           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9393
9394         return r;
9395       }
9396       break;
9397
9398     default:
9399       sorry ("use of %qs in template",
9400              tree_code_name [(int) TREE_CODE (t)]);
9401       return error_mark_node;
9402     }
9403 }
9404
9405 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9406    type of the expression on the left-hand side of the "." or "->"
9407    operator.  */
9408
9409 static tree
9410 tsubst_baselink (tree baselink, tree object_type,
9411                  tree args, tsubst_flags_t complain, tree in_decl)
9412 {
9413     tree name;
9414     tree qualifying_scope;
9415     tree fns;
9416     tree optype;
9417     tree template_args = 0;
9418     bool template_id_p = false;
9419
9420     /* A baselink indicates a function from a base class.  Both the
9421        BASELINK_ACCESS_BINFO and the base class referenced may
9422        indicate bases of the template class, rather than the
9423        instantiated class.  In addition, lookups that were not
9424        ambiguous before may be ambiguous now.  Therefore, we perform
9425        the lookup again.  */
9426     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9427     qualifying_scope = tsubst (qualifying_scope, args,
9428                                complain, in_decl);
9429     fns = BASELINK_FUNCTIONS (baselink);
9430     optype = BASELINK_OPTYPE (baselink);
9431     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9432       {
9433         template_id_p = true;
9434         template_args = TREE_OPERAND (fns, 1);
9435         fns = TREE_OPERAND (fns, 0);
9436         if (template_args)
9437           template_args = tsubst_template_args (template_args, args,
9438                                                 complain, in_decl);
9439       }
9440     name = DECL_NAME (get_first_fn (fns));
9441     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9442
9443     /* If lookup found a single function, mark it as used at this
9444        point.  (If it lookup found multiple functions the one selected
9445        later by overload resolution will be marked as used at that
9446        point.)  */
9447     if (BASELINK_P (baselink))
9448       fns = BASELINK_FUNCTIONS (baselink);
9449     if (!template_id_p && !really_overloaded_fn (fns))
9450       mark_used (OVL_CURRENT (fns));
9451
9452     /* Add back the template arguments, if present.  */
9453     if (BASELINK_P (baselink) && template_id_p)
9454       BASELINK_FUNCTIONS (baselink)
9455         = build_nt (TEMPLATE_ID_EXPR,
9456                     BASELINK_FUNCTIONS (baselink),
9457                     template_args);
9458     /* Update the conversion operator type.  */
9459     BASELINK_OPTYPE (baselink) 
9460       = tsubst (optype, args, complain, in_decl);
9461
9462     if (!object_type)
9463       object_type = current_class_type;
9464     return adjust_result_of_qualified_name_lookup (baselink,
9465                                                    qualifying_scope,
9466                                                    object_type);
9467 }
9468
9469 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9470    true if the qualified-id will be a postfix-expression in-and-of
9471    itself; false if more of the postfix-expression follows the
9472    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9473    of "&".  */
9474
9475 static tree
9476 tsubst_qualified_id (tree qualified_id, tree args,
9477                      tsubst_flags_t complain, tree in_decl,
9478                      bool done, bool address_p)
9479 {
9480   tree expr;
9481   tree scope;
9482   tree name;
9483   bool is_template;
9484   tree template_args;
9485
9486   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9487
9488   /* Figure out what name to look up.  */
9489   name = TREE_OPERAND (qualified_id, 1);
9490   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9491     {
9492       is_template = true;
9493       template_args = TREE_OPERAND (name, 1);
9494       if (template_args)
9495         template_args = tsubst_template_args (template_args, args,
9496                                               complain, in_decl);
9497       name = TREE_OPERAND (name, 0);
9498     }
9499   else
9500     {
9501       is_template = false;
9502       template_args = NULL_TREE;
9503     }
9504
9505   /* Substitute into the qualifying scope.  When there are no ARGS, we
9506      are just trying to simplify a non-dependent expression.  In that
9507      case the qualifying scope may be dependent, and, in any case,
9508      substituting will not help.  */
9509   scope = TREE_OPERAND (qualified_id, 0);
9510   if (args)
9511     {
9512       scope = tsubst (scope, args, complain, in_decl);
9513       expr = tsubst_copy (name, args, complain, in_decl);
9514     }
9515   else
9516     expr = name;
9517
9518   if (dependent_type_p (scope))
9519     return build_qualified_name (/*type=*/NULL_TREE,
9520                                  scope, expr,
9521                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9522
9523   if (!BASELINK_P (name) && !DECL_P (expr))
9524     {
9525       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9526         /* If this were actually a destructor call, it would have been
9527            parsed as such by the parser.  */
9528         expr = error_mark_node;
9529       else
9530         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9531       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9532                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9533         {
9534           if (complain & tf_error)
9535             {
9536               error ("dependent-name %qE is parsed as a non-type, but "
9537                      "instantiation yields a type", qualified_id);
9538               inform ("say %<typename %E%> if a type is meant", qualified_id);
9539             }
9540           return error_mark_node;
9541         }
9542     }
9543
9544   if (DECL_P (expr))
9545     {
9546       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9547                                            scope);
9548       /* Remember that there was a reference to this entity.  */
9549       mark_used (expr);
9550     }
9551
9552   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9553     {
9554       if (complain & tf_error)
9555         qualified_name_lookup_error (scope,
9556                                      TREE_OPERAND (qualified_id, 1),
9557                                      expr);
9558       return error_mark_node;
9559     }
9560
9561   if (is_template)
9562     expr = lookup_template_function (expr, template_args);
9563
9564   if (expr == error_mark_node && complain & tf_error)
9565     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
9566                                  expr);
9567   else if (TYPE_P (scope))
9568     {
9569       expr = (adjust_result_of_qualified_name_lookup
9570               (expr, scope, current_class_type));
9571       expr = (finish_qualified_id_expr
9572               (scope, expr, done, address_p,
9573                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
9574                /*template_arg_p=*/false));
9575     }
9576
9577   /* Expressions do not generally have reference type.  */
9578   if (TREE_CODE (expr) != SCOPE_REF
9579       /* However, if we're about to form a pointer-to-member, we just
9580          want the referenced member referenced.  */
9581       && TREE_CODE (expr) != OFFSET_REF)
9582     expr = convert_from_reference (expr);
9583
9584   return expr;
9585 }
9586
9587 /* Like tsubst, but deals with expressions.  This function just replaces
9588    template parms; to finish processing the resultant expression, use
9589    tsubst_expr.  */
9590
9591 static tree
9592 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9593 {
9594   enum tree_code code;
9595   tree r;
9596
9597   if (t == NULL_TREE || t == error_mark_node)
9598     return t;
9599
9600   code = TREE_CODE (t);
9601
9602   switch (code)
9603     {
9604     case PARM_DECL:
9605       r = retrieve_local_specialization (t);
9606       gcc_assert (r != NULL);
9607       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
9608         r = ARGUMENT_PACK_SELECT_ARG (r);
9609       mark_used (r);
9610       return r;
9611
9612     case CONST_DECL:
9613       {
9614         tree enum_type;
9615         tree v;
9616
9617         if (DECL_TEMPLATE_PARM_P (t))
9618           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
9619         /* There is no need to substitute into namespace-scope
9620            enumerators.  */
9621         if (DECL_NAMESPACE_SCOPE_P (t))
9622           return t;
9623         /* If ARGS is NULL, then T is known to be non-dependent.  */
9624         if (args == NULL_TREE)
9625           return integral_constant_value (t);
9626
9627         /* Unfortunately, we cannot just call lookup_name here.
9628            Consider:
9629
9630              template <int I> int f() {
9631              enum E { a = I };
9632              struct S { void g() { E e = a; } };
9633              };
9634
9635            When we instantiate f<7>::S::g(), say, lookup_name is not
9636            clever enough to find f<7>::a.  */
9637         enum_type
9638           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
9639                               /*entering_scope=*/0);
9640
9641         for (v = TYPE_VALUES (enum_type);
9642              v != NULL_TREE;
9643              v = TREE_CHAIN (v))
9644           if (TREE_PURPOSE (v) == DECL_NAME (t))
9645             return TREE_VALUE (v);
9646
9647           /* We didn't find the name.  That should never happen; if
9648              name-lookup found it during preliminary parsing, we
9649              should find it again here during instantiation.  */
9650         gcc_unreachable ();
9651       }
9652       return t;
9653
9654     case FIELD_DECL:
9655       if (DECL_CONTEXT (t))
9656         {
9657           tree ctx;
9658
9659           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
9660                                   /*entering_scope=*/1);
9661           if (ctx != DECL_CONTEXT (t))
9662             {
9663               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
9664               if (!r)
9665                 {
9666                   if (complain & tf_error)
9667                     error ("using invalid field %qD", t);
9668                   return error_mark_node;
9669                 }
9670               return r;
9671             }
9672         }
9673
9674       return t;
9675
9676     case VAR_DECL:
9677     case FUNCTION_DECL:
9678       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9679           || local_variable_p (t))
9680         t = tsubst (t, args, complain, in_decl);
9681       mark_used (t);
9682       return t;
9683
9684     case BASELINK:
9685       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
9686
9687     case TEMPLATE_DECL:
9688       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9689         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
9690                        args, complain, in_decl);
9691       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
9692         return tsubst (t, args, complain, in_decl);
9693       else if (DECL_CLASS_SCOPE_P (t)
9694                && uses_template_parms (DECL_CONTEXT (t)))
9695         {
9696           /* Template template argument like the following example need
9697              special treatment:
9698
9699                template <template <class> class TT> struct C {};
9700                template <class T> struct D {
9701                  template <class U> struct E {};
9702                  C<E> c;                                // #1
9703                };
9704                D<int> d;                                // #2
9705
9706              We are processing the template argument `E' in #1 for
9707              the template instantiation #2.  Originally, `E' is a
9708              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
9709              have to substitute this with one having context `D<int>'.  */
9710
9711           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
9712           return lookup_field (context, DECL_NAME(t), 0, false);
9713         }
9714       else
9715         /* Ordinary template template argument.  */
9716         return t;
9717
9718     case CAST_EXPR:
9719     case REINTERPRET_CAST_EXPR:
9720     case CONST_CAST_EXPR:
9721     case STATIC_CAST_EXPR:
9722     case DYNAMIC_CAST_EXPR:
9723     case NOP_EXPR:
9724       return build1
9725         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9726          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9727
9728     case SIZEOF_EXPR:
9729       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
9730         {
9731           /* We only want to compute the number of arguments.  */
9732           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
9733                                                 complain, in_decl);
9734           if (expanded == error_mark_node)
9735             return error_mark_node;
9736           return build_int_cst (size_type_node, TREE_VEC_LENGTH (expanded));
9737         }
9738       /* Fall through */
9739
9740     case INDIRECT_REF:
9741     case NEGATE_EXPR:
9742     case TRUTH_NOT_EXPR:
9743     case BIT_NOT_EXPR:
9744     case ADDR_EXPR:
9745     case UNARY_PLUS_EXPR:      /* Unary + */
9746     case ALIGNOF_EXPR:
9747     case ARROW_EXPR:
9748     case THROW_EXPR:
9749     case TYPEID_EXPR:
9750     case REALPART_EXPR:
9751     case IMAGPART_EXPR:
9752       return build1
9753         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9754          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9755
9756     case COMPONENT_REF:
9757       {
9758         tree object;
9759         tree name;
9760
9761         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
9762         name = TREE_OPERAND (t, 1);
9763         if (TREE_CODE (name) == BIT_NOT_EXPR)
9764           {
9765             name = tsubst_copy (TREE_OPERAND (name, 0), args,
9766                                 complain, in_decl);
9767             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
9768           }
9769         else if (TREE_CODE (name) == SCOPE_REF
9770                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
9771           {
9772             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
9773                                      complain, in_decl);
9774             name = TREE_OPERAND (name, 1);
9775             name = tsubst_copy (TREE_OPERAND (name, 0), args,
9776                                 complain, in_decl);
9777             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
9778             name = build_qualified_name (/*type=*/NULL_TREE,
9779                                          base, name,
9780                                          /*template_p=*/false);
9781           }
9782         else if (TREE_CODE (name) == BASELINK)
9783           name = tsubst_baselink (name,
9784                                   non_reference (TREE_TYPE (object)),
9785                                   args, complain,
9786                                   in_decl);
9787         else
9788           name = tsubst_copy (name, args, complain, in_decl);
9789         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
9790       }
9791
9792     case PLUS_EXPR:
9793     case MINUS_EXPR:
9794     case MULT_EXPR:
9795     case TRUNC_DIV_EXPR:
9796     case CEIL_DIV_EXPR:
9797     case FLOOR_DIV_EXPR:
9798     case ROUND_DIV_EXPR:
9799     case EXACT_DIV_EXPR:
9800     case BIT_AND_EXPR:
9801     case BIT_IOR_EXPR:
9802     case BIT_XOR_EXPR:
9803     case TRUNC_MOD_EXPR:
9804     case FLOOR_MOD_EXPR:
9805     case TRUTH_ANDIF_EXPR:
9806     case TRUTH_ORIF_EXPR:
9807     case TRUTH_AND_EXPR:
9808     case TRUTH_OR_EXPR:
9809     case RSHIFT_EXPR:
9810     case LSHIFT_EXPR:
9811     case RROTATE_EXPR:
9812     case LROTATE_EXPR:
9813     case EQ_EXPR:
9814     case NE_EXPR:
9815     case MAX_EXPR:
9816     case MIN_EXPR:
9817     case LE_EXPR:
9818     case GE_EXPR:
9819     case LT_EXPR:
9820     case GT_EXPR:
9821     case COMPOUND_EXPR:
9822     case DOTSTAR_EXPR:
9823     case MEMBER_REF:
9824     case PREDECREMENT_EXPR:
9825     case PREINCREMENT_EXPR:
9826     case POSTDECREMENT_EXPR:
9827     case POSTINCREMENT_EXPR:
9828       return build_nt
9829         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9830          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
9831
9832     case SCOPE_REF:
9833       return build_qualified_name (/*type=*/NULL_TREE,
9834                                    tsubst_copy (TREE_OPERAND (t, 0),
9835                                                 args, complain, in_decl),
9836                                    tsubst_copy (TREE_OPERAND (t, 1),
9837                                                 args, complain, in_decl),
9838                                    QUALIFIED_NAME_IS_TEMPLATE (t));
9839
9840     case ARRAY_REF:
9841       return build_nt
9842         (ARRAY_REF,
9843          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9844          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
9845          NULL_TREE, NULL_TREE);
9846
9847     case CALL_EXPR:
9848       {
9849         int n = VL_EXP_OPERAND_LENGTH (t);
9850         tree result = build_vl_exp (CALL_EXPR, n);
9851         int i;
9852         for (i = 0; i < n; i++)
9853           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
9854                                              complain, in_decl);
9855         return result;
9856       }
9857
9858     case COND_EXPR:
9859     case MODOP_EXPR:
9860     case PSEUDO_DTOR_EXPR:
9861       {
9862         r = build_nt
9863           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9864            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
9865            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
9866         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
9867         return r;
9868       }
9869
9870     case NEW_EXPR:
9871       {
9872         r = build_nt
9873         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9874          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
9875          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
9876         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
9877         return r;
9878       }
9879
9880     case DELETE_EXPR:
9881       {
9882         r = build_nt
9883         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9884          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
9885         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
9886         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
9887         return r;
9888       }
9889
9890     case TEMPLATE_ID_EXPR:
9891       {
9892         /* Substituted template arguments */
9893         tree fn = TREE_OPERAND (t, 0);
9894         tree targs = TREE_OPERAND (t, 1);
9895
9896         fn = tsubst_copy (fn, args, complain, in_decl);
9897         if (targs)
9898           targs = tsubst_template_args (targs, args, complain, in_decl);
9899
9900         return lookup_template_function (fn, targs);
9901       }
9902
9903     case TREE_LIST:
9904       {
9905         tree purpose, value, chain;
9906
9907         if (t == void_list_node)
9908           return t;
9909
9910         purpose = TREE_PURPOSE (t);
9911         if (purpose)
9912           purpose = tsubst_copy (purpose, args, complain, in_decl);
9913         value = TREE_VALUE (t);
9914         if (value)
9915           value = tsubst_copy (value, args, complain, in_decl);
9916         chain = TREE_CHAIN (t);
9917         if (chain && chain != void_type_node)
9918           chain = tsubst_copy (chain, args, complain, in_decl);
9919         if (purpose == TREE_PURPOSE (t)
9920             && value == TREE_VALUE (t)
9921             && chain == TREE_CHAIN (t))
9922           return t;
9923         return tree_cons (purpose, value, chain);
9924       }
9925
9926     case RECORD_TYPE:
9927     case UNION_TYPE:
9928     case ENUMERAL_TYPE:
9929     case INTEGER_TYPE:
9930     case TEMPLATE_TYPE_PARM:
9931     case TEMPLATE_TEMPLATE_PARM:
9932     case BOUND_TEMPLATE_TEMPLATE_PARM:
9933     case TEMPLATE_PARM_INDEX:
9934     case POINTER_TYPE:
9935     case REFERENCE_TYPE:
9936     case OFFSET_TYPE:
9937     case FUNCTION_TYPE:
9938     case METHOD_TYPE:
9939     case ARRAY_TYPE:
9940     case TYPENAME_TYPE:
9941     case UNBOUND_CLASS_TEMPLATE:
9942     case TYPEOF_TYPE:
9943     case DECLTYPE_TYPE:
9944     case TYPE_DECL:
9945       return tsubst (t, args, complain, in_decl);
9946
9947     case IDENTIFIER_NODE:
9948       if (IDENTIFIER_TYPENAME_P (t))
9949         {
9950           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9951           return mangle_conv_op_name_for_type (new_type);
9952         }
9953       else
9954         return t;
9955
9956     case CONSTRUCTOR:
9957       /* This is handled by tsubst_copy_and_build.  */
9958       gcc_unreachable ();
9959
9960     case VA_ARG_EXPR:
9961       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
9962                                           in_decl),
9963                              tsubst (TREE_TYPE (t), args, complain, in_decl));
9964
9965     case CLEANUP_POINT_EXPR:
9966       /* We shouldn't have built any of these during initial template
9967          generation.  Instead, they should be built during instantiation
9968          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
9969       gcc_unreachable ();
9970
9971     case OFFSET_REF:
9972       mark_used (TREE_OPERAND (t, 1));
9973       return t;
9974
9975     case EXPR_PACK_EXPANSION:
9976       error ("invalid use of pack expansion expression");
9977       return error_mark_node;
9978
9979     case NONTYPE_ARGUMENT_PACK:
9980       error ("use %<...%> to expand argument pack");
9981       return error_mark_node;
9982
9983     default:
9984       return t;
9985     }
9986 }
9987
9988 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
9989
9990 static tree
9991 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
9992                     tree in_decl)
9993 {
9994   tree new_clauses = NULL, nc, oc;
9995
9996   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
9997     {
9998       nc = copy_node (oc);
9999       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10000       new_clauses = nc;
10001
10002       switch (OMP_CLAUSE_CODE (nc))
10003         {
10004         case OMP_CLAUSE_PRIVATE:
10005         case OMP_CLAUSE_SHARED:
10006         case OMP_CLAUSE_FIRSTPRIVATE:
10007         case OMP_CLAUSE_LASTPRIVATE:
10008         case OMP_CLAUSE_REDUCTION:
10009         case OMP_CLAUSE_COPYIN:
10010         case OMP_CLAUSE_COPYPRIVATE:
10011         case OMP_CLAUSE_IF:
10012         case OMP_CLAUSE_NUM_THREADS:
10013         case OMP_CLAUSE_SCHEDULE:
10014           OMP_CLAUSE_OPERAND (nc, 0)
10015             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10016                            in_decl, /*integral_constant_expression_p=*/false);
10017           break;
10018         case OMP_CLAUSE_NOWAIT:
10019         case OMP_CLAUSE_ORDERED:
10020         case OMP_CLAUSE_DEFAULT:
10021           break;
10022         default:
10023           gcc_unreachable ();
10024         }
10025     }
10026
10027   return finish_omp_clauses (nreverse (new_clauses));
10028 }
10029
10030 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10031
10032 static tree
10033 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10034                           tree in_decl)
10035 {
10036 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10037
10038   tree purpose, value, chain;
10039
10040   if (t == NULL)
10041     return t;
10042
10043   if (TREE_CODE (t) != TREE_LIST)
10044     return tsubst_copy_and_build (t, args, complain, in_decl,
10045                                   /*function_p=*/false,
10046                                   /*integral_constant_expression_p=*/false);
10047
10048   if (t == void_list_node)
10049     return t;
10050
10051   purpose = TREE_PURPOSE (t);
10052   if (purpose)
10053     purpose = RECUR (purpose);
10054   value = TREE_VALUE (t);
10055   if (value)
10056     value = RECUR (value);
10057   chain = TREE_CHAIN (t);
10058   if (chain && chain != void_type_node)
10059     chain = RECUR (chain);
10060   return tree_cons (purpose, value, chain);
10061 #undef RECUR
10062 }
10063
10064 /* Like tsubst_copy for expressions, etc. but also does semantic
10065    processing.  */
10066
10067 static tree
10068 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10069              bool integral_constant_expression_p)
10070 {
10071 #define RECUR(NODE)                             \
10072   tsubst_expr ((NODE), args, complain, in_decl, \
10073                integral_constant_expression_p)
10074
10075   tree stmt, tmp;
10076
10077   if (t == NULL_TREE || t == error_mark_node)
10078     return t;
10079
10080   if (EXPR_HAS_LOCATION (t))
10081     input_location = EXPR_LOCATION (t);
10082   if (STATEMENT_CODE_P (TREE_CODE (t)))
10083     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10084
10085   switch (TREE_CODE (t))
10086     {
10087     case STATEMENT_LIST:
10088       {
10089         tree_stmt_iterator i;
10090         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10091           RECUR (tsi_stmt (i));
10092         break;
10093       }
10094
10095     case CTOR_INITIALIZER:
10096       finish_mem_initializers (tsubst_initializer_list
10097                                (TREE_OPERAND (t, 0), args));
10098       break;
10099
10100     case RETURN_EXPR:
10101       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10102       break;
10103
10104     case EXPR_STMT:
10105       tmp = RECUR (EXPR_STMT_EXPR (t));
10106       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10107         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10108       else
10109         finish_expr_stmt (tmp);
10110       break;
10111
10112     case USING_STMT:
10113       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10114       break;
10115
10116     case DECL_EXPR:
10117       {
10118         tree decl;
10119         tree init;
10120
10121         decl = DECL_EXPR_DECL (t);
10122         if (TREE_CODE (decl) == LABEL_DECL)
10123           finish_label_decl (DECL_NAME (decl));
10124         else if (TREE_CODE (decl) == USING_DECL)
10125           {
10126             tree scope = USING_DECL_SCOPE (decl);
10127             tree name = DECL_NAME (decl);
10128             tree decl;
10129
10130             scope = RECUR (scope);
10131             decl = lookup_qualified_name (scope, name,
10132                                           /*is_type_p=*/false,
10133                                           /*complain=*/false);
10134             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10135               qualified_name_lookup_error (scope, name, decl);
10136             else
10137               do_local_using_decl (decl, scope, name);
10138           }
10139         else
10140           {
10141             init = DECL_INITIAL (decl);
10142             decl = tsubst (decl, args, complain, in_decl);
10143             if (decl != error_mark_node)
10144               {
10145                 /* By marking the declaration as instantiated, we avoid
10146                    trying to instantiate it.  Since instantiate_decl can't
10147                    handle local variables, and since we've already done
10148                    all that needs to be done, that's the right thing to
10149                    do.  */
10150                 if (TREE_CODE (decl) == VAR_DECL)
10151                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10152                 if (TREE_CODE (decl) == VAR_DECL
10153                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10154                   /* Anonymous aggregates are a special case.  */
10155                   finish_anon_union (decl);
10156                 else
10157                   {
10158                     maybe_push_decl (decl);
10159                     if (TREE_CODE (decl) == VAR_DECL
10160                         && DECL_PRETTY_FUNCTION_P (decl))
10161                       {
10162                         /* For __PRETTY_FUNCTION__ we have to adjust the
10163                            initializer.  */
10164                         const char *const name
10165                           = cxx_printable_name (current_function_decl, 2);
10166                         init = cp_fname_init (name, &TREE_TYPE (decl));
10167                       }
10168                     else
10169                       {
10170                         tree t = RECUR (init);
10171
10172                         if (init && !t)
10173                           /* If we had an initializer but it
10174                              instantiated to nothing,
10175                              value-initialize the object.  This will
10176                              only occur when the initializer was a
10177                              pack expansion where the parameter packs
10178                              used in that expansion were of length
10179                              zero.  */
10180                           init = build_default_init (TREE_TYPE (decl),
10181                                                      NULL_TREE);
10182                         else
10183                           init = t;
10184                       }
10185
10186                     finish_decl (decl, init, NULL_TREE);
10187                   }
10188               }
10189           }
10190
10191         /* A DECL_EXPR can also be used as an expression, in the condition
10192            clause of an if/for/while construct.  */
10193         return decl;
10194       }
10195
10196     case FOR_STMT:
10197       stmt = begin_for_stmt ();
10198                           RECUR (FOR_INIT_STMT (t));
10199       finish_for_init_stmt (stmt);
10200       tmp = RECUR (FOR_COND (t));
10201       finish_for_cond (tmp, stmt);
10202       tmp = RECUR (FOR_EXPR (t));
10203       finish_for_expr (tmp, stmt);
10204       RECUR (FOR_BODY (t));
10205       finish_for_stmt (stmt);
10206       break;
10207
10208     case WHILE_STMT:
10209       stmt = begin_while_stmt ();
10210       tmp = RECUR (WHILE_COND (t));
10211       finish_while_stmt_cond (tmp, stmt);
10212       RECUR (WHILE_BODY (t));
10213       finish_while_stmt (stmt);
10214       break;
10215
10216     case DO_STMT:
10217       stmt = begin_do_stmt ();
10218       RECUR (DO_BODY (t));
10219       finish_do_body (stmt);
10220       tmp = RECUR (DO_COND (t));
10221       finish_do_stmt (tmp, stmt);
10222       break;
10223
10224     case IF_STMT:
10225       stmt = begin_if_stmt ();
10226       tmp = RECUR (IF_COND (t));
10227       finish_if_stmt_cond (tmp, stmt);
10228       RECUR (THEN_CLAUSE (t));
10229       finish_then_clause (stmt);
10230
10231       if (ELSE_CLAUSE (t))
10232         {
10233           begin_else_clause (stmt);
10234           RECUR (ELSE_CLAUSE (t));
10235           finish_else_clause (stmt);
10236         }
10237
10238       finish_if_stmt (stmt);
10239       break;
10240
10241     case BIND_EXPR:
10242       if (BIND_EXPR_BODY_BLOCK (t))
10243         stmt = begin_function_body ();
10244       else
10245         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10246                                     ? BCS_TRY_BLOCK : 0);
10247
10248       RECUR (BIND_EXPR_BODY (t));
10249
10250       if (BIND_EXPR_BODY_BLOCK (t))
10251         finish_function_body (stmt);
10252       else
10253         finish_compound_stmt (stmt);
10254       break;
10255
10256     case BREAK_STMT:
10257       finish_break_stmt ();
10258       break;
10259
10260     case CONTINUE_STMT:
10261       finish_continue_stmt ();
10262       break;
10263
10264     case SWITCH_STMT:
10265       stmt = begin_switch_stmt ();
10266       tmp = RECUR (SWITCH_STMT_COND (t));
10267       finish_switch_cond (tmp, stmt);
10268       RECUR (SWITCH_STMT_BODY (t));
10269       finish_switch_stmt (stmt);
10270       break;
10271
10272     case CASE_LABEL_EXPR:
10273       finish_case_label (RECUR (CASE_LOW (t)),
10274                          RECUR (CASE_HIGH (t)));
10275       break;
10276
10277     case LABEL_EXPR:
10278       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10279       break;
10280
10281     case GOTO_EXPR:
10282       tmp = GOTO_DESTINATION (t);
10283       if (TREE_CODE (tmp) != LABEL_DECL)
10284         /* Computed goto's must be tsubst'd into.  On the other hand,
10285            non-computed gotos must not be; the identifier in question
10286            will have no binding.  */
10287         tmp = RECUR (tmp);
10288       else
10289         tmp = DECL_NAME (tmp);
10290       finish_goto_stmt (tmp);
10291       break;
10292
10293     case ASM_EXPR:
10294       tmp = finish_asm_stmt
10295         (ASM_VOLATILE_P (t),
10296          RECUR (ASM_STRING (t)),
10297          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10298          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10299          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10300       {
10301         tree asm_expr = tmp;
10302         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10303           asm_expr = TREE_OPERAND (asm_expr, 0);
10304         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10305       }
10306       break;
10307
10308     case TRY_BLOCK:
10309       if (CLEANUP_P (t))
10310         {
10311           stmt = begin_try_block ();
10312           RECUR (TRY_STMTS (t));
10313           finish_cleanup_try_block (stmt);
10314           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10315         }
10316       else
10317         {
10318           tree compound_stmt = NULL_TREE;
10319
10320           if (FN_TRY_BLOCK_P (t))
10321             stmt = begin_function_try_block (&compound_stmt);
10322           else
10323             stmt = begin_try_block ();
10324
10325           RECUR (TRY_STMTS (t));
10326
10327           if (FN_TRY_BLOCK_P (t))
10328             finish_function_try_block (stmt);
10329           else
10330             finish_try_block (stmt);
10331
10332           RECUR (TRY_HANDLERS (t));
10333           if (FN_TRY_BLOCK_P (t))
10334             finish_function_handler_sequence (stmt, compound_stmt);
10335           else
10336             finish_handler_sequence (stmt);
10337         }
10338       break;
10339
10340     case HANDLER:
10341       {
10342         tree decl = HANDLER_PARMS (t);
10343
10344         if (decl)
10345           {
10346             decl = tsubst (decl, args, complain, in_decl);
10347             /* Prevent instantiate_decl from trying to instantiate
10348                this variable.  We've already done all that needs to be
10349                done.  */
10350             if (decl != error_mark_node)
10351               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10352           }
10353         stmt = begin_handler ();
10354         finish_handler_parms (decl, stmt);
10355         RECUR (HANDLER_BODY (t));
10356         finish_handler (stmt);
10357       }
10358       break;
10359
10360     case TAG_DEFN:
10361       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10362       break;
10363
10364     case STATIC_ASSERT:
10365       {
10366         tree condition = 
10367           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10368                        args,
10369                        complain, in_decl,
10370                        /*integral_constant_expression_p=*/true);
10371         finish_static_assert (condition,
10372                               STATIC_ASSERT_MESSAGE (t),
10373                               STATIC_ASSERT_SOURCE_LOCATION (t),
10374                               /*member_p=*/false);
10375       }
10376       break;
10377
10378     case OMP_PARALLEL:
10379       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
10380                                 args, complain, in_decl);
10381       stmt = begin_omp_parallel ();
10382       RECUR (OMP_PARALLEL_BODY (t));
10383       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
10384         = OMP_PARALLEL_COMBINED (t);
10385       break;
10386
10387     case OMP_FOR:
10388       {
10389         tree clauses, decl, init, cond, incr, body, pre_body;
10390
10391         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
10392                                       args, complain, in_decl);
10393         init = OMP_FOR_INIT (t);
10394         gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10395         decl = RECUR (TREE_OPERAND (init, 0));
10396         init = RECUR (TREE_OPERAND (init, 1));
10397         cond = RECUR (OMP_FOR_COND (t));
10398         incr = RECUR (OMP_FOR_INCR (t));
10399
10400         stmt = begin_omp_structured_block ();
10401
10402         pre_body = push_stmt_list ();
10403         RECUR (OMP_FOR_PRE_BODY (t));
10404         pre_body = pop_stmt_list (pre_body);
10405
10406         body = push_stmt_list ();
10407         RECUR (OMP_FOR_BODY (t));
10408         body = pop_stmt_list (body);
10409
10410         t = finish_omp_for (EXPR_LOCATION (t), decl, init, cond, incr, body,
10411                             pre_body);
10412         if (t)
10413           OMP_FOR_CLAUSES (t) = clauses;
10414
10415         add_stmt (finish_omp_structured_block (stmt));
10416       }
10417       break;
10418
10419     case OMP_SECTIONS:
10420     case OMP_SINGLE:
10421       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
10422       stmt = push_stmt_list ();
10423       RECUR (OMP_BODY (t));
10424       stmt = pop_stmt_list (stmt);
10425
10426       t = copy_node (t);
10427       OMP_BODY (t) = stmt;
10428       OMP_CLAUSES (t) = tmp;
10429       add_stmt (t);
10430       break;
10431
10432     case OMP_SECTION:
10433     case OMP_CRITICAL:
10434     case OMP_MASTER:
10435     case OMP_ORDERED:
10436       stmt = push_stmt_list ();
10437       RECUR (OMP_BODY (t));
10438       stmt = pop_stmt_list (stmt);
10439
10440       t = copy_node (t);
10441       OMP_BODY (t) = stmt;
10442       add_stmt (t);
10443       break;
10444
10445     case OMP_ATOMIC:
10446       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
10447       {
10448         tree op1 = TREE_OPERAND (t, 1);
10449         tree lhs = RECUR (TREE_OPERAND (op1, 0));
10450         tree rhs = RECUR (TREE_OPERAND (op1, 1));
10451         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
10452       }
10453       break;
10454
10455     case EXPR_PACK_EXPANSION:
10456       error ("invalid use of pack expansion expression");
10457       return error_mark_node;
10458
10459     case NONTYPE_ARGUMENT_PACK:
10460       error ("use %<...%> to expand argument pack");
10461       return error_mark_node;
10462
10463     default:
10464       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
10465
10466       return tsubst_copy_and_build (t, args, complain, in_decl,
10467                                     /*function_p=*/false,
10468                                     integral_constant_expression_p);
10469     }
10470
10471   return NULL_TREE;
10472 #undef RECUR
10473 }
10474
10475 /* T is a postfix-expression that is not being used in a function
10476    call.  Return the substituted version of T.  */
10477
10478 static tree
10479 tsubst_non_call_postfix_expression (tree t, tree args,
10480                                     tsubst_flags_t complain,
10481                                     tree in_decl)
10482 {
10483   if (TREE_CODE (t) == SCOPE_REF)
10484     t = tsubst_qualified_id (t, args, complain, in_decl,
10485                              /*done=*/false, /*address_p=*/false);
10486   else
10487     t = tsubst_copy_and_build (t, args, complain, in_decl,
10488                                /*function_p=*/false,
10489                                /*integral_constant_expression_p=*/false);
10490
10491   return t;
10492 }
10493
10494 /* Like tsubst but deals with expressions and performs semantic
10495    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
10496
10497 tree
10498 tsubst_copy_and_build (tree t,
10499                        tree args,
10500                        tsubst_flags_t complain,
10501                        tree in_decl,
10502                        bool function_p,
10503                        bool integral_constant_expression_p)
10504 {
10505 #define RECUR(NODE)                                             \
10506   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
10507                          /*function_p=*/false,                  \
10508                          integral_constant_expression_p)
10509
10510   tree op1;
10511
10512   if (t == NULL_TREE || t == error_mark_node)
10513     return t;
10514
10515   switch (TREE_CODE (t))
10516     {
10517     case USING_DECL:
10518       t = DECL_NAME (t);
10519       /* Fall through.  */
10520     case IDENTIFIER_NODE:
10521       {
10522         tree decl;
10523         cp_id_kind idk;
10524         bool non_integral_constant_expression_p;
10525         const char *error_msg;
10526
10527         if (IDENTIFIER_TYPENAME_P (t))
10528           {
10529             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10530             t = mangle_conv_op_name_for_type (new_type);
10531           }
10532
10533         /* Look up the name.  */
10534         decl = lookup_name (t);
10535
10536         /* By convention, expressions use ERROR_MARK_NODE to indicate
10537            failure, not NULL_TREE.  */
10538         if (decl == NULL_TREE)
10539           decl = error_mark_node;
10540
10541         decl = finish_id_expression (t, decl, NULL_TREE,
10542                                      &idk,
10543                                      integral_constant_expression_p,
10544                                      /*allow_non_integral_constant_expression_p=*/false,
10545                                      &non_integral_constant_expression_p,
10546                                      /*template_p=*/false,
10547                                      /*done=*/true,
10548                                      /*address_p=*/false,
10549                                      /*template_arg_p=*/false,
10550                                      &error_msg);
10551         if (error_msg)
10552           error (error_msg);
10553         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
10554           decl = unqualified_name_lookup_error (decl);
10555         return decl;
10556       }
10557
10558     case TEMPLATE_ID_EXPR:
10559       {
10560         tree object;
10561         tree template = RECUR (TREE_OPERAND (t, 0));
10562         tree targs = TREE_OPERAND (t, 1);
10563
10564         if (targs)
10565           targs = tsubst_template_args (targs, args, complain, in_decl);
10566
10567         if (TREE_CODE (template) == COMPONENT_REF)
10568           {
10569             object = TREE_OPERAND (template, 0);
10570             template = TREE_OPERAND (template, 1);
10571           }
10572         else
10573           object = NULL_TREE;
10574         template = lookup_template_function (template, targs);
10575
10576         if (object)
10577           return build3 (COMPONENT_REF, TREE_TYPE (template),
10578                          object, template, NULL_TREE);
10579         else
10580           return baselink_for_fns (template);
10581       }
10582
10583     case INDIRECT_REF:
10584       {
10585         tree r = RECUR (TREE_OPERAND (t, 0));
10586
10587         if (REFERENCE_REF_P (t))
10588           {
10589             /* A type conversion to reference type will be enclosed in
10590                such an indirect ref, but the substitution of the cast
10591                will have also added such an indirect ref.  */
10592             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
10593               r = convert_from_reference (r);
10594           }
10595         else
10596           r = build_x_indirect_ref (r, "unary *");
10597         return r;
10598       }
10599
10600     case NOP_EXPR:
10601       return build_nop
10602         (tsubst (TREE_TYPE (t), args, complain, in_decl),
10603          RECUR (TREE_OPERAND (t, 0)));
10604
10605     case CAST_EXPR:
10606     case REINTERPRET_CAST_EXPR:
10607     case CONST_CAST_EXPR:
10608     case DYNAMIC_CAST_EXPR:
10609     case STATIC_CAST_EXPR:
10610       {
10611         tree type;
10612         tree op;
10613
10614         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10615         if (integral_constant_expression_p
10616             && !cast_valid_in_integral_constant_expression_p (type))
10617           {
10618             error ("a cast to a type other than an integral or "
10619                    "enumeration type cannot appear in a constant-expression");
10620             return error_mark_node; 
10621           }
10622
10623         op = RECUR (TREE_OPERAND (t, 0));
10624
10625         switch (TREE_CODE (t))
10626           {
10627           case CAST_EXPR:
10628             return build_functional_cast (type, op);
10629           case REINTERPRET_CAST_EXPR:
10630             return build_reinterpret_cast (type, op);
10631           case CONST_CAST_EXPR:
10632             return build_const_cast (type, op);
10633           case DYNAMIC_CAST_EXPR:
10634             return build_dynamic_cast (type, op);
10635           case STATIC_CAST_EXPR:
10636             return build_static_cast (type, op);
10637           default:
10638             gcc_unreachable ();
10639           }
10640       }
10641
10642     case POSTDECREMENT_EXPR:
10643     case POSTINCREMENT_EXPR:
10644       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10645                                                 args, complain, in_decl);
10646       return build_x_unary_op (TREE_CODE (t), op1);
10647
10648     case PREDECREMENT_EXPR:
10649     case PREINCREMENT_EXPR:
10650     case NEGATE_EXPR:
10651     case BIT_NOT_EXPR:
10652     case ABS_EXPR:
10653     case TRUTH_NOT_EXPR:
10654     case UNARY_PLUS_EXPR:  /* Unary + */
10655     case REALPART_EXPR:
10656     case IMAGPART_EXPR:
10657       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)));
10658
10659     case ADDR_EXPR:
10660       op1 = TREE_OPERAND (t, 0);
10661       if (TREE_CODE (op1) == SCOPE_REF)
10662         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
10663                                    /*done=*/true, /*address_p=*/true);
10664       else
10665         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
10666                                                   in_decl);
10667       if (TREE_CODE (op1) == LABEL_DECL)
10668         return finish_label_address_expr (DECL_NAME (op1));
10669       return build_x_unary_op (ADDR_EXPR, op1);
10670
10671     case PLUS_EXPR:
10672     case MINUS_EXPR:
10673     case MULT_EXPR:
10674     case TRUNC_DIV_EXPR:
10675     case CEIL_DIV_EXPR:
10676     case FLOOR_DIV_EXPR:
10677     case ROUND_DIV_EXPR:
10678     case EXACT_DIV_EXPR:
10679     case BIT_AND_EXPR:
10680     case BIT_IOR_EXPR:
10681     case BIT_XOR_EXPR:
10682     case TRUNC_MOD_EXPR:
10683     case FLOOR_MOD_EXPR:
10684     case TRUTH_ANDIF_EXPR:
10685     case TRUTH_ORIF_EXPR:
10686     case TRUTH_AND_EXPR:
10687     case TRUTH_OR_EXPR:
10688     case RSHIFT_EXPR:
10689     case LSHIFT_EXPR:
10690     case RROTATE_EXPR:
10691     case LROTATE_EXPR:
10692     case EQ_EXPR:
10693     case NE_EXPR:
10694     case MAX_EXPR:
10695     case MIN_EXPR:
10696     case LE_EXPR:
10697     case GE_EXPR:
10698     case LT_EXPR:
10699     case GT_EXPR:
10700     case MEMBER_REF:
10701     case DOTSTAR_EXPR:
10702       return build_x_binary_op
10703         (TREE_CODE (t),
10704          RECUR (TREE_OPERAND (t, 0)),
10705          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
10706           ? ERROR_MARK
10707           : TREE_CODE (TREE_OPERAND (t, 0))),
10708          RECUR (TREE_OPERAND (t, 1)),
10709          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
10710           ? ERROR_MARK
10711           : TREE_CODE (TREE_OPERAND (t, 1))),
10712          /*overloaded_p=*/NULL);
10713
10714     case SCOPE_REF:
10715       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
10716                                   /*address_p=*/false);
10717     case ARRAY_REF:
10718       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10719                                                 args, complain, in_decl);
10720       return build_x_binary_op (ARRAY_REF, op1,
10721                                 (TREE_NO_WARNING (TREE_OPERAND (t, 0))
10722                                  ? ERROR_MARK
10723                                  : TREE_CODE (TREE_OPERAND (t, 0))),
10724                                 RECUR (TREE_OPERAND (t, 1)),
10725                                 (TREE_NO_WARNING (TREE_OPERAND (t, 1))
10726                                  ? ERROR_MARK
10727                                  : TREE_CODE (TREE_OPERAND (t, 1))),
10728                                 /*overloaded_p=*/NULL);
10729
10730     case SIZEOF_EXPR:
10731       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10732         {
10733           /* We only want to compute the number of arguments.  */
10734           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10735                                                 complain, in_decl);
10736           if (expanded == error_mark_node)
10737             return error_mark_node;
10738           return build_int_cst (size_type_node, TREE_VEC_LENGTH (expanded));
10739         }
10740       /* Fall through */
10741       
10742     case ALIGNOF_EXPR:
10743       op1 = TREE_OPERAND (t, 0);
10744       if (!args)
10745         {
10746           /* When there are no ARGS, we are trying to evaluate a
10747              non-dependent expression from the parser.  Trying to do
10748              the substitutions may not work.  */
10749           if (!TYPE_P (op1))
10750             op1 = TREE_TYPE (op1);
10751         }
10752       else
10753         {
10754           ++skip_evaluation;
10755           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
10756                                        /*function_p=*/false,
10757                                        /*integral_constant_expression_p=*/false);
10758           --skip_evaluation;
10759         }
10760       if (TYPE_P (op1))
10761         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), true);
10762       else
10763         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t));
10764
10765     case MODOP_EXPR:
10766       {
10767         tree r = build_x_modify_expr
10768           (RECUR (TREE_OPERAND (t, 0)),
10769            TREE_CODE (TREE_OPERAND (t, 1)),
10770            RECUR (TREE_OPERAND (t, 2)));
10771         /* TREE_NO_WARNING must be set if either the expression was
10772            parenthesized or it uses an operator such as >>= rather
10773            than plain assignment.  In the former case, it was already
10774            set and must be copied.  In the latter case,
10775            build_x_modify_expr sets it and it must not be reset
10776            here.  */
10777         if (TREE_NO_WARNING (t))
10778           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10779         return r;
10780       }
10781
10782     case ARROW_EXPR:
10783       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10784                                                 args, complain, in_decl);
10785       /* Remember that there was a reference to this entity.  */
10786       if (DECL_P (op1))
10787         mark_used (op1);
10788       return build_x_arrow (op1);
10789
10790     case NEW_EXPR:
10791       {
10792         tree init = RECUR (TREE_OPERAND (t, 3));
10793
10794         if (TREE_OPERAND (t, 3) && !init)
10795           /* If there was an initializer in the the original tree, but
10796              it instantiated to an empty list, then we should pass on
10797              VOID_ZERO_NODE to tell build_new that it was an empty
10798              initializer () rather than no initializer.  This can only
10799              happen when the initializer is a pack expansion whose
10800              parameter packs are of length zero.  */
10801           init = void_zero_node;
10802
10803         return build_new
10804           (RECUR (TREE_OPERAND (t, 0)),
10805            RECUR (TREE_OPERAND (t, 1)),
10806            RECUR (TREE_OPERAND (t, 2)),
10807            init,
10808            NEW_EXPR_USE_GLOBAL (t));
10809       }
10810
10811     case DELETE_EXPR:
10812      return delete_sanity
10813        (RECUR (TREE_OPERAND (t, 0)),
10814         RECUR (TREE_OPERAND (t, 1)),
10815         DELETE_EXPR_USE_VEC (t),
10816         DELETE_EXPR_USE_GLOBAL (t));
10817
10818     case COMPOUND_EXPR:
10819       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
10820                                     RECUR (TREE_OPERAND (t, 1)));
10821
10822     case CALL_EXPR:
10823       {
10824         tree function;
10825         tree call_args;
10826         bool qualified_p;
10827         bool koenig_p;
10828
10829         function = CALL_EXPR_FN (t);
10830         /* When we parsed the expression,  we determined whether or
10831            not Koenig lookup should be performed.  */
10832         koenig_p = KOENIG_LOOKUP_P (t);
10833         if (TREE_CODE (function) == SCOPE_REF)
10834           {
10835             qualified_p = true;
10836             function = tsubst_qualified_id (function, args, complain, in_decl,
10837                                             /*done=*/false,
10838                                             /*address_p=*/false);
10839           }
10840         else
10841           {
10842             if (TREE_CODE (function) == COMPONENT_REF)
10843               {
10844                 tree op = TREE_OPERAND (function, 1);
10845
10846                 qualified_p = (TREE_CODE (op) == SCOPE_REF
10847                                || (BASELINK_P (op)
10848                                    && BASELINK_QUALIFIED_P (op)));
10849               }
10850             else
10851               qualified_p = false;
10852
10853             function = tsubst_copy_and_build (function, args, complain,
10854                                               in_decl,
10855                                               !qualified_p,
10856                                               integral_constant_expression_p);
10857
10858             if (BASELINK_P (function))
10859               qualified_p = true;
10860           }
10861
10862         /* FIXME:  Rewrite this so as not to construct an arglist.  */
10863         call_args = RECUR (CALL_EXPR_ARGS (t));
10864
10865         /* We do not perform argument-dependent lookup if normal
10866            lookup finds a non-function, in accordance with the
10867            expected resolution of DR 218.  */
10868         if (koenig_p
10869             && ((is_overloaded_fn (function)
10870                  /* If lookup found a member function, the Koenig lookup is
10871                     not appropriate, even if an unqualified-name was used
10872                     to denote the function.  */
10873                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
10874                 || TREE_CODE (function) == IDENTIFIER_NODE))
10875           function = perform_koenig_lookup (function, call_args);
10876
10877         if (TREE_CODE (function) == IDENTIFIER_NODE)
10878           {
10879             unqualified_name_lookup_error (function);
10880             return error_mark_node;
10881           }
10882
10883         /* Remember that there was a reference to this entity.  */
10884         if (DECL_P (function))
10885           mark_used (function);
10886
10887         if (TREE_CODE (function) == OFFSET_REF)
10888           return build_offset_ref_call_from_tree (function, call_args);
10889         if (TREE_CODE (function) == COMPONENT_REF)
10890           {
10891             if (!BASELINK_P (TREE_OPERAND (function, 1)))
10892               return finish_call_expr (function, call_args,
10893                                        /*disallow_virtual=*/false,
10894                                        /*koenig_p=*/false);
10895             else
10896               return (build_new_method_call
10897                       (TREE_OPERAND (function, 0),
10898                        TREE_OPERAND (function, 1),
10899                        call_args, NULL_TREE,
10900                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
10901                        /*fn_p=*/NULL));
10902           }
10903         return finish_call_expr (function, call_args,
10904                                  /*disallow_virtual=*/qualified_p,
10905                                  koenig_p);
10906       }
10907
10908     case COND_EXPR:
10909       return build_x_conditional_expr
10910         (RECUR (TREE_OPERAND (t, 0)),
10911          RECUR (TREE_OPERAND (t, 1)),
10912          RECUR (TREE_OPERAND (t, 2)));
10913
10914     case PSEUDO_DTOR_EXPR:
10915       return finish_pseudo_destructor_expr
10916         (RECUR (TREE_OPERAND (t, 0)),
10917          RECUR (TREE_OPERAND (t, 1)),
10918          RECUR (TREE_OPERAND (t, 2)));
10919
10920     case TREE_LIST:
10921       {
10922         tree purpose, value, chain;
10923
10924         if (t == void_list_node)
10925           return t;
10926
10927         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
10928             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
10929           {
10930             /* We have pack expansions, so expand those and
10931                create a new list out of it.  */
10932             tree purposevec = NULL_TREE;
10933             tree valuevec = NULL_TREE;
10934             tree chain;
10935             int i, len = -1;
10936
10937             /* Expand the argument expressions.  */
10938             if (TREE_PURPOSE (t))
10939               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
10940                                                  complain, in_decl);
10941             if (TREE_VALUE (t))
10942               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
10943                                                complain, in_decl);
10944
10945             /* Build the rest of the list.  */
10946             chain = TREE_CHAIN (t);
10947             if (chain && chain != void_type_node)
10948               chain = RECUR (chain);
10949
10950             /* Determine the number of arguments.  */
10951             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
10952               {
10953                 len = TREE_VEC_LENGTH (purposevec);
10954                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
10955               }
10956             else if (TREE_CODE (valuevec) == TREE_VEC)
10957               len = TREE_VEC_LENGTH (valuevec);
10958             else
10959               {
10960                 /* Since we only performed a partial substitution into
10961                    the argument pack, we only return a single list
10962                    node.  */
10963                 if (purposevec == TREE_PURPOSE (t)
10964                     && valuevec == TREE_VALUE (t)
10965                     && chain == TREE_CHAIN (t))
10966                   return t;
10967
10968                 return tree_cons (purposevec, valuevec, chain);
10969               }
10970             
10971             /* Convert the argument vectors into a TREE_LIST */
10972             i = len;
10973             while (i > 0)
10974               {
10975                 /* Grab the Ith values.  */
10976                 i--;
10977                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
10978                                      : NULL_TREE;
10979                 value 
10980                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
10981                              : NULL_TREE;
10982
10983                 /* Build the list (backwards).  */
10984                 chain = tree_cons (purpose, value, chain);
10985               }
10986
10987             return chain;
10988           }
10989
10990         purpose = TREE_PURPOSE (t);
10991         if (purpose)
10992           purpose = RECUR (purpose);
10993         value = TREE_VALUE (t);
10994         if (value)
10995           value = RECUR (value);
10996         chain = TREE_CHAIN (t);
10997         if (chain && chain != void_type_node)
10998           chain = RECUR (chain);
10999         if (purpose == TREE_PURPOSE (t)
11000             && value == TREE_VALUE (t)
11001             && chain == TREE_CHAIN (t))
11002           return t;
11003         return tree_cons (purpose, value, chain);
11004       }
11005
11006     case COMPONENT_REF:
11007       {
11008         tree object;
11009         tree object_type;
11010         tree member;
11011
11012         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11013                                                      args, complain, in_decl);
11014         /* Remember that there was a reference to this entity.  */
11015         if (DECL_P (object))
11016           mark_used (object);
11017         object_type = TREE_TYPE (object);
11018
11019         member = TREE_OPERAND (t, 1);
11020         if (BASELINK_P (member))
11021           member = tsubst_baselink (member,
11022                                     non_reference (TREE_TYPE (object)),
11023                                     args, complain, in_decl);
11024         else
11025           member = tsubst_copy (member, args, complain, in_decl);
11026         if (member == error_mark_node)
11027           return error_mark_node;
11028
11029         if (object_type && !CLASS_TYPE_P (object_type))
11030           {
11031             if (SCALAR_TYPE_P (object_type))
11032               {
11033                 tree s = NULL_TREE;
11034                 tree dtor = member;
11035
11036                 if (TREE_CODE (dtor) == SCOPE_REF)
11037                   {
11038                     s = TREE_OPERAND (dtor, 0);
11039                     dtor = TREE_OPERAND (dtor, 1);
11040                   }
11041                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11042                   {
11043                     dtor = TREE_OPERAND (dtor, 0);
11044                     if (TYPE_P (dtor))
11045                       return finish_pseudo_destructor_expr (object, s, dtor);
11046                   }
11047               }
11048           }
11049         else if (TREE_CODE (member) == SCOPE_REF
11050                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11051           {
11052             tree tmpl;
11053             tree args;
11054
11055             /* Lookup the template functions now that we know what the
11056                scope is.  */
11057             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11058             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11059             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11060                                             /*is_type_p=*/false,
11061                                             /*complain=*/false);
11062             if (BASELINK_P (member))
11063               {
11064                 BASELINK_FUNCTIONS (member)
11065                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11066                               args);
11067                 member = (adjust_result_of_qualified_name_lookup
11068                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11069                            object_type));
11070               }
11071             else
11072               {
11073                 qualified_name_lookup_error (object_type, tmpl, member);
11074                 return error_mark_node;
11075               }
11076           }
11077         else if (TREE_CODE (member) == SCOPE_REF
11078                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11079                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11080           {
11081             if (complain & tf_error)
11082               {
11083                 if (TYPE_P (TREE_OPERAND (member, 0)))
11084                   error ("%qT is not a class or namespace",
11085                          TREE_OPERAND (member, 0));
11086                 else
11087                   error ("%qD is not a class or namespace",
11088                          TREE_OPERAND (member, 0));
11089               }
11090             return error_mark_node;
11091           }
11092         else if (TREE_CODE (member) == FIELD_DECL)
11093           return finish_non_static_data_member (member, object, NULL_TREE);
11094
11095         return finish_class_member_access_expr (object, member,
11096                                                 /*template_p=*/false);
11097       }
11098
11099     case THROW_EXPR:
11100       return build_throw
11101         (RECUR (TREE_OPERAND (t, 0)));
11102
11103     case CONSTRUCTOR:
11104       {
11105         VEC(constructor_elt,gc) *n;
11106         constructor_elt *ce;
11107         unsigned HOST_WIDE_INT idx;
11108         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11109         bool process_index_p;
11110         int newlen;
11111         bool need_copy_p = false;
11112
11113         if (type == error_mark_node)
11114           return error_mark_node;
11115
11116         /* digest_init will do the wrong thing if we let it.  */
11117         if (type && TYPE_PTRMEMFUNC_P (type))
11118           return t;
11119
11120         /* We do not want to process the index of aggregate
11121            initializers as they are identifier nodes which will be
11122            looked up by digest_init.  */
11123         process_index_p = !(type && IS_AGGR_TYPE (type));
11124
11125         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11126         newlen = VEC_length (constructor_elt, n);
11127         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11128           {
11129             if (ce->index && process_index_p)
11130               ce->index = RECUR (ce->index);
11131
11132             if (PACK_EXPANSION_P (ce->value))
11133               {
11134                 /* Substitute into the pack expansion.  */
11135                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11136                                                   in_decl);
11137
11138                 if (ce->value == error_mark_node)
11139                   ;
11140                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11141                   /* Just move the argument into place.  */
11142                   ce->value = TREE_VEC_ELT (ce->value, 0);
11143                 else
11144                   {
11145                     /* Update the length of the final CONSTRUCTOR
11146                        arguments vector, and note that we will need to
11147                        copy.*/
11148                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11149                     need_copy_p = true;
11150                   }
11151               }
11152             else
11153               ce->value = RECUR (ce->value);
11154           }
11155
11156         if (need_copy_p)
11157           {
11158             VEC(constructor_elt,gc) *old_n = n;
11159
11160             n = VEC_alloc (constructor_elt, gc, newlen);
11161             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11162                  idx++)
11163               {
11164                 if (TREE_CODE (ce->value) == TREE_VEC)
11165                   {
11166                     int i, len = TREE_VEC_LENGTH (ce->value);
11167                     for (i = 0; i < len; ++i)
11168                       CONSTRUCTOR_APPEND_ELT (n, 0,
11169                                               TREE_VEC_ELT (ce->value, i));
11170                   }
11171                 else
11172                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11173               }
11174           }
11175
11176         if (TREE_HAS_CONSTRUCTOR (t))
11177           return finish_compound_literal (type, n);
11178
11179         return build_constructor (NULL_TREE, n);
11180       }
11181
11182     case TYPEID_EXPR:
11183       {
11184         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11185         if (TYPE_P (operand_0))
11186           return get_typeid (operand_0);
11187         return build_typeid (operand_0);
11188       }
11189
11190     case VAR_DECL:
11191       if (!args)
11192         return t;
11193       /* Fall through */
11194
11195     case PARM_DECL:
11196       {
11197         tree r = tsubst_copy (t, args, complain, in_decl);
11198
11199         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11200           /* If the original type was a reference, we'll be wrapped in
11201              the appropriate INDIRECT_REF.  */
11202           r = convert_from_reference (r);
11203         return r;
11204       }
11205
11206     case VA_ARG_EXPR:
11207       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11208                              tsubst_copy (TREE_TYPE (t), args, complain,
11209                                           in_decl));
11210
11211     case OFFSETOF_EXPR:
11212       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11213
11214     case TRAIT_EXPR:
11215       {
11216         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11217                                   complain, in_decl);
11218
11219         tree type2 = TRAIT_EXPR_TYPE2 (t);
11220         if (type2)
11221           type2 = tsubst_copy (type2, args, complain, in_decl);
11222         
11223         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11224       }
11225
11226     case STMT_EXPR:
11227       {
11228         tree old_stmt_expr = cur_stmt_expr;
11229         tree stmt_expr = begin_stmt_expr ();
11230
11231         cur_stmt_expr = stmt_expr;
11232         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11233                      integral_constant_expression_p);
11234         stmt_expr = finish_stmt_expr (stmt_expr, false);
11235         cur_stmt_expr = old_stmt_expr;
11236
11237         return stmt_expr;
11238       }
11239
11240     case CONST_DECL:
11241       t = tsubst_copy (t, args, complain, in_decl);
11242       /* As in finish_id_expression, we resolve enumeration constants
11243          to their underlying values.  */
11244       if (TREE_CODE (t) == CONST_DECL)
11245         {
11246           used_types_insert (TREE_TYPE (t));
11247           return DECL_INITIAL (t);
11248         }
11249       return t;
11250
11251     default:
11252       /* Handle Objective-C++ constructs, if appropriate.  */
11253       {
11254         tree subst
11255           = objcp_tsubst_copy_and_build (t, args, complain,
11256                                          in_decl, /*function_p=*/false);
11257         if (subst)
11258           return subst;
11259       }
11260       return tsubst_copy (t, args, complain, in_decl);
11261     }
11262
11263 #undef RECUR
11264 }
11265
11266 /* Verify that the instantiated ARGS are valid. For type arguments,
11267    make sure that the type's linkage is ok. For non-type arguments,
11268    make sure they are constants if they are integral or enumerations.
11269    Emit an error under control of COMPLAIN, and return TRUE on error.  */
11270
11271 static bool
11272 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
11273 {
11274   int ix, len = DECL_NTPARMS (tmpl);
11275   bool result = false;
11276
11277   for (ix = 0; ix != len; ix++)
11278     {
11279       tree t = TREE_VEC_ELT (args, ix);
11280
11281       if (TYPE_P (t))
11282         {
11283           /* [basic.link]: A name with no linkage (notably, the name
11284              of a class or enumeration declared in a local scope)
11285              shall not be used to declare an entity with linkage.
11286              This implies that names with no linkage cannot be used as
11287              template arguments.  */
11288           tree nt = no_linkage_check (t, /*relaxed_p=*/false);
11289
11290           if (nt)
11291             {
11292               /* DR 488 makes use of a type with no linkage cause
11293                  type deduction to fail.  */
11294               if (complain & tf_error)
11295                 {
11296                   if (TYPE_ANONYMOUS_P (nt))
11297                     error ("%qT is/uses anonymous type", t);
11298                   else
11299                     error ("template argument for %qD uses local type %qT",
11300                            tmpl, t);
11301                 }
11302               result = true;
11303             }
11304           /* In order to avoid all sorts of complications, we do not
11305              allow variably-modified types as template arguments.  */
11306           else if (variably_modified_type_p (t, NULL_TREE))
11307             {
11308               if (complain & tf_error)
11309                 error ("%qT is a variably modified type", t);
11310               result = true;
11311             }
11312         }
11313       /* A non-type argument of integral or enumerated type must be a
11314          constant.  */
11315       else if (TREE_TYPE (t)
11316                && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
11317                && !TREE_CONSTANT (t))
11318         {
11319           if (complain & tf_error)
11320             error ("integral expression %qE is not constant", t);
11321           result = true;
11322         }
11323     }
11324   if (result && (complain & tf_error))
11325     error ("  trying to instantiate %qD", tmpl);
11326   return result;
11327 }
11328
11329 /* Instantiate the indicated variable or function template TMPL with
11330    the template arguments in TARG_PTR.  */
11331
11332 tree
11333 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
11334 {
11335   tree fndecl;
11336   tree gen_tmpl;
11337   tree spec;
11338   HOST_WIDE_INT saved_processing_template_decl;
11339
11340   if (tmpl == error_mark_node)
11341     return error_mark_node;
11342
11343   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
11344
11345   /* If this function is a clone, handle it specially.  */
11346   if (DECL_CLONED_FUNCTION_P (tmpl))
11347     {
11348       tree spec;
11349       tree clone;
11350
11351       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
11352                                    complain);
11353       if (spec == error_mark_node)
11354         return error_mark_node;
11355
11356       /* Look for the clone.  */
11357       FOR_EACH_CLONE (clone, spec)
11358         if (DECL_NAME (clone) == DECL_NAME (tmpl))
11359           return clone;
11360       /* We should always have found the clone by now.  */
11361       gcc_unreachable ();
11362       return NULL_TREE;
11363     }
11364
11365   /* Check to see if we already have this specialization.  */
11366   spec = retrieve_specialization (tmpl, targ_ptr,
11367                                   /*class_specializations_p=*/false);
11368   if (spec != NULL_TREE)
11369     return spec;
11370
11371   gen_tmpl = most_general_template (tmpl);
11372   if (tmpl != gen_tmpl)
11373     {
11374       /* The TMPL is a partial instantiation.  To get a full set of
11375          arguments we must add the arguments used to perform the
11376          partial instantiation.  */
11377       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
11378                                               targ_ptr);
11379
11380       /* Check to see if we already have this specialization.  */
11381       spec = retrieve_specialization (gen_tmpl, targ_ptr,
11382                                       /*class_specializations_p=*/false);
11383       if (spec != NULL_TREE)
11384         return spec;
11385     }
11386
11387   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
11388                                complain))
11389     return error_mark_node;
11390
11391   /* We are building a FUNCTION_DECL, during which the access of its
11392      parameters and return types have to be checked.  However this
11393      FUNCTION_DECL which is the desired context for access checking
11394      is not built yet.  We solve this chicken-and-egg problem by
11395      deferring all checks until we have the FUNCTION_DECL.  */
11396   push_deferring_access_checks (dk_deferred);
11397
11398   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
11399      (because, for example, we have encountered a non-dependent
11400      function call in the body of a template function and must now
11401      determine which of several overloaded functions will be called),
11402      within the instantiation itself we are not processing a
11403      template.  */  
11404   saved_processing_template_decl = processing_template_decl;
11405   processing_template_decl = 0;
11406   /* Substitute template parameters to obtain the specialization.  */
11407   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
11408                    targ_ptr, complain, gen_tmpl);
11409   processing_template_decl = saved_processing_template_decl;
11410   if (fndecl == error_mark_node)
11411     return error_mark_node;
11412
11413   /* Now we know the specialization, compute access previously
11414      deferred.  */
11415   push_access_scope (fndecl);
11416   perform_deferred_access_checks ();
11417   pop_access_scope (fndecl);
11418   pop_deferring_access_checks ();
11419
11420   /* The DECL_TI_TEMPLATE should always be the immediate parent
11421      template, not the most general template.  */
11422   DECL_TI_TEMPLATE (fndecl) = tmpl;
11423
11424   /* If we've just instantiated the main entry point for a function,
11425      instantiate all the alternate entry points as well.  We do this
11426      by cloning the instantiation of the main entry point, not by
11427      instantiating the template clones.  */
11428   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
11429     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
11430
11431   return fndecl;
11432 }
11433
11434 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
11435    arguments that are being used when calling it.  TARGS is a vector
11436    into which the deduced template arguments are placed.
11437
11438    Return zero for success, 2 for an incomplete match that doesn't resolve
11439    all the types, and 1 for complete failure.  An error message will be
11440    printed only for an incomplete match.
11441
11442    If FN is a conversion operator, or we are trying to produce a specific
11443    specialization, RETURN_TYPE is the return type desired.
11444
11445    The EXPLICIT_TARGS are explicit template arguments provided via a
11446    template-id.
11447
11448    The parameter STRICT is one of:
11449
11450    DEDUCE_CALL:
11451      We are deducing arguments for a function call, as in
11452      [temp.deduct.call].
11453
11454    DEDUCE_CONV:
11455      We are deducing arguments for a conversion function, as in
11456      [temp.deduct.conv].
11457
11458    DEDUCE_EXACT:
11459      We are deducing arguments when doing an explicit instantiation
11460      as in [temp.explicit], when determining an explicit specialization
11461      as in [temp.expl.spec], or when taking the address of a function
11462      template, as in [temp.deduct.funcaddr].  */
11463
11464 int
11465 fn_type_unification (tree fn,
11466                      tree explicit_targs,
11467                      tree targs,
11468                      tree args,
11469                      tree return_type,
11470                      unification_kind_t strict,
11471                      int flags)
11472 {
11473   tree parms;
11474   tree fntype;
11475   int result;
11476   bool incomplete_argument_packs_p = false;
11477
11478   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
11479
11480   fntype = TREE_TYPE (fn);
11481   if (explicit_targs)
11482     {
11483       /* [temp.deduct]
11484
11485          The specified template arguments must match the template
11486          parameters in kind (i.e., type, nontype, template), and there
11487          must not be more arguments than there are parameters;
11488          otherwise type deduction fails.
11489
11490          Nontype arguments must match the types of the corresponding
11491          nontype template parameters, or must be convertible to the
11492          types of the corresponding nontype parameters as specified in
11493          _temp.arg.nontype_, otherwise type deduction fails.
11494
11495          All references in the function type of the function template
11496          to the corresponding template parameters are replaced by the
11497          specified template argument values.  If a substitution in a
11498          template parameter or in the function type of the function
11499          template results in an invalid type, type deduction fails.  */
11500       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
11501       int i, len = TREE_VEC_LENGTH (tparms);
11502       tree converted_args;
11503       bool incomplete = false;
11504
11505       if (explicit_targs == error_mark_node)
11506         return 1;
11507
11508       converted_args
11509         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
11510                                   /*require_all_args=*/false,
11511                                   /*use_default_args=*/false));
11512       if (converted_args == error_mark_node)
11513         return 1;
11514
11515       /* Substitute the explicit args into the function type.  This is
11516          necessary so that, for instance, explicitly declared function
11517          arguments can match null pointed constants.  If we were given
11518          an incomplete set of explicit args, we must not do semantic
11519          processing during substitution as we could create partial
11520          instantiations.  */
11521       for (i = 0; i < len; i++)
11522         {
11523           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
11524           bool parameter_pack = false;
11525
11526           /* Dig out the actual parm.  */
11527           if (TREE_CODE (parm) == TYPE_DECL
11528               || TREE_CODE (parm) == TEMPLATE_DECL)
11529             {
11530               parm = TREE_TYPE (parm);
11531               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
11532             }
11533           else if (TREE_CODE (parm) == PARM_DECL)
11534             {
11535               parm = DECL_INITIAL (parm);
11536               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
11537             }
11538
11539           if (parameter_pack)
11540             {
11541               int level, idx;
11542               tree targ;
11543               template_parm_level_and_index (parm, &level, &idx);
11544
11545               /* Mark the argument pack as "incomplete". We could
11546                  still deduce more arguments during unification.  */
11547               targ = TMPL_ARG (converted_args, level, idx);
11548               if (targ)
11549                 {
11550                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
11551                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
11552                     = ARGUMENT_PACK_ARGS (targ);
11553                 }
11554
11555               /* We have some incomplete argument packs.  */
11556               incomplete_argument_packs_p = true;
11557             }
11558         }
11559
11560       if (incomplete_argument_packs_p)
11561         /* Any substitution is guaranteed to be incomplete if there
11562            are incomplete argument packs, because we can still deduce
11563            more arguments.  */
11564         incomplete = 1;
11565       else
11566         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
11567
11568       processing_template_decl += incomplete;
11569       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
11570       processing_template_decl -= incomplete;
11571
11572       if (fntype == error_mark_node)
11573         return 1;
11574
11575       /* Place the explicitly specified arguments in TARGS.  */
11576       for (i = NUM_TMPL_ARGS (converted_args); i--;)
11577         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
11578     }
11579
11580   /* Never do unification on the 'this' parameter.  */
11581   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
11582
11583   if (return_type)
11584     {
11585       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
11586       args = tree_cons (NULL_TREE, return_type, args);
11587     }
11588
11589   /* We allow incomplete unification without an error message here
11590      because the standard doesn't seem to explicitly prohibit it.  Our
11591      callers must be ready to deal with unification failures in any
11592      event.  */
11593   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
11594                                   targs, parms, args, /*subr=*/0,
11595                                   strict, flags);
11596
11597   if (result == 0 && incomplete_argument_packs_p)
11598     {
11599       int i, len = NUM_TMPL_ARGS (targs);
11600
11601       /* Clear the "incomplete" flags on all argument packs.  */
11602       for (i = 0; i < len; i++)
11603         {
11604           tree arg = TREE_VEC_ELT (targs, i);
11605           if (ARGUMENT_PACK_P (arg))
11606             {
11607               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
11608               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
11609             }
11610         }
11611     }
11612
11613   if (result == 0)
11614     /* All is well so far.  Now, check:
11615
11616        [temp.deduct]
11617
11618        When all template arguments have been deduced, all uses of
11619        template parameters in nondeduced contexts are replaced with
11620        the corresponding deduced argument values.  If the
11621        substitution results in an invalid type, as described above,
11622        type deduction fails.  */
11623     if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
11624         == error_mark_node)
11625       return 1;
11626
11627   return result;
11628 }
11629
11630 /* Adjust types before performing type deduction, as described in
11631    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
11632    sections are symmetric.  PARM is the type of a function parameter
11633    or the return type of the conversion function.  ARG is the type of
11634    the argument passed to the call, or the type of the value
11635    initialized with the result of the conversion function.
11636    ARG_EXPR is the original argument expression, which may be null.  */
11637
11638 static int
11639 maybe_adjust_types_for_deduction (unification_kind_t strict,
11640                                   tree* parm,
11641                                   tree* arg,
11642                                   tree arg_expr)
11643 {
11644   int result = 0;
11645
11646   switch (strict)
11647     {
11648     case DEDUCE_CALL:
11649       break;
11650
11651     case DEDUCE_CONV:
11652       {
11653         /* Swap PARM and ARG throughout the remainder of this
11654            function; the handling is precisely symmetric since PARM
11655            will initialize ARG rather than vice versa.  */
11656         tree* temp = parm;
11657         parm = arg;
11658         arg = temp;
11659         break;
11660       }
11661
11662     case DEDUCE_EXACT:
11663       /* There is nothing to do in this case.  */
11664       return 0;
11665
11666     default:
11667       gcc_unreachable ();
11668     }
11669
11670   if (TREE_CODE (*parm) != REFERENCE_TYPE)
11671     {
11672       /* [temp.deduct.call]
11673
11674          If P is not a reference type:
11675
11676          --If A is an array type, the pointer type produced by the
11677          array-to-pointer standard conversion (_conv.array_) is
11678          used in place of A for type deduction; otherwise,
11679
11680          --If A is a function type, the pointer type produced by
11681          the function-to-pointer standard conversion
11682          (_conv.func_) is used in place of A for type deduction;
11683          otherwise,
11684
11685          --If A is a cv-qualified type, the top level
11686          cv-qualifiers of A's type are ignored for type
11687          deduction.  */
11688       if (TREE_CODE (*arg) == ARRAY_TYPE)
11689         *arg = build_pointer_type (TREE_TYPE (*arg));
11690       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
11691         *arg = build_pointer_type (*arg);
11692       else
11693         *arg = TYPE_MAIN_VARIANT (*arg);
11694     }
11695
11696   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
11697      of the form T&&, where T is a template parameter, and the argument
11698      is an lvalue, T is deduced as A& */
11699   if (TREE_CODE (*parm) == REFERENCE_TYPE
11700       && TYPE_REF_IS_RVALUE (*parm)
11701       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
11702       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
11703       && arg_expr && real_lvalue_p (arg_expr))
11704     *arg = build_reference_type (*arg);
11705
11706   /* [temp.deduct.call]
11707
11708      If P is a cv-qualified type, the top level cv-qualifiers
11709      of P's type are ignored for type deduction.  If P is a
11710      reference type, the type referred to by P is used for
11711      type deduction.  */
11712   *parm = TYPE_MAIN_VARIANT (*parm);
11713   if (TREE_CODE (*parm) == REFERENCE_TYPE)
11714     {
11715       *parm = TREE_TYPE (*parm);
11716       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
11717     }
11718
11719   /* DR 322. For conversion deduction, remove a reference type on parm
11720      too (which has been swapped into ARG).  */
11721   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
11722     *arg = TREE_TYPE (*arg);
11723
11724   return result;
11725 }
11726
11727 /* Most parms like fn_type_unification.
11728
11729    If SUBR is 1, we're being called recursively (to unify the
11730    arguments of a function or method parameter of a function
11731    template). */
11732
11733 static int
11734 type_unification_real (tree tparms,
11735                        tree targs,
11736                        tree xparms,
11737                        tree xargs,
11738                        int subr,
11739                        unification_kind_t strict,
11740                        int flags)
11741 {
11742   tree parm, arg, arg_expr;
11743   int i;
11744   int ntparms = TREE_VEC_LENGTH (tparms);
11745   int sub_strict;
11746   int saw_undeduced = 0;
11747   tree parms, args;
11748
11749   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
11750   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
11751   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
11752   gcc_assert (ntparms > 0);
11753
11754   switch (strict)
11755     {
11756     case DEDUCE_CALL:
11757       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
11758                     | UNIFY_ALLOW_DERIVED);
11759       break;
11760
11761     case DEDUCE_CONV:
11762       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
11763       break;
11764
11765     case DEDUCE_EXACT:
11766       sub_strict = UNIFY_ALLOW_NONE;
11767       break;
11768
11769     default:
11770       gcc_unreachable ();
11771     }
11772
11773  again:
11774   parms = xparms;
11775   args = xargs;
11776
11777   while (parms && parms != void_list_node
11778          && args && args != void_list_node)
11779     {
11780       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
11781         break;
11782
11783       parm = TREE_VALUE (parms);
11784       parms = TREE_CHAIN (parms);
11785       arg = TREE_VALUE (args);
11786       args = TREE_CHAIN (args);
11787       arg_expr = NULL;
11788
11789       if (arg == error_mark_node)
11790         return 1;
11791       if (arg == unknown_type_node)
11792         /* We can't deduce anything from this, but we might get all the
11793            template args from other function args.  */
11794         continue;
11795
11796       /* Conversions will be performed on a function argument that
11797          corresponds with a function parameter that contains only
11798          non-deducible template parameters and explicitly specified
11799          template parameters.  */
11800       if (!uses_template_parms (parm))
11801         {
11802           tree type;
11803
11804           if (!TYPE_P (arg))
11805             type = TREE_TYPE (arg);
11806           else
11807             type = arg;
11808
11809           if (same_type_p (parm, type))
11810             continue;
11811           if (strict != DEDUCE_EXACT
11812               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
11813                                   flags))
11814             continue;
11815
11816           return 1;
11817         }
11818
11819       if (!TYPE_P (arg))
11820         {
11821           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
11822           if (type_unknown_p (arg))
11823             {
11824               /* [temp.deduct.type] 
11825
11826                  A template-argument can be deduced from a pointer to
11827                  function or pointer to member function argument if
11828                  the set of overloaded functions does not contain
11829                  function templates and at most one of a set of
11830                  overloaded functions provides a unique match.  */
11831               if (resolve_overloaded_unification
11832                   (tparms, targs, parm, arg, strict, sub_strict))
11833                 continue;
11834
11835               return 1;
11836             }
11837           arg_expr = arg;
11838           arg = unlowered_expr_type (arg);
11839           if (arg == error_mark_node)
11840             return 1;
11841         }
11842
11843       {
11844         int arg_strict = sub_strict;
11845
11846         if (!subr)
11847           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
11848                                                           arg_expr);
11849
11850         if (unify (tparms, targs, parm, arg, arg_strict))
11851           return 1;
11852       }
11853     }
11854
11855
11856   if (parms 
11857       && parms != void_list_node
11858       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
11859     {
11860       /* Unify the remaining arguments with the pack expansion type.  */
11861       tree argvec;
11862       tree parmvec = make_tree_vec (1);
11863       int len = 0;
11864       tree t;
11865
11866       /* Count the number of arguments that remain.  */
11867       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
11868         len++;
11869         
11870       /* Allocate a TREE_VEC and copy in all of the arguments */ 
11871       argvec = make_tree_vec (len);
11872       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
11873         {
11874           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
11875           ++i;
11876         }
11877
11878       /* Copy the parameter into parmvec.  */
11879       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
11880       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
11881                                 /*call_args_p=*/true, /*subr=*/subr))
11882         return 1;
11883
11884       /* Advance to the end of the list of parameters.  */
11885       parms = TREE_CHAIN (parms);
11886     }
11887
11888   /* Fail if we've reached the end of the parm list, and more args
11889      are present, and the parm list isn't variadic.  */
11890   if (args && args != void_list_node && parms == void_list_node)
11891     return 1;
11892   /* Fail if parms are left and they don't have default values.  */
11893   if (parms && parms != void_list_node
11894       && TREE_PURPOSE (parms) == NULL_TREE)
11895     return 1;
11896
11897   if (!subr)
11898     for (i = 0; i < ntparms; i++)
11899       if (!TREE_VEC_ELT (targs, i))
11900         {
11901           tree tparm;
11902
11903           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
11904             continue;
11905
11906           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
11907
11908           /* If this is an undeduced nontype parameter that depends on
11909              a type parameter, try another pass; its type may have been
11910              deduced from a later argument than the one from which
11911              this parameter can be deduced.  */
11912           if (TREE_CODE (tparm) == PARM_DECL
11913               && uses_template_parms (TREE_TYPE (tparm))
11914               && !saw_undeduced++)
11915             goto again;
11916
11917           /* Core issue #226 (C++0x) [temp.deduct]:
11918
11919                If a template argument has not been deduced, its
11920                default template argument, if any, is used. 
11921
11922              When we are in C++98 mode, TREE_PURPOSE will either
11923              be NULL_TREE or ERROR_MARK_NODE, so we do not need
11924              to explicitly check cxx_dialect here.  */
11925           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
11926             {
11927               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
11928                                  targs, tf_none, NULL_TREE);
11929               if (arg == error_mark_node)
11930                 return 1;
11931               else
11932                 {
11933                   TREE_VEC_ELT (targs, i) = arg;
11934                   continue;
11935                 }
11936             }
11937
11938           /* If the type parameter is a parameter pack, then it will
11939              be deduced to an empty parameter pack.  */
11940           if (template_parameter_pack_p (tparm))
11941             {
11942               tree arg;
11943
11944               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
11945                 {
11946                   arg = make_node (NONTYPE_ARGUMENT_PACK);
11947                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
11948                   TREE_CONSTANT (arg) = 1;
11949                 }
11950               else
11951                 arg = make_node (TYPE_ARGUMENT_PACK);
11952
11953               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
11954
11955               TREE_VEC_ELT (targs, i) = arg;
11956               continue;
11957             }
11958
11959           return 2;
11960         }
11961
11962   return 0;
11963 }
11964
11965 /* Subroutine of type_unification_real.  Args are like the variables
11966    at the call site.  ARG is an overloaded function (or template-id);
11967    we try deducing template args from each of the overloads, and if
11968    only one succeeds, we go with that.  Modifies TARGS and returns
11969    true on success.  */
11970
11971 static bool
11972 resolve_overloaded_unification (tree tparms,
11973                                 tree targs,
11974                                 tree parm,
11975                                 tree arg,
11976                                 unification_kind_t strict,
11977                                 int sub_strict)
11978 {
11979   tree tempargs = copy_node (targs);
11980   int good = 0;
11981   bool addr_p;
11982
11983   if (TREE_CODE (arg) == ADDR_EXPR)
11984     {
11985       arg = TREE_OPERAND (arg, 0);
11986       addr_p = true;
11987     }
11988   else
11989     addr_p = false;
11990
11991   if (TREE_CODE (arg) == COMPONENT_REF)
11992     /* Handle `&x' where `x' is some static or non-static member
11993        function name.  */
11994     arg = TREE_OPERAND (arg, 1);
11995
11996   if (TREE_CODE (arg) == OFFSET_REF)
11997     arg = TREE_OPERAND (arg, 1);
11998
11999   /* Strip baselink information.  */
12000   if (BASELINK_P (arg))
12001     arg = BASELINK_FUNCTIONS (arg);
12002
12003   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12004     {
12005       /* If we got some explicit template args, we need to plug them into
12006          the affected templates before we try to unify, in case the
12007          explicit args will completely resolve the templates in question.  */
12008
12009       tree expl_subargs = TREE_OPERAND (arg, 1);
12010       arg = TREE_OPERAND (arg, 0);
12011
12012       for (; arg; arg = OVL_NEXT (arg))
12013         {
12014           tree fn = OVL_CURRENT (arg);
12015           tree subargs, elem;
12016
12017           if (TREE_CODE (fn) != TEMPLATE_DECL)
12018             continue;
12019
12020           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12021                                   expl_subargs, /*check_ret=*/false);
12022           if (subargs)
12023             {
12024               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12025               good += try_one_overload (tparms, targs, tempargs, parm,
12026                                         elem, strict, sub_strict, addr_p);
12027             }
12028         }
12029     }
12030   else if (TREE_CODE (arg) != OVERLOAD
12031            && TREE_CODE (arg) != FUNCTION_DECL)
12032     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12033        -- but the deduction does not succeed because the expression is
12034        not just the function on its own.  */
12035     return false;
12036   else
12037     for (; arg; arg = OVL_NEXT (arg))
12038       good += try_one_overload (tparms, targs, tempargs, parm,
12039                                 TREE_TYPE (OVL_CURRENT (arg)),
12040                                 strict, sub_strict, addr_p);
12041
12042   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12043      to function or pointer to member function argument if the set of
12044      overloaded functions does not contain function templates and at most
12045      one of a set of overloaded functions provides a unique match.
12046
12047      So if we found multiple possibilities, we return success but don't
12048      deduce anything.  */
12049
12050   if (good == 1)
12051     {
12052       int i = TREE_VEC_LENGTH (targs);
12053       for (; i--; )
12054         if (TREE_VEC_ELT (tempargs, i))
12055           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12056     }
12057   if (good)
12058     return true;
12059
12060   return false;
12061 }
12062
12063 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12064    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12065    different overloads deduce different arguments for a given parm.
12066    ADDR_P is true if the expression for which deduction is being
12067    performed was of the form "& fn" rather than simply "fn".
12068
12069    Returns 1 on success.  */
12070
12071 static int
12072 try_one_overload (tree tparms,
12073                   tree orig_targs,
12074                   tree targs,
12075                   tree parm,
12076                   tree arg,
12077                   unification_kind_t strict,
12078                   int sub_strict,
12079                   bool addr_p)
12080 {
12081   int nargs;
12082   tree tempargs;
12083   int i;
12084
12085   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12086      to function or pointer to member function argument if the set of
12087      overloaded functions does not contain function templates and at most
12088      one of a set of overloaded functions provides a unique match.
12089
12090      So if this is a template, just return success.  */
12091
12092   if (uses_template_parms (arg))
12093     return 1;
12094
12095   if (TREE_CODE (arg) == METHOD_TYPE)
12096     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12097   else if (addr_p)
12098     arg = build_pointer_type (arg);
12099
12100   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12101
12102   /* We don't copy orig_targs for this because if we have already deduced
12103      some template args from previous args, unify would complain when we
12104      try to deduce a template parameter for the same argument, even though
12105      there isn't really a conflict.  */
12106   nargs = TREE_VEC_LENGTH (targs);
12107   tempargs = make_tree_vec (nargs);
12108
12109   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12110     return 0;
12111
12112   /* First make sure we didn't deduce anything that conflicts with
12113      explicitly specified args.  */
12114   for (i = nargs; i--; )
12115     {
12116       tree elt = TREE_VEC_ELT (tempargs, i);
12117       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12118
12119       if (!elt)
12120         /*NOP*/;
12121       else if (uses_template_parms (elt))
12122         /* Since we're unifying against ourselves, we will fill in
12123            template args used in the function parm list with our own
12124            template parms.  Discard them.  */
12125         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12126       else if (oldelt && !template_args_equal (oldelt, elt))
12127         return 0;
12128     }
12129
12130   for (i = nargs; i--; )
12131     {
12132       tree elt = TREE_VEC_ELT (tempargs, i);
12133
12134       if (elt)
12135         TREE_VEC_ELT (targs, i) = elt;
12136     }
12137
12138   return 1;
12139 }
12140
12141 /* PARM is a template class (perhaps with unbound template
12142    parameters).  ARG is a fully instantiated type.  If ARG can be
12143    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12144    TARGS are as for unify.  */
12145
12146 static tree
12147 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12148 {
12149   tree copy_of_targs;
12150
12151   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12152       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12153           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12154     return NULL_TREE;
12155
12156   /* We need to make a new template argument vector for the call to
12157      unify.  If we used TARGS, we'd clutter it up with the result of
12158      the attempted unification, even if this class didn't work out.
12159      We also don't want to commit ourselves to all the unifications
12160      we've already done, since unification is supposed to be done on
12161      an argument-by-argument basis.  In other words, consider the
12162      following pathological case:
12163
12164        template <int I, int J, int K>
12165        struct S {};
12166
12167        template <int I, int J>
12168        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12169
12170        template <int I, int J, int K>
12171        void f(S<I, J, K>, S<I, I, I>);
12172
12173        void g() {
12174          S<0, 0, 0> s0;
12175          S<0, 1, 2> s2;
12176
12177          f(s0, s2);
12178        }
12179
12180      Now, by the time we consider the unification involving `s2', we
12181      already know that we must have `f<0, 0, 0>'.  But, even though
12182      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
12183      because there are two ways to unify base classes of S<0, 1, 2>
12184      with S<I, I, I>.  If we kept the already deduced knowledge, we
12185      would reject the possibility I=1.  */
12186   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
12187
12188   /* If unification failed, we're done.  */
12189   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
12190              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
12191     return NULL_TREE;
12192
12193   return arg;
12194 }
12195
12196 /* Given a template type PARM and a class type ARG, find the unique
12197    base type in ARG that is an instance of PARM.  We do not examine
12198    ARG itself; only its base-classes.  If there is not exactly one
12199    appropriate base class, return NULL_TREE.  PARM may be the type of
12200    a partial specialization, as well as a plain template type.  Used
12201    by unify.  */
12202
12203 static tree
12204 get_template_base (tree tparms, tree targs, tree parm, tree arg)
12205 {
12206   tree rval = NULL_TREE;
12207   tree binfo;
12208
12209   gcc_assert (IS_AGGR_TYPE_CODE (TREE_CODE (arg)));
12210
12211   binfo = TYPE_BINFO (complete_type (arg));
12212   if (!binfo)
12213     /* The type could not be completed.  */
12214     return NULL_TREE;
12215
12216   /* Walk in inheritance graph order.  The search order is not
12217      important, and this avoids multiple walks of virtual bases.  */
12218   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
12219     {
12220       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
12221
12222       if (r)
12223         {
12224           /* If there is more than one satisfactory baseclass, then:
12225
12226                [temp.deduct.call]
12227
12228               If they yield more than one possible deduced A, the type
12229               deduction fails.
12230
12231              applies.  */
12232           if (rval && !same_type_p (r, rval))
12233             return NULL_TREE;
12234
12235           rval = r;
12236         }
12237     }
12238
12239   return rval;
12240 }
12241
12242 /* Returns the level of DECL, which declares a template parameter.  */
12243
12244 static int
12245 template_decl_level (tree decl)
12246 {
12247   switch (TREE_CODE (decl))
12248     {
12249     case TYPE_DECL:
12250     case TEMPLATE_DECL:
12251       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
12252
12253     case PARM_DECL:
12254       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
12255
12256     default:
12257       gcc_unreachable ();
12258     }
12259   return 0;
12260 }
12261
12262 /* Decide whether ARG can be unified with PARM, considering only the
12263    cv-qualifiers of each type, given STRICT as documented for unify.
12264    Returns nonzero iff the unification is OK on that basis.  */
12265
12266 static int
12267 check_cv_quals_for_unify (int strict, tree arg, tree parm)
12268 {
12269   int arg_quals = cp_type_quals (arg);
12270   int parm_quals = cp_type_quals (parm);
12271
12272   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12273       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12274     {
12275       /*  Although a CVR qualifier is ignored when being applied to a
12276           substituted template parameter ([8.3.2]/1 for example), that
12277           does not apply during deduction [14.8.2.4]/1, (even though
12278           that is not explicitly mentioned, [14.8.2.4]/9 indicates
12279           this).  Except when we're allowing additional CV qualifiers
12280           at the outer level [14.8.2.1]/3,1st bullet.  */
12281       if ((TREE_CODE (arg) == REFERENCE_TYPE
12282            || TREE_CODE (arg) == FUNCTION_TYPE
12283            || TREE_CODE (arg) == METHOD_TYPE)
12284           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
12285         return 0;
12286
12287       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
12288           && (parm_quals & TYPE_QUAL_RESTRICT))
12289         return 0;
12290     }
12291
12292   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12293       && (arg_quals & parm_quals) != parm_quals)
12294     return 0;
12295
12296   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
12297       && (parm_quals & arg_quals) != arg_quals)
12298     return 0;
12299
12300   return 1;
12301 }
12302
12303 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
12304 void 
12305 template_parm_level_and_index (tree parm, int* level, int* index)
12306 {
12307   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12308       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12309       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12310     {
12311       *index = TEMPLATE_TYPE_IDX (parm);
12312       *level = TEMPLATE_TYPE_LEVEL (parm);
12313     }
12314   else
12315     {
12316       *index = TEMPLATE_PARM_IDX (parm);
12317       *level = TEMPLATE_PARM_LEVEL (parm);
12318     }
12319 }
12320
12321 /* Unifies the remaining arguments in PACKED_ARGS with the pack
12322    expansion at the end of PACKED_PARMS. Returns 0 if the type
12323    deduction succeeds, 1 otherwise. STRICT is the same as in
12324    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
12325    call argument list. We'll need to adjust the arguments to make them
12326    types. SUBR tells us if this is from a recursive call to
12327    type_unification_real.  */
12328 int
12329 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
12330                       tree packed_args, int strict, bool call_args_p,
12331                       bool subr)
12332 {
12333   tree parm 
12334     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
12335   tree pattern = PACK_EXPANSION_PATTERN (parm);
12336   tree pack, packs = NULL_TREE;
12337   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
12338   int len = TREE_VEC_LENGTH (packed_args);
12339
12340   /* Determine the parameter packs we will be deducing from the
12341      pattern, and record their current deductions.  */
12342   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
12343        pack; pack = TREE_CHAIN (pack))
12344     {
12345       tree parm_pack = TREE_VALUE (pack);
12346       int idx, level;
12347
12348       /* Determine the index and level of this parameter pack.  */
12349       template_parm_level_and_index (parm_pack, &level, &idx);
12350
12351       /* Keep track of the parameter packs and their corresponding
12352          argument packs.  */
12353       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
12354       TREE_TYPE (packs) = make_tree_vec (len - start);
12355     }
12356   
12357   /* Loop through all of the arguments that have not yet been
12358      unified and unify each with the pattern.  */
12359   for (i = start; i < len; i++)
12360     {
12361       tree parm = pattern;
12362
12363       /* For each parameter pack, clear out the deduced value so that
12364          we can deduce it again.  */
12365       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12366         {
12367           int idx, level;
12368           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12369
12370           TMPL_ARG (targs, level, idx) = NULL_TREE;
12371         }
12372
12373       /* Unify the pattern with the current argument.  */
12374       {
12375         tree arg = TREE_VEC_ELT (packed_args, i);
12376         tree arg_expr = NULL_TREE;
12377         int arg_strict = strict;
12378         bool skip_arg_p = false;
12379
12380         if (call_args_p)
12381           {
12382             int sub_strict;
12383
12384             /* This mirrors what we do in type_unification_real.  */
12385             switch (strict)
12386               {
12387               case DEDUCE_CALL:
12388                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
12389                               | UNIFY_ALLOW_MORE_CV_QUAL
12390                               | UNIFY_ALLOW_DERIVED);
12391                 break;
12392                 
12393               case DEDUCE_CONV:
12394                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12395                 break;
12396                 
12397               case DEDUCE_EXACT:
12398                 sub_strict = UNIFY_ALLOW_NONE;
12399                 break;
12400                 
12401               default:
12402                 gcc_unreachable ();
12403               }
12404
12405             if (!TYPE_P (arg))
12406               {
12407                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12408                 if (type_unknown_p (arg))
12409                   {
12410                     /* [temp.deduct.type] A template-argument can be
12411                        deduced from a pointer to function or pointer
12412                        to member function argument if the set of
12413                        overloaded functions does not contain function
12414                        templates and at most one of a set of
12415                        overloaded functions provides a unique
12416                        match.  */
12417
12418                     if (resolve_overloaded_unification
12419                         (tparms, targs, parm, arg, strict, sub_strict)
12420                         != 0)
12421                       return 1;
12422                     skip_arg_p = true;
12423                   }
12424
12425                 if (!skip_arg_p)
12426                   {
12427                     arg_expr = arg;
12428                     arg = unlowered_expr_type (arg);
12429                     if (arg == error_mark_node)
12430                       return 1;
12431                   }
12432               }
12433       
12434             arg_strict = sub_strict;
12435
12436             if (!subr)
12437               arg_strict |= 
12438                 maybe_adjust_types_for_deduction (strict, &parm, &arg, 
12439                                                   arg_expr);
12440           }
12441
12442         if (!skip_arg_p)
12443           {
12444             if (unify (tparms, targs, parm, arg, arg_strict))
12445               return 1;
12446           }
12447       }
12448
12449       /* For each parameter pack, collect the deduced value.  */
12450       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12451         {
12452           int idx, level;
12453           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12454
12455           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
12456             TMPL_ARG (targs, level, idx);
12457         }
12458     }
12459
12460   /* Verify that the results of unification with the parameter packs
12461      produce results consistent with what we've seen before, and make
12462      the deduced argument packs available.  */
12463   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12464     {
12465       tree old_pack = TREE_VALUE (pack);
12466       tree new_args = TREE_TYPE (pack);
12467
12468       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
12469         {
12470           /* Prepend the explicit arguments onto NEW_ARGS.  */
12471           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12472           tree old_args = new_args;
12473           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
12474           int len = explicit_len + TREE_VEC_LENGTH (old_args);
12475
12476           /* Copy the explicit arguments.  */
12477           new_args = make_tree_vec (len);
12478           for (i = 0; i < explicit_len; i++)
12479             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
12480
12481           /* Copy the deduced arguments.  */
12482           for (; i < len; i++)
12483             TREE_VEC_ELT (new_args, i) =
12484               TREE_VEC_ELT (old_args, i - explicit_len);
12485         }
12486
12487       if (!old_pack)
12488         {
12489           tree result;
12490           int idx, level;
12491           
12492           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12493
12494           /* Build the deduced *_ARGUMENT_PACK.  */
12495           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
12496             {
12497               result = make_node (NONTYPE_ARGUMENT_PACK);
12498               TREE_TYPE (result) = 
12499                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
12500               TREE_CONSTANT (result) = 1;
12501             }
12502           else
12503             result = make_node (TYPE_ARGUMENT_PACK);
12504
12505           SET_ARGUMENT_PACK_ARGS (result, new_args);
12506
12507           /* Note the deduced argument packs for this parameter
12508              pack.  */
12509           TMPL_ARG (targs, level, idx) = result;
12510         }
12511       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
12512                && (ARGUMENT_PACK_ARGS (old_pack) 
12513                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
12514         {
12515           /* We only had the explicitly-provided arguments before, but
12516              now we have a complete set of arguments.  */
12517           int idx, level;
12518           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12519           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12520
12521           /* Keep the original deduced argument pack.  */
12522           TMPL_ARG (targs, level, idx) = old_pack;
12523
12524           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
12525           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
12526           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
12527         }
12528       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
12529                                     new_args))
12530         /* Inconsistent unification of this parameter pack.  */
12531         return 1;
12532       else
12533         {
12534           int idx, level;
12535           
12536           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12537
12538           /* Keep the original deduced argument pack.  */
12539           TMPL_ARG (targs, level, idx) = old_pack;
12540         }
12541     }
12542
12543   return 0;
12544 }
12545
12546 /* Deduce the value of template parameters.  TPARMS is the (innermost)
12547    set of template parameters to a template.  TARGS is the bindings
12548    for those template parameters, as determined thus far; TARGS may
12549    include template arguments for outer levels of template parameters
12550    as well.  PARM is a parameter to a template function, or a
12551    subcomponent of that parameter; ARG is the corresponding argument.
12552    This function attempts to match PARM with ARG in a manner
12553    consistent with the existing assignments in TARGS.  If more values
12554    are deduced, then TARGS is updated.
12555
12556    Returns 0 if the type deduction succeeds, 1 otherwise.  The
12557    parameter STRICT is a bitwise or of the following flags:
12558
12559      UNIFY_ALLOW_NONE:
12560        Require an exact match between PARM and ARG.
12561      UNIFY_ALLOW_MORE_CV_QUAL:
12562        Allow the deduced ARG to be more cv-qualified (by qualification
12563        conversion) than ARG.
12564      UNIFY_ALLOW_LESS_CV_QUAL:
12565        Allow the deduced ARG to be less cv-qualified than ARG.
12566      UNIFY_ALLOW_DERIVED:
12567        Allow the deduced ARG to be a template base class of ARG,
12568        or a pointer to a template base class of the type pointed to by
12569        ARG.
12570      UNIFY_ALLOW_INTEGER:
12571        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
12572        case for more information.
12573      UNIFY_ALLOW_OUTER_LEVEL:
12574        This is the outermost level of a deduction. Used to determine validity
12575        of qualification conversions. A valid qualification conversion must
12576        have const qualified pointers leading up to the inner type which
12577        requires additional CV quals, except at the outer level, where const
12578        is not required [conv.qual]. It would be normal to set this flag in
12579        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
12580      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
12581        This is the outermost level of a deduction, and PARM can be more CV
12582        qualified at this point.
12583      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
12584        This is the outermost level of a deduction, and PARM can be less CV
12585        qualified at this point.  */
12586
12587 static int
12588 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
12589 {
12590   int idx;
12591   tree targ;
12592   tree tparm;
12593   int strict_in = strict;
12594
12595   /* I don't think this will do the right thing with respect to types.
12596      But the only case I've seen it in so far has been array bounds, where
12597      signedness is the only information lost, and I think that will be
12598      okay.  */
12599   while (TREE_CODE (parm) == NOP_EXPR)
12600     parm = TREE_OPERAND (parm, 0);
12601
12602   if (arg == error_mark_node)
12603     return 1;
12604   if (arg == unknown_type_node)
12605     /* We can't deduce anything from this, but we might get all the
12606        template args from other function args.  */
12607     return 0;
12608
12609   /* If PARM uses template parameters, then we can't bail out here,
12610      even if ARG == PARM, since we won't record unifications for the
12611      template parameters.  We might need them if we're trying to
12612      figure out which of two things is more specialized.  */
12613   if (arg == parm && !uses_template_parms (parm))
12614     return 0;
12615
12616   /* Immediately reject some pairs that won't unify because of
12617      cv-qualification mismatches.  */
12618   if (TREE_CODE (arg) == TREE_CODE (parm)
12619       && TYPE_P (arg)
12620       /* It is the elements of the array which hold the cv quals of an array
12621          type, and the elements might be template type parms. We'll check
12622          when we recurse.  */
12623       && TREE_CODE (arg) != ARRAY_TYPE
12624       /* We check the cv-qualifiers when unifying with template type
12625          parameters below.  We want to allow ARG `const T' to unify with
12626          PARM `T' for example, when computing which of two templates
12627          is more specialized, for example.  */
12628       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
12629       && !check_cv_quals_for_unify (strict_in, arg, parm))
12630     return 1;
12631
12632   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
12633       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
12634     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
12635   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
12636   strict &= ~UNIFY_ALLOW_DERIVED;
12637   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12638   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
12639
12640   switch (TREE_CODE (parm))
12641     {
12642     case TYPENAME_TYPE:
12643     case SCOPE_REF:
12644     case UNBOUND_CLASS_TEMPLATE:
12645       /* In a type which contains a nested-name-specifier, template
12646          argument values cannot be deduced for template parameters used
12647          within the nested-name-specifier.  */
12648       return 0;
12649
12650     case TEMPLATE_TYPE_PARM:
12651     case TEMPLATE_TEMPLATE_PARM:
12652     case BOUND_TEMPLATE_TEMPLATE_PARM:
12653       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
12654       if (tparm == error_mark_node)
12655         return 1;
12656
12657       if (TEMPLATE_TYPE_LEVEL (parm)
12658           != template_decl_level (tparm))
12659         /* The PARM is not one we're trying to unify.  Just check
12660            to see if it matches ARG.  */
12661         return (TREE_CODE (arg) == TREE_CODE (parm)
12662                 && same_type_p (parm, arg)) ? 0 : 1;
12663       idx = TEMPLATE_TYPE_IDX (parm);
12664       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
12665       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
12666
12667       /* Check for mixed types and values.  */
12668       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12669            && TREE_CODE (tparm) != TYPE_DECL)
12670           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12671               && TREE_CODE (tparm) != TEMPLATE_DECL))
12672         return 1;
12673
12674       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12675         {
12676           /* ARG must be constructed from a template class or a template
12677              template parameter.  */
12678           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
12679               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
12680             return 1;
12681
12682           {
12683             tree parmvec = TYPE_TI_ARGS (parm);
12684             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
12685             tree argtmplvec
12686               = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_TI_TEMPLATE (arg));
12687             int i;
12688
12689             /* The resolution to DR150 makes clear that default
12690                arguments for an N-argument may not be used to bind T
12691                to a template template parameter with fewer than N
12692                parameters.  It is not safe to permit the binding of
12693                default arguments as an extension, as that may change
12694                the meaning of a conforming program.  Consider:
12695
12696                   struct Dense { static const unsigned int dim = 1; };
12697
12698                   template <template <typename> class View,
12699                             typename Block>
12700                   void operator+(float, View<Block> const&);
12701
12702                   template <typename Block,
12703                             unsigned int Dim = Block::dim>
12704                   struct Lvalue_proxy { operator float() const; };
12705
12706                   void
12707                   test_1d (void) {
12708                     Lvalue_proxy<Dense> p;
12709                     float b;
12710                     b + p;
12711                   }
12712
12713               Here, if Lvalue_proxy is permitted to bind to View, then
12714               the global operator+ will be used; if they are not, the
12715               Lvalue_proxy will be converted to float.  */
12716             if (coerce_template_parms (argtmplvec, parmvec,
12717                                        TYPE_TI_TEMPLATE (parm),
12718                                        tf_none,
12719                                        /*require_all_args=*/true,
12720                                        /*use_default_args=*/false)
12721                 == error_mark_node)
12722               return 1;
12723
12724             /* Deduce arguments T, i from TT<T> or TT<i>.
12725                We check each element of PARMVEC and ARGVEC individually
12726                rather than the whole TREE_VEC since they can have
12727                different number of elements.  */
12728
12729             for (i = 0; i < TREE_VEC_LENGTH (parmvec); ++i)
12730               {
12731                 if (unify (tparms, targs,
12732                            TREE_VEC_ELT (parmvec, i),
12733                            TREE_VEC_ELT (argvec, i),
12734                            UNIFY_ALLOW_NONE))
12735                   return 1;
12736               }
12737           }
12738           arg = TYPE_TI_TEMPLATE (arg);
12739
12740           /* Fall through to deduce template name.  */
12741         }
12742
12743       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12744           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12745         {
12746           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
12747
12748           /* Simple cases: Value already set, does match or doesn't.  */
12749           if (targ != NULL_TREE && template_args_equal (targ, arg))
12750             return 0;
12751           else if (targ)
12752             return 1;
12753         }
12754       else
12755         {
12756           /* If PARM is `const T' and ARG is only `int', we don't have
12757              a match unless we are allowing additional qualification.
12758              If ARG is `const int' and PARM is just `T' that's OK;
12759              that binds `const int' to `T'.  */
12760           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
12761                                          arg, parm))
12762             return 1;
12763
12764           /* Consider the case where ARG is `const volatile int' and
12765              PARM is `const T'.  Then, T should be `volatile int'.  */
12766           arg = cp_build_qualified_type_real
12767             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
12768           if (arg == error_mark_node)
12769             return 1;
12770
12771           /* Simple cases: Value already set, does match or doesn't.  */
12772           if (targ != NULL_TREE && same_type_p (targ, arg))
12773             return 0;
12774           else if (targ)
12775             return 1;
12776
12777           /* Make sure that ARG is not a variable-sized array.  (Note
12778              that were talking about variable-sized arrays (like
12779              `int[n]'), rather than arrays of unknown size (like
12780              `int[]').)  We'll get very confused by such a type since
12781              the bound of the array will not be computable in an
12782              instantiation.  Besides, such types are not allowed in
12783              ISO C++, so we can do as we please here.  */
12784           if (variably_modified_type_p (arg, NULL_TREE))
12785             return 1;
12786         }
12787
12788       /* If ARG is a parameter pack or an expansion, we cannot unify
12789          against it unless PARM is also a parameter pack.  */
12790       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
12791           && !template_parameter_pack_p (parm))
12792         return 1;
12793
12794       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
12795       return 0;
12796
12797     case TEMPLATE_PARM_INDEX:
12798       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
12799       if (tparm == error_mark_node)
12800         return 1;
12801
12802       if (TEMPLATE_PARM_LEVEL (parm)
12803           != template_decl_level (tparm))
12804         /* The PARM is not one we're trying to unify.  Just check
12805            to see if it matches ARG.  */
12806         return !(TREE_CODE (arg) == TREE_CODE (parm)
12807                  && cp_tree_equal (parm, arg));
12808
12809       idx = TEMPLATE_PARM_IDX (parm);
12810       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
12811
12812       if (targ)
12813         return !cp_tree_equal (targ, arg);
12814
12815       /* [temp.deduct.type] If, in the declaration of a function template
12816          with a non-type template-parameter, the non-type
12817          template-parameter is used in an expression in the function
12818          parameter-list and, if the corresponding template-argument is
12819          deduced, the template-argument type shall match the type of the
12820          template-parameter exactly, except that a template-argument
12821          deduced from an array bound may be of any integral type.
12822          The non-type parameter might use already deduced type parameters.  */
12823       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
12824       if (!TREE_TYPE (arg))
12825         /* Template-parameter dependent expression.  Just accept it for now.
12826            It will later be processed in convert_template_argument.  */
12827         ;
12828       else if (same_type_p (TREE_TYPE (arg), tparm))
12829         /* OK */;
12830       else if ((strict & UNIFY_ALLOW_INTEGER)
12831                && (TREE_CODE (tparm) == INTEGER_TYPE
12832                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
12833         /* Convert the ARG to the type of PARM; the deduced non-type
12834            template argument must exactly match the types of the
12835            corresponding parameter.  */
12836         arg = fold (build_nop (TREE_TYPE (parm), arg));
12837       else if (uses_template_parms (tparm))
12838         /* We haven't deduced the type of this parameter yet.  Try again
12839            later.  */
12840         return 0;
12841       else
12842         return 1;
12843
12844       /* If ARG is a parameter pack or an expansion, we cannot unify
12845          against it unless PARM is also a parameter pack.  */
12846       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
12847           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
12848         return 1;
12849
12850       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
12851       return 0;
12852
12853     case PTRMEM_CST:
12854      {
12855         /* A pointer-to-member constant can be unified only with
12856          another constant.  */
12857       if (TREE_CODE (arg) != PTRMEM_CST)
12858         return 1;
12859
12860       /* Just unify the class member. It would be useless (and possibly
12861          wrong, depending on the strict flags) to unify also
12862          PTRMEM_CST_CLASS, because we want to be sure that both parm and
12863          arg refer to the same variable, even if through different
12864          classes. For instance:
12865
12866          struct A { int x; };
12867          struct B : A { };
12868
12869          Unification of &A::x and &B::x must succeed.  */
12870       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
12871                     PTRMEM_CST_MEMBER (arg), strict);
12872      }
12873
12874     case POINTER_TYPE:
12875       {
12876         if (TREE_CODE (arg) != POINTER_TYPE)
12877           return 1;
12878
12879         /* [temp.deduct.call]
12880
12881            A can be another pointer or pointer to member type that can
12882            be converted to the deduced A via a qualification
12883            conversion (_conv.qual_).
12884
12885            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
12886            This will allow for additional cv-qualification of the
12887            pointed-to types if appropriate.  */
12888
12889         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
12890           /* The derived-to-base conversion only persists through one
12891              level of pointers.  */
12892           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
12893
12894         return unify (tparms, targs, TREE_TYPE (parm),
12895                       TREE_TYPE (arg), strict);
12896       }
12897
12898     case REFERENCE_TYPE:
12899       if (TREE_CODE (arg) != REFERENCE_TYPE)
12900         return 1;
12901       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
12902                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
12903
12904     case ARRAY_TYPE:
12905       if (TREE_CODE (arg) != ARRAY_TYPE)
12906         return 1;
12907       if ((TYPE_DOMAIN (parm) == NULL_TREE)
12908           != (TYPE_DOMAIN (arg) == NULL_TREE))
12909         return 1;
12910       if (TYPE_DOMAIN (parm) != NULL_TREE)
12911         {
12912           tree parm_max;
12913           tree arg_max;
12914           bool parm_cst;
12915           bool arg_cst;
12916
12917           /* Our representation of array types uses "N - 1" as the
12918              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
12919              not an integer constant.  We cannot unify arbitrarily
12920              complex expressions, so we eliminate the MINUS_EXPRs
12921              here.  */
12922           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
12923           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
12924           if (!parm_cst)
12925             {
12926               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
12927               parm_max = TREE_OPERAND (parm_max, 0);
12928             }
12929           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
12930           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
12931           if (!arg_cst)
12932             {
12933               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
12934                  trying to unify the type of a variable with the type
12935                  of a template parameter.  For example:
12936
12937                    template <unsigned int N>
12938                    void f (char (&) [N]);
12939                    int g(); 
12940                    void h(int i) {
12941                      char a[g(i)];
12942                      f(a); 
12943                    }
12944
12945                 Here, the type of the ARG will be "int [g(i)]", and
12946                 may be a SAVE_EXPR, etc.  */
12947               if (TREE_CODE (arg_max) != MINUS_EXPR)
12948                 return 1;
12949               arg_max = TREE_OPERAND (arg_max, 0);
12950             }
12951
12952           /* If only one of the bounds used a MINUS_EXPR, compensate
12953              by adding one to the other bound.  */
12954           if (parm_cst && !arg_cst)
12955             parm_max = fold_build2 (PLUS_EXPR,
12956                                     integer_type_node,
12957                                     parm_max,
12958                                     integer_one_node);
12959           else if (arg_cst && !parm_cst)
12960             arg_max = fold_build2 (PLUS_EXPR,
12961                                    integer_type_node,
12962                                    arg_max,
12963                                    integer_one_node);
12964
12965           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
12966             return 1;
12967         }
12968       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
12969                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
12970
12971     case REAL_TYPE:
12972     case COMPLEX_TYPE:
12973     case VECTOR_TYPE:
12974     case INTEGER_TYPE:
12975     case BOOLEAN_TYPE:
12976     case ENUMERAL_TYPE:
12977     case VOID_TYPE:
12978       if (TREE_CODE (arg) != TREE_CODE (parm))
12979         return 1;
12980
12981       /* We have already checked cv-qualification at the top of the
12982          function.  */
12983       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
12984         return 1;
12985
12986       /* As far as unification is concerned, this wins.  Later checks
12987          will invalidate it if necessary.  */
12988       return 0;
12989
12990       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
12991       /* Type INTEGER_CST can come from ordinary constant template args.  */
12992     case INTEGER_CST:
12993       while (TREE_CODE (arg) == NOP_EXPR)
12994         arg = TREE_OPERAND (arg, 0);
12995
12996       if (TREE_CODE (arg) != INTEGER_CST)
12997         return 1;
12998       return !tree_int_cst_equal (parm, arg);
12999
13000     case TREE_VEC:
13001       {
13002         int i;
13003         if (TREE_CODE (arg) != TREE_VEC)
13004           return 1;
13005         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13006           return 1;
13007         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13008           if (unify (tparms, targs,
13009                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13010                      UNIFY_ALLOW_NONE))
13011             return 1;
13012         return 0;
13013       }
13014
13015     case RECORD_TYPE:
13016     case UNION_TYPE:
13017       if (TREE_CODE (arg) != TREE_CODE (parm))
13018         return 1;
13019
13020       if (TYPE_PTRMEMFUNC_P (parm))
13021         {
13022           if (!TYPE_PTRMEMFUNC_P (arg))
13023             return 1;
13024
13025           return unify (tparms, targs,
13026                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13027                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13028                         strict);
13029         }
13030
13031       if (CLASSTYPE_TEMPLATE_INFO (parm))
13032         {
13033           tree t = NULL_TREE;
13034
13035           if (strict_in & UNIFY_ALLOW_DERIVED)
13036             {
13037               /* First, we try to unify the PARM and ARG directly.  */
13038               t = try_class_unification (tparms, targs,
13039                                          parm, arg);
13040
13041               if (!t)
13042                 {
13043                   /* Fallback to the special case allowed in
13044                      [temp.deduct.call]:
13045
13046                        If P is a class, and P has the form
13047                        template-id, then A can be a derived class of
13048                        the deduced A.  Likewise, if P is a pointer to
13049                        a class of the form template-id, A can be a
13050                        pointer to a derived class pointed to by the
13051                        deduced A.  */
13052                   t = get_template_base (tparms, targs, parm, arg);
13053
13054                   if (!t)
13055                     return 1;
13056                 }
13057             }
13058           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13059                    && (CLASSTYPE_TI_TEMPLATE (parm)
13060                        == CLASSTYPE_TI_TEMPLATE (arg)))
13061             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13062                Then, we should unify `int' and `U'.  */
13063             t = arg;
13064           else
13065             /* There's no chance of unification succeeding.  */
13066             return 1;
13067
13068           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13069                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13070         }
13071       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13072         return 1;
13073       return 0;
13074
13075     case METHOD_TYPE:
13076     case FUNCTION_TYPE:
13077       if (TREE_CODE (arg) != TREE_CODE (parm))
13078         return 1;
13079
13080       /* CV qualifications for methods can never be deduced, they must
13081          match exactly.  We need to check them explicitly here,
13082          because type_unification_real treats them as any other
13083          cvqualified parameter.  */
13084       if (TREE_CODE (parm) == METHOD_TYPE
13085           && (!check_cv_quals_for_unify
13086               (UNIFY_ALLOW_NONE,
13087                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
13088                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
13089         return 1;
13090
13091       if (unify (tparms, targs, TREE_TYPE (parm),
13092                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
13093         return 1;
13094       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
13095                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
13096                                     LOOKUP_NORMAL);
13097
13098     case OFFSET_TYPE:
13099       /* Unify a pointer to member with a pointer to member function, which
13100          deduces the type of the member as a function type. */
13101       if (TYPE_PTRMEMFUNC_P (arg))
13102         {
13103           tree method_type;
13104           tree fntype;
13105           cp_cv_quals cv_quals;
13106
13107           /* Check top-level cv qualifiers */
13108           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
13109             return 1;
13110
13111           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13112                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
13113             return 1;
13114
13115           /* Determine the type of the function we are unifying against. */
13116           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
13117           fntype =
13118             build_function_type (TREE_TYPE (method_type),
13119                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
13120
13121           /* Extract the cv-qualifiers of the member function from the
13122              implicit object parameter and place them on the function
13123              type to be restored later. */
13124           cv_quals =
13125             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
13126           fntype = build_qualified_type (fntype, cv_quals);
13127           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
13128         }
13129
13130       if (TREE_CODE (arg) != OFFSET_TYPE)
13131         return 1;
13132       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13133                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
13134         return 1;
13135       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13136                     strict);
13137
13138     case CONST_DECL:
13139       if (DECL_TEMPLATE_PARM_P (parm))
13140         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
13141       if (arg != integral_constant_value (parm))
13142         return 1;
13143       return 0;
13144
13145     case FIELD_DECL:
13146     case TEMPLATE_DECL:
13147       /* Matched cases are handled by the ARG == PARM test above.  */
13148       return 1;
13149
13150     case TYPE_ARGUMENT_PACK:
13151     case NONTYPE_ARGUMENT_PACK:
13152       {
13153         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
13154         tree packed_args = ARGUMENT_PACK_ARGS (arg);
13155         int i, len = TREE_VEC_LENGTH (packed_parms);
13156         int argslen = TREE_VEC_LENGTH (packed_args);
13157         int parm_variadic_p = 0;
13158
13159         /* Check if the parameters end in a pack, making them variadic.  */
13160         if (len > 0 
13161             && PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, len - 1)))
13162           parm_variadic_p = 1;
13163
13164         /* If we don't have enough arguments to satisfy the parameters
13165            (not counting the pack expression at the end), or we have
13166            too many arguments for a parameter list that doesn't end in
13167            a pack expression, we can't unify.  */
13168         if (argslen < (len - parm_variadic_p)
13169             || (argslen > len && !parm_variadic_p))
13170           return 1;
13171
13172         /* Unify all of the parameters that precede the (optional)
13173            pack expression.  */
13174         for (i = 0; i < len - parm_variadic_p; ++i)
13175           {
13176             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
13177                        TREE_VEC_ELT (packed_args, i), strict))
13178               return 1;
13179           }
13180
13181         if (parm_variadic_p)
13182           return unify_pack_expansion (tparms, targs, 
13183                                        packed_parms, packed_args,
13184                                        strict, /*call_args_p=*/false,
13185                                        /*subr=*/false);
13186         return 0;
13187       }
13188
13189       break;
13190
13191     case TYPEOF_TYPE:
13192     case DECLTYPE_TYPE:
13193       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
13194          nodes.  */
13195       return 0;
13196
13197     case ERROR_MARK:
13198       /* Unification fails if we hit an error node.  */
13199       return 1;
13200
13201     default:
13202       gcc_assert (EXPR_P (parm));
13203
13204       /* We must be looking at an expression.  This can happen with
13205          something like:
13206
13207            template <int I>
13208            void foo(S<I>, S<I + 2>);
13209
13210          This is a "nondeduced context":
13211
13212            [deduct.type]
13213
13214            The nondeduced contexts are:
13215
13216            --A type that is a template-id in which one or more of
13217              the template-arguments is an expression that references
13218              a template-parameter.
13219
13220          In these cases, we assume deduction succeeded, but don't
13221          actually infer any unifications.  */
13222
13223       if (!uses_template_parms (parm)
13224           && !template_args_equal (parm, arg))
13225         return 1;
13226       else
13227         return 0;
13228     }
13229 }
13230 \f
13231 /* Note that DECL can be defined in this translation unit, if
13232    required.  */
13233
13234 static void
13235 mark_definable (tree decl)
13236 {
13237   tree clone;
13238   DECL_NOT_REALLY_EXTERN (decl) = 1;
13239   FOR_EACH_CLONE (clone, decl)
13240     DECL_NOT_REALLY_EXTERN (clone) = 1;
13241 }
13242
13243 /* Called if RESULT is explicitly instantiated, or is a member of an
13244    explicitly instantiated class.  */
13245
13246 void
13247 mark_decl_instantiated (tree result, int extern_p)
13248 {
13249   SET_DECL_EXPLICIT_INSTANTIATION (result);
13250
13251   /* If this entity has already been written out, it's too late to
13252      make any modifications.  */
13253   if (TREE_ASM_WRITTEN (result))
13254     return;
13255
13256   if (TREE_CODE (result) != FUNCTION_DECL)
13257     /* The TREE_PUBLIC flag for function declarations will have been
13258        set correctly by tsubst.  */
13259     TREE_PUBLIC (result) = 1;
13260
13261   /* This might have been set by an earlier implicit instantiation.  */
13262   DECL_COMDAT (result) = 0;
13263
13264   if (extern_p)
13265     DECL_NOT_REALLY_EXTERN (result) = 0;
13266   else
13267     {
13268       mark_definable (result);
13269       /* Always make artificials weak.  */
13270       if (DECL_ARTIFICIAL (result) && flag_weak)
13271         comdat_linkage (result);
13272       /* For WIN32 we also want to put explicit instantiations in
13273          linkonce sections.  */
13274       else if (TREE_PUBLIC (result))
13275         maybe_make_one_only (result);
13276     }
13277
13278   /* If EXTERN_P, then this function will not be emitted -- unless
13279      followed by an explicit instantiation, at which point its linkage
13280      will be adjusted.  If !EXTERN_P, then this function will be
13281      emitted here.  In neither circumstance do we want
13282      import_export_decl to adjust the linkage.  */
13283   DECL_INTERFACE_KNOWN (result) = 1;
13284 }
13285
13286 /* Given two function templates PAT1 and PAT2, return:
13287
13288    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
13289    -1 if PAT2 is more specialized than PAT1.
13290    0 if neither is more specialized.
13291
13292    LEN indicates the number of parameters we should consider
13293    (defaulted parameters should not be considered).
13294
13295    The 1998 std underspecified function template partial ordering, and
13296    DR214 addresses the issue.  We take pairs of arguments, one from
13297    each of the templates, and deduce them against each other.  One of
13298    the templates will be more specialized if all the *other*
13299    template's arguments deduce against its arguments and at least one
13300    of its arguments *does* *not* deduce against the other template's
13301    corresponding argument.  Deduction is done as for class templates.
13302    The arguments used in deduction have reference and top level cv
13303    qualifiers removed.  Iff both arguments were originally reference
13304    types *and* deduction succeeds in both directions, the template
13305    with the more cv-qualified argument wins for that pairing (if
13306    neither is more cv-qualified, they both are equal).  Unlike regular
13307    deduction, after all the arguments have been deduced in this way,
13308    we do *not* verify the deduced template argument values can be
13309    substituted into non-deduced contexts, nor do we have to verify
13310    that all template arguments have been deduced.  */
13311
13312 int
13313 more_specialized_fn (tree pat1, tree pat2, int len)
13314 {
13315   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
13316   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
13317   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
13318   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
13319   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
13320   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
13321   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
13322   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
13323   int better1 = 0;
13324   int better2 = 0;
13325
13326   /* Remove the this parameter from non-static member functions.  If
13327      one is a non-static member function and the other is not a static
13328      member function, remove the first parameter from that function
13329      also.  This situation occurs for operator functions where we
13330      locate both a member function (with this pointer) and non-member
13331      operator (with explicit first operand).  */
13332   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
13333     {
13334       len--; /* LEN is the number of significant arguments for DECL1 */
13335       args1 = TREE_CHAIN (args1);
13336       if (!DECL_STATIC_FUNCTION_P (decl2))
13337         args2 = TREE_CHAIN (args2);
13338     }
13339   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
13340     {
13341       args2 = TREE_CHAIN (args2);
13342       if (!DECL_STATIC_FUNCTION_P (decl1))
13343         {
13344           len--;
13345           args1 = TREE_CHAIN (args1);
13346         }
13347     }
13348
13349   /* If only one is a conversion operator, they are unordered.  */
13350   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
13351     return 0;
13352
13353   /* Consider the return type for a conversion function */
13354   if (DECL_CONV_FN_P (decl1))
13355     {
13356       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
13357       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
13358       len++;
13359     }
13360
13361   processing_template_decl++;
13362
13363   while (len--)
13364     {
13365       tree arg1 = TREE_VALUE (args1);
13366       tree arg2 = TREE_VALUE (args2);
13367       int deduce1, deduce2;
13368       int quals1 = -1;
13369       int quals2 = -1;
13370
13371       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13372           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13373         {
13374           /* When both arguments are pack expansions, we need only
13375              unify the patterns themselves.  */
13376           arg1 = PACK_EXPANSION_PATTERN (arg1);
13377           arg2 = PACK_EXPANSION_PATTERN (arg2);
13378
13379           /* This is the last comparison we need to do.  */
13380           len = 0;
13381         }
13382
13383       if (TREE_CODE (arg1) == REFERENCE_TYPE)
13384         {
13385           arg1 = TREE_TYPE (arg1);
13386           quals1 = cp_type_quals (arg1);
13387         }
13388
13389       if (TREE_CODE (arg2) == REFERENCE_TYPE)
13390         {
13391           arg2 = TREE_TYPE (arg2);
13392           quals2 = cp_type_quals (arg2);
13393         }
13394
13395       if ((quals1 < 0) != (quals2 < 0))
13396         {
13397           /* Only of the args is a reference, see if we should apply
13398              array/function pointer decay to it.  This is not part of
13399              DR214, but is, IMHO, consistent with the deduction rules
13400              for the function call itself, and with our earlier
13401              implementation of the underspecified partial ordering
13402              rules.  (nathan).  */
13403           if (quals1 >= 0)
13404             {
13405               switch (TREE_CODE (arg1))
13406                 {
13407                 case ARRAY_TYPE:
13408                   arg1 = TREE_TYPE (arg1);
13409                   /* FALLTHROUGH. */
13410                 case FUNCTION_TYPE:
13411                   arg1 = build_pointer_type (arg1);
13412                   break;
13413
13414                 default:
13415                   break;
13416                 }
13417             }
13418           else
13419             {
13420               switch (TREE_CODE (arg2))
13421                 {
13422                 case ARRAY_TYPE:
13423                   arg2 = TREE_TYPE (arg2);
13424                   /* FALLTHROUGH. */
13425                 case FUNCTION_TYPE:
13426                   arg2 = build_pointer_type (arg2);
13427                   break;
13428
13429                 default:
13430                   break;
13431                 }
13432             }
13433         }
13434
13435       arg1 = TYPE_MAIN_VARIANT (arg1);
13436       arg2 = TYPE_MAIN_VARIANT (arg2);
13437
13438       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
13439         {
13440           int i, len2 = list_length (args2);
13441           tree parmvec = make_tree_vec (1);
13442           tree argvec = make_tree_vec (len2);
13443           tree ta = args2;
13444
13445           /* Setup the parameter vector, which contains only ARG1.  */
13446           TREE_VEC_ELT (parmvec, 0) = arg1;
13447
13448           /* Setup the argument vector, which contains the remaining
13449              arguments.  */
13450           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
13451             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13452
13453           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
13454                                            argvec, UNIFY_ALLOW_NONE, 
13455                                            /*call_args_p=*/false, 
13456                                            /*subr=*/0);
13457
13458           /* We cannot deduce in the other direction, because ARG1 is
13459              a pack expansion but ARG2 is not.  */
13460           deduce2 = 0;
13461         }
13462       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13463         {
13464           int i, len1 = list_length (args1);
13465           tree parmvec = make_tree_vec (1);
13466           tree argvec = make_tree_vec (len1);
13467           tree ta = args1;
13468
13469           /* Setup the parameter vector, which contains only ARG1.  */
13470           TREE_VEC_ELT (parmvec, 0) = arg2;
13471
13472           /* Setup the argument vector, which contains the remaining
13473              arguments.  */
13474           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
13475             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13476
13477           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
13478                                            argvec, UNIFY_ALLOW_NONE, 
13479                                            /*call_args_p=*/false, 
13480                                            /*subr=*/0);
13481
13482           /* We cannot deduce in the other direction, because ARG2 is
13483              a pack expansion but ARG1 is not.*/
13484           deduce1 = 0;
13485         }
13486
13487       else
13488         {
13489           /* The normal case, where neither argument is a pack
13490              expansion.  */
13491           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
13492           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
13493         }
13494
13495       if (!deduce1)
13496         better2 = -1;
13497       if (!deduce2)
13498         better1 = -1;
13499       if (better1 < 0 && better2 < 0)
13500         /* We've failed to deduce something in either direction.
13501            These must be unordered.  */
13502         break;
13503
13504       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
13505         {
13506           /* Deduces in both directions, see if quals can
13507              disambiguate.  Pretend the worse one failed to deduce. */
13508           if ((quals1 & quals2) == quals2)
13509             deduce1 = 0;
13510           if ((quals1 & quals2) == quals1)
13511             deduce2 = 0;
13512         }
13513       if (deduce1 && !deduce2 && !better2)
13514         better2 = 1;
13515       if (deduce2 && !deduce1 && !better1)
13516         better1 = 1;
13517
13518       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13519           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13520         /* We have already processed all of the arguments in our
13521            handing of the pack expansion type.  */
13522         len = 0;
13523
13524       args1 = TREE_CHAIN (args1);
13525       args2 = TREE_CHAIN (args2);
13526
13527       /* Stop when an ellipsis is seen.  */
13528       if (args1 == NULL_TREE || args2 == NULL_TREE)
13529         break;
13530     }
13531
13532   processing_template_decl--;
13533
13534   /* All things being equal, if the next argument is a pack expansion
13535      for one function but not for the other, prefer the
13536      non-variadic function.  */
13537   if ((better1 > 0) - (better2 > 0) == 0
13538       && args1 && TREE_VALUE (args1)
13539       && args2 && TREE_VALUE (args2))
13540     {
13541       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
13542         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
13543       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
13544         return 1;
13545     }
13546
13547   return (better1 > 0) - (better2 > 0);
13548 }
13549
13550 /* Determine which of two partial specializations is more specialized.
13551
13552    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
13553    to the first partial specialization.  The TREE_VALUE is the
13554    innermost set of template parameters for the partial
13555    specialization.  PAT2 is similar, but for the second template.
13556
13557    Return 1 if the first partial specialization is more specialized;
13558    -1 if the second is more specialized; 0 if neither is more
13559    specialized.
13560
13561    See [temp.class.order] for information about determining which of
13562    two templates is more specialized.  */
13563
13564 static int
13565 more_specialized_class (tree pat1, tree pat2)
13566 {
13567   tree targs;
13568   tree tmpl1, tmpl2;
13569   int winner = 0;
13570   bool any_deductions = false;
13571
13572   tmpl1 = TREE_TYPE (pat1);
13573   tmpl2 = TREE_TYPE (pat2);
13574
13575   /* Just like what happens for functions, if we are ordering between
13576      different class template specializations, we may encounter dependent
13577      types in the arguments, and we need our dependency check functions
13578      to behave correctly.  */
13579   ++processing_template_decl;
13580   targs = get_class_bindings (TREE_VALUE (pat1),
13581                               CLASSTYPE_TI_ARGS (tmpl1),
13582                               CLASSTYPE_TI_ARGS (tmpl2));
13583   if (targs)
13584     {
13585       --winner;
13586       any_deductions = true;
13587     }
13588
13589   targs = get_class_bindings (TREE_VALUE (pat2),
13590                               CLASSTYPE_TI_ARGS (tmpl2),
13591                               CLASSTYPE_TI_ARGS (tmpl1));
13592   if (targs)
13593     {
13594       ++winner;
13595       any_deductions = true;
13596     }
13597   --processing_template_decl;
13598
13599   /* In the case of a tie where at least one of the class templates
13600      has a parameter pack at the end, the template with the most
13601      non-packed parameters wins.  */
13602   if (winner == 0
13603       && any_deductions
13604       && (template_args_variadic_p (TREE_PURPOSE (pat1))
13605           || template_args_variadic_p (TREE_PURPOSE (pat2))))
13606     {
13607       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
13608       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
13609       int len1 = TREE_VEC_LENGTH (args1);
13610       int len2 = TREE_VEC_LENGTH (args2);
13611
13612       /* We don't count the pack expansion at the end.  */
13613       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
13614         --len1;
13615       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
13616         --len2;
13617
13618       if (len1 > len2)
13619         return 1;
13620       else if (len1 < len2)
13621         return -1;
13622     }
13623
13624   return winner;
13625 }
13626
13627 /* Return the template arguments that will produce the function signature
13628    DECL from the function template FN, with the explicit template
13629    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
13630    also match.  Return NULL_TREE if no satisfactory arguments could be
13631    found.  */
13632
13633 static tree
13634 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
13635 {
13636   int ntparms = DECL_NTPARMS (fn);
13637   tree targs = make_tree_vec (ntparms);
13638   tree decl_type;
13639   tree decl_arg_types;
13640
13641   /* Substitute the explicit template arguments into the type of DECL.
13642      The call to fn_type_unification will handle substitution into the
13643      FN.  */
13644   decl_type = TREE_TYPE (decl);
13645   if (explicit_args && uses_template_parms (decl_type))
13646     {
13647       tree tmpl;
13648       tree converted_args;
13649
13650       if (DECL_TEMPLATE_INFO (decl))
13651         tmpl = DECL_TI_TEMPLATE (decl);
13652       else
13653         /* We can get here for some invalid specializations.  */
13654         return NULL_TREE;
13655
13656       converted_args
13657         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
13658                                  explicit_args, NULL_TREE,
13659                                  tf_none,
13660                                  /*require_all_args=*/false,
13661                                  /*use_default_args=*/false);
13662       if (converted_args == error_mark_node)
13663         return NULL_TREE;
13664
13665       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
13666       if (decl_type == error_mark_node)
13667         return NULL_TREE;
13668     }
13669
13670   /* Never do unification on the 'this' parameter.  */
13671   decl_arg_types = skip_artificial_parms_for (decl, 
13672                                               TYPE_ARG_TYPES (decl_type));
13673
13674   if (fn_type_unification (fn, explicit_args, targs,
13675                            decl_arg_types,
13676                            (check_rettype || DECL_CONV_FN_P (fn)
13677                             ? TREE_TYPE (decl_type) : NULL_TREE),
13678                            DEDUCE_EXACT, LOOKUP_NORMAL))
13679     return NULL_TREE;
13680
13681   return targs;
13682 }
13683
13684 /* Return the innermost template arguments that, when applied to a
13685    template specialization whose innermost template parameters are
13686    TPARMS, and whose specialization arguments are PARMS, yield the
13687    ARGS.
13688
13689    For example, suppose we have:
13690
13691      template <class T, class U> struct S {};
13692      template <class T> struct S<T*, int> {};
13693
13694    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
13695    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
13696    int}.  The resulting vector will be {double}, indicating that `T'
13697    is bound to `double'.  */
13698
13699 static tree
13700 get_class_bindings (tree tparms, tree spec_args, tree args)
13701 {
13702   int i, ntparms = TREE_VEC_LENGTH (tparms);
13703   tree deduced_args;
13704   tree innermost_deduced_args;
13705
13706   innermost_deduced_args = make_tree_vec (ntparms);
13707   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13708     {
13709       deduced_args = copy_node (args);
13710       SET_TMPL_ARGS_LEVEL (deduced_args,
13711                            TMPL_ARGS_DEPTH (deduced_args),
13712                            innermost_deduced_args);
13713     }
13714   else
13715     deduced_args = innermost_deduced_args;
13716
13717   if (unify (tparms, deduced_args,
13718              INNERMOST_TEMPLATE_ARGS (spec_args),
13719              INNERMOST_TEMPLATE_ARGS (args),
13720              UNIFY_ALLOW_NONE))
13721     return NULL_TREE;
13722
13723   for (i =  0; i < ntparms; ++i)
13724     if (! TREE_VEC_ELT (innermost_deduced_args, i))
13725       return NULL_TREE;
13726
13727   /* Verify that nondeduced template arguments agree with the type
13728      obtained from argument deduction.
13729
13730      For example:
13731
13732        struct A { typedef int X; };
13733        template <class T, class U> struct C {};
13734        template <class T> struct C<T, typename T::X> {};
13735
13736      Then with the instantiation `C<A, int>', we can deduce that
13737      `T' is `A' but unify () does not check whether `typename T::X'
13738      is `int'.  */
13739   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
13740   if (spec_args == error_mark_node
13741       /* We only need to check the innermost arguments; the other
13742          arguments will always agree.  */
13743       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
13744                               INNERMOST_TEMPLATE_ARGS (args)))
13745     return NULL_TREE;
13746
13747   return deduced_args;
13748 }
13749
13750 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
13751    Return the TREE_LIST node with the most specialized template, if
13752    any.  If there is no most specialized template, the error_mark_node
13753    is returned.
13754
13755    Note that this function does not look at, or modify, the
13756    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
13757    returned is one of the elements of INSTANTIATIONS, callers may
13758    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
13759    and retrieve it from the value returned.  */
13760
13761 tree
13762 most_specialized_instantiation (tree templates)
13763 {
13764   tree fn, champ;
13765
13766   ++processing_template_decl;
13767
13768   champ = templates;
13769   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
13770     {
13771       int fate = 0;
13772
13773       if (get_bindings (TREE_VALUE (champ),
13774                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
13775                         NULL_TREE, /*check_ret=*/false))
13776         fate--;
13777
13778       if (get_bindings (TREE_VALUE (fn),
13779                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
13780                         NULL_TREE, /*check_ret=*/false))
13781         fate++;
13782
13783       if (fate == -1)
13784         champ = fn;
13785       else if (!fate)
13786         {
13787           /* Equally specialized, move to next function.  If there
13788              is no next function, nothing's most specialized.  */
13789           fn = TREE_CHAIN (fn);
13790           champ = fn;
13791           if (!fn)
13792             break;
13793         }
13794     }
13795
13796   if (champ)
13797     /* Now verify that champ is better than everything earlier in the
13798        instantiation list.  */
13799     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
13800       if (get_bindings (TREE_VALUE (champ),
13801                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
13802                         NULL_TREE, /*check_ret=*/false)
13803           || !get_bindings (TREE_VALUE (fn),
13804                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
13805                             NULL_TREE, /*check_ret=*/false))
13806         {
13807           champ = NULL_TREE;
13808           break;
13809         }
13810
13811   processing_template_decl--;
13812
13813   if (!champ)
13814     return error_mark_node;
13815
13816   return champ;
13817 }
13818
13819 /* If DECL is a specialization of some template, return the most
13820    general such template.  Otherwise, returns NULL_TREE.
13821
13822    For example, given:
13823
13824      template <class T> struct S { template <class U> void f(U); };
13825
13826    if TMPL is `template <class U> void S<int>::f(U)' this will return
13827    the full template.  This function will not trace past partial
13828    specializations, however.  For example, given in addition:
13829
13830      template <class T> struct S<T*> { template <class U> void f(U); };
13831
13832    if TMPL is `template <class U> void S<int*>::f(U)' this will return
13833    `template <class T> template <class U> S<T*>::f(U)'.  */
13834
13835 tree
13836 most_general_template (tree decl)
13837 {
13838   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
13839      an immediate specialization.  */
13840   if (TREE_CODE (decl) == FUNCTION_DECL)
13841     {
13842       if (DECL_TEMPLATE_INFO (decl)) {
13843         decl = DECL_TI_TEMPLATE (decl);
13844
13845         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
13846            template friend.  */
13847         if (TREE_CODE (decl) != TEMPLATE_DECL)
13848           return NULL_TREE;
13849       } else
13850         return NULL_TREE;
13851     }
13852
13853   /* Look for more and more general templates.  */
13854   while (DECL_TEMPLATE_INFO (decl))
13855     {
13856       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
13857          (See cp-tree.h for details.)  */
13858       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
13859         break;
13860
13861       if (CLASS_TYPE_P (TREE_TYPE (decl))
13862           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
13863         break;
13864
13865       /* Stop if we run into an explicitly specialized class template.  */
13866       if (!DECL_NAMESPACE_SCOPE_P (decl)
13867           && DECL_CONTEXT (decl)
13868           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
13869         break;
13870
13871       decl = DECL_TI_TEMPLATE (decl);
13872     }
13873
13874   return decl;
13875 }
13876
13877 /* Return the most specialized of the class template partial
13878    specializations of TMPL which can produce TYPE, a specialization of
13879    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
13880    a _TYPE node corresponding to the partial specialization, while the
13881    TREE_PURPOSE is the set of template arguments that must be
13882    substituted into the TREE_TYPE in order to generate TYPE.
13883
13884    If the choice of partial specialization is ambiguous, a diagnostic
13885    is issued, and the error_mark_node is returned.  If there are no
13886    partial specializations of TMPL matching TYPE, then NULL_TREE is
13887    returned.  */
13888
13889 static tree
13890 most_specialized_class (tree type, tree tmpl)
13891 {
13892   tree list = NULL_TREE;
13893   tree t;
13894   tree champ;
13895   int fate;
13896   bool ambiguous_p;
13897   tree args;
13898   tree outer_args = NULL_TREE;
13899
13900   tmpl = most_general_template (tmpl);
13901   args = CLASSTYPE_TI_ARGS (type);
13902
13903   /* For determining which partial specialization to use, only the
13904      innermost args are interesting.  */
13905   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13906     {
13907       outer_args = strip_innermost_template_args (args, 1);
13908       args = INNERMOST_TEMPLATE_ARGS (args);
13909     }
13910
13911   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
13912     {
13913       tree partial_spec_args;
13914       tree spec_args;
13915       tree parms = TREE_VALUE (t);
13916
13917       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
13918       if (outer_args)
13919         {
13920           int i;
13921
13922           ++processing_template_decl;
13923
13924           /* Discard the outer levels of args, and then substitute in the
13925              template args from the enclosing class.  */
13926           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
13927           partial_spec_args = tsubst_template_args
13928             (partial_spec_args, outer_args, tf_none, NULL_TREE);
13929
13930           /* PARMS already refers to just the innermost parms, but the
13931              template parms in partial_spec_args had their levels lowered
13932              by tsubst, so we need to do the same for the parm list.  We
13933              can't just tsubst the TREE_VEC itself, as tsubst wants to
13934              treat a TREE_VEC as an argument vector.  */
13935           parms = copy_node (parms);
13936           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
13937             TREE_VEC_ELT (parms, i) =
13938               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
13939
13940           --processing_template_decl;
13941         }
13942       spec_args = get_class_bindings (parms,
13943                                       partial_spec_args,
13944                                       args);
13945       if (spec_args)
13946         {
13947           if (outer_args)
13948             spec_args = add_to_template_args (outer_args, spec_args);
13949           list = tree_cons (spec_args, TREE_VALUE (t), list);
13950           TREE_TYPE (list) = TREE_TYPE (t);
13951         }
13952     }
13953
13954   if (! list)
13955     return NULL_TREE;
13956
13957   ambiguous_p = false;
13958   t = list;
13959   champ = t;
13960   t = TREE_CHAIN (t);
13961   for (; t; t = TREE_CHAIN (t))
13962     {
13963       fate = more_specialized_class (champ, t);
13964       if (fate == 1)
13965         ;
13966       else
13967         {
13968           if (fate == 0)
13969             {
13970               t = TREE_CHAIN (t);
13971               if (! t)
13972                 {
13973                   ambiguous_p = true;
13974                   break;
13975                 }
13976             }
13977           champ = t;
13978         }
13979     }
13980
13981   if (!ambiguous_p)
13982     for (t = list; t && t != champ; t = TREE_CHAIN (t))
13983       {
13984         fate = more_specialized_class (champ, t);
13985         if (fate != 1)
13986           {
13987             ambiguous_p = true;
13988             break;
13989           }
13990       }
13991
13992   if (ambiguous_p)
13993     {
13994       const char *str = "candidates are:";
13995       error ("ambiguous class template instantiation for %q#T", type);
13996       for (t = list; t; t = TREE_CHAIN (t))
13997         {
13998           error ("%s %+#T", str, TREE_TYPE (t));
13999           str = "               ";
14000         }
14001       return error_mark_node;
14002     }
14003
14004   return champ;
14005 }
14006
14007 /* Explicitly instantiate DECL.  */
14008
14009 void
14010 do_decl_instantiation (tree decl, tree storage)
14011 {
14012   tree result = NULL_TREE;
14013   int extern_p = 0;
14014
14015   if (!decl || decl == error_mark_node)
14016     /* An error occurred, for which grokdeclarator has already issued
14017        an appropriate message.  */
14018     return;
14019   else if (! DECL_LANG_SPECIFIC (decl))
14020     {
14021       error ("explicit instantiation of non-template %q#D", decl);
14022       return;
14023     }
14024   else if (TREE_CODE (decl) == VAR_DECL)
14025     {
14026       /* There is an asymmetry here in the way VAR_DECLs and
14027          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14028          the latter, the DECL we get back will be marked as a
14029          template instantiation, and the appropriate
14030          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14031          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14032          should handle VAR_DECLs as it currently handles
14033          FUNCTION_DECLs.  */
14034       if (!DECL_CLASS_SCOPE_P (decl))
14035         {
14036           error ("%qD is not a static data member of a class template", decl);
14037           return;
14038         }
14039       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14040       if (!result || TREE_CODE (result) != VAR_DECL)
14041         {
14042           error ("no matching template for %qD found", decl);
14043           return;
14044         }
14045       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14046         {
14047           error ("type %qT for explicit instantiation %qD does not match "
14048                  "declared type %qT", TREE_TYPE (result), decl,
14049                  TREE_TYPE (decl));
14050           return;
14051         }
14052     }
14053   else if (TREE_CODE (decl) != FUNCTION_DECL)
14054     {
14055       error ("explicit instantiation of %q#D", decl);
14056       return;
14057     }
14058   else
14059     result = decl;
14060
14061   /* Check for various error cases.  Note that if the explicit
14062      instantiation is valid the RESULT will currently be marked as an
14063      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
14064      until we get here.  */
14065
14066   if (DECL_TEMPLATE_SPECIALIZATION (result))
14067     {
14068       /* DR 259 [temp.spec].
14069
14070          Both an explicit instantiation and a declaration of an explicit
14071          specialization shall not appear in a program unless the explicit
14072          instantiation follows a declaration of the explicit specialization.
14073
14074          For a given set of template parameters, if an explicit
14075          instantiation of a template appears after a declaration of an
14076          explicit specialization for that template, the explicit
14077          instantiation has no effect.  */
14078       return;
14079     }
14080   else if (DECL_EXPLICIT_INSTANTIATION (result))
14081     {
14082       /* [temp.spec]
14083
14084          No program shall explicitly instantiate any template more
14085          than once.
14086
14087          We check DECL_NOT_REALLY_EXTERN so as not to complain when
14088          the first instantiation was `extern' and the second is not,
14089          and EXTERN_P for the opposite case.  */
14090       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
14091         pedwarn ("duplicate explicit instantiation of %q#D", result);
14092       /* If an "extern" explicit instantiation follows an ordinary
14093          explicit instantiation, the template is instantiated.  */
14094       if (extern_p)
14095         return;
14096     }
14097   else if (!DECL_IMPLICIT_INSTANTIATION (result))
14098     {
14099       error ("no matching template for %qD found", result);
14100       return;
14101     }
14102   else if (!DECL_TEMPLATE_INFO (result))
14103     {
14104       pedwarn ("explicit instantiation of non-template %q#D", result);
14105       return;
14106     }
14107
14108   if (storage == NULL_TREE)
14109     ;
14110   else if (storage == ridpointers[(int) RID_EXTERN])
14111     {
14112       if (pedantic && !in_system_header)
14113         pedwarn ("ISO C++ forbids the use of %<extern%> on explicit "
14114                  "instantiations");
14115       extern_p = 1;
14116     }
14117   else
14118     error ("storage class %qD applied to template instantiation", storage);
14119
14120   check_explicit_instantiation_namespace (result);
14121   mark_decl_instantiated (result, extern_p);
14122   if (! extern_p)
14123     instantiate_decl (result, /*defer_ok=*/1,
14124                       /*expl_inst_class_mem_p=*/false);
14125 }
14126
14127 static void
14128 mark_class_instantiated (tree t, int extern_p)
14129 {
14130   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
14131   SET_CLASSTYPE_INTERFACE_KNOWN (t);
14132   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
14133   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
14134   if (! extern_p)
14135     {
14136       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
14137       rest_of_type_compilation (t, 1);
14138     }
14139 }
14140
14141 /* Called from do_type_instantiation through binding_table_foreach to
14142    do recursive instantiation for the type bound in ENTRY.  */
14143 static void
14144 bt_instantiate_type_proc (binding_entry entry, void *data)
14145 {
14146   tree storage = *(tree *) data;
14147
14148   if (IS_AGGR_TYPE (entry->type)
14149       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
14150     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
14151 }
14152
14153 /* Called from do_type_instantiation to instantiate a member
14154    (a member function or a static member variable) of an
14155    explicitly instantiated class template.  */
14156 static void
14157 instantiate_class_member (tree decl, int extern_p)
14158 {
14159   mark_decl_instantiated (decl, extern_p);
14160   if (! extern_p)
14161     instantiate_decl (decl, /*defer_ok=*/1,
14162                       /*expl_inst_class_mem_p=*/true);
14163 }
14164
14165 /* Perform an explicit instantiation of template class T.  STORAGE, if
14166    non-null, is the RID for extern, inline or static.  COMPLAIN is
14167    nonzero if this is called from the parser, zero if called recursively,
14168    since the standard is unclear (as detailed below).  */
14169
14170 void
14171 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
14172 {
14173   int extern_p = 0;
14174   int nomem_p = 0;
14175   int static_p = 0;
14176   int previous_instantiation_extern_p = 0;
14177
14178   if (TREE_CODE (t) == TYPE_DECL)
14179     t = TREE_TYPE (t);
14180
14181   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
14182     {
14183       error ("explicit instantiation of non-template type %qT", t);
14184       return;
14185     }
14186
14187   complete_type (t);
14188
14189   if (!COMPLETE_TYPE_P (t))
14190     {
14191       if (complain & tf_error)
14192         error ("explicit instantiation of %q#T before definition of template",
14193                t);
14194       return;
14195     }
14196
14197   if (storage != NULL_TREE)
14198     {
14199       if (pedantic && !in_system_header)
14200         pedwarn("ISO C++ forbids the use of %qE on explicit instantiations",
14201                 storage);
14202
14203       if (storage == ridpointers[(int) RID_INLINE])
14204         nomem_p = 1;
14205       else if (storage == ridpointers[(int) RID_EXTERN])
14206         extern_p = 1;
14207       else if (storage == ridpointers[(int) RID_STATIC])
14208         static_p = 1;
14209       else
14210         {
14211           error ("storage class %qD applied to template instantiation",
14212                  storage);
14213           extern_p = 0;
14214         }
14215     }
14216
14217   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
14218     {
14219       /* DR 259 [temp.spec].
14220
14221          Both an explicit instantiation and a declaration of an explicit
14222          specialization shall not appear in a program unless the explicit
14223          instantiation follows a declaration of the explicit specialization.
14224
14225          For a given set of template parameters, if an explicit
14226          instantiation of a template appears after a declaration of an
14227          explicit specialization for that template, the explicit
14228          instantiation has no effect.  */
14229       return;
14230     }
14231   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
14232     {
14233       /* [temp.spec]
14234
14235          No program shall explicitly instantiate any template more
14236          than once.
14237
14238          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
14239          instantiation was `extern'.  If EXTERN_P then the second is.
14240          These cases are OK.  */
14241       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
14242
14243       if (!previous_instantiation_extern_p && !extern_p
14244           && (complain & tf_error))
14245         pedwarn ("duplicate explicit instantiation of %q#T", t);
14246
14247       /* If we've already instantiated the template, just return now.  */
14248       if (!CLASSTYPE_INTERFACE_ONLY (t))
14249         return;
14250     }
14251
14252   check_explicit_instantiation_namespace (TYPE_NAME (t));
14253   mark_class_instantiated (t, extern_p);
14254
14255   if (nomem_p)
14256     return;
14257
14258   {
14259     tree tmp;
14260
14261     /* In contrast to implicit instantiation, where only the
14262        declarations, and not the definitions, of members are
14263        instantiated, we have here:
14264
14265          [temp.explicit]
14266
14267          The explicit instantiation of a class template specialization
14268          implies the instantiation of all of its members not
14269          previously explicitly specialized in the translation unit
14270          containing the explicit instantiation.
14271
14272        Of course, we can't instantiate member template classes, since
14273        we don't have any arguments for them.  Note that the standard
14274        is unclear on whether the instantiation of the members are
14275        *explicit* instantiations or not.  However, the most natural
14276        interpretation is that it should be an explicit instantiation.  */
14277
14278     if (! static_p)
14279       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
14280         if (TREE_CODE (tmp) == FUNCTION_DECL
14281             && DECL_TEMPLATE_INSTANTIATION (tmp))
14282           instantiate_class_member (tmp, extern_p);
14283
14284     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
14285       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
14286         instantiate_class_member (tmp, extern_p);
14287
14288     if (CLASSTYPE_NESTED_UTDS (t))
14289       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
14290                              bt_instantiate_type_proc, &storage);
14291   }
14292 }
14293
14294 /* Given a function DECL, which is a specialization of TMPL, modify
14295    DECL to be a re-instantiation of TMPL with the same template
14296    arguments.  TMPL should be the template into which tsubst'ing
14297    should occur for DECL, not the most general template.
14298
14299    One reason for doing this is a scenario like this:
14300
14301      template <class T>
14302      void f(const T&, int i);
14303
14304      void g() { f(3, 7); }
14305
14306      template <class T>
14307      void f(const T& t, const int i) { }
14308
14309    Note that when the template is first instantiated, with
14310    instantiate_template, the resulting DECL will have no name for the
14311    first parameter, and the wrong type for the second.  So, when we go
14312    to instantiate the DECL, we regenerate it.  */
14313
14314 static void
14315 regenerate_decl_from_template (tree decl, tree tmpl)
14316 {
14317   /* The arguments used to instantiate DECL, from the most general
14318      template.  */
14319   tree args;
14320   tree code_pattern;
14321
14322   args = DECL_TI_ARGS (decl);
14323   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
14324
14325   /* Make sure that we can see identifiers, and compute access
14326      correctly.  */
14327   push_access_scope (decl);
14328
14329   if (TREE_CODE (decl) == FUNCTION_DECL)
14330     {
14331       tree decl_parm;
14332       tree pattern_parm;
14333       tree specs;
14334       int args_depth;
14335       int parms_depth;
14336
14337       args_depth = TMPL_ARGS_DEPTH (args);
14338       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
14339       if (args_depth > parms_depth)
14340         args = get_innermost_template_args (args, parms_depth);
14341
14342       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
14343                                               args, tf_error, NULL_TREE);
14344       if (specs)
14345         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
14346                                                     specs);
14347
14348       /* Merge parameter declarations.  */
14349       decl_parm = skip_artificial_parms_for (decl,
14350                                              DECL_ARGUMENTS (decl));
14351       pattern_parm
14352         = skip_artificial_parms_for (code_pattern,
14353                                      DECL_ARGUMENTS (code_pattern));
14354       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
14355         {
14356           tree parm_type;
14357           tree attributes;
14358           
14359           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14360             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
14361           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
14362                               NULL_TREE);
14363           parm_type = type_decays_to (parm_type);
14364           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14365             TREE_TYPE (decl_parm) = parm_type;
14366           attributes = DECL_ATTRIBUTES (pattern_parm);
14367           if (DECL_ATTRIBUTES (decl_parm) != attributes)
14368             {
14369               DECL_ATTRIBUTES (decl_parm) = attributes;
14370               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14371             }
14372           decl_parm = TREE_CHAIN (decl_parm);
14373           pattern_parm = TREE_CHAIN (pattern_parm);
14374         }
14375       /* Merge any parameters that match with the function parameter
14376          pack.  */
14377       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
14378         {
14379           int i, len;
14380           tree expanded_types;
14381           /* Expand the TYPE_PACK_EXPANSION that provides the types for
14382              the parameters in this function parameter pack.  */
14383           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
14384                                                  args, tf_error, NULL_TREE);
14385           len = TREE_VEC_LENGTH (expanded_types);
14386           for (i = 0; i < len; i++)
14387             {
14388               tree parm_type;
14389               tree attributes;
14390           
14391               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14392                 /* Rename the parameter to include the index.  */
14393                 DECL_NAME (decl_parm) = 
14394                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
14395               parm_type = TREE_VEC_ELT (expanded_types, i);
14396               parm_type = type_decays_to (parm_type);
14397               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14398                 TREE_TYPE (decl_parm) = parm_type;
14399               attributes = DECL_ATTRIBUTES (pattern_parm);
14400               if (DECL_ATTRIBUTES (decl_parm) != attributes)
14401                 {
14402                   DECL_ATTRIBUTES (decl_parm) = attributes;
14403                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14404                 }
14405               decl_parm = TREE_CHAIN (decl_parm);
14406             }
14407         }
14408       /* Merge additional specifiers from the CODE_PATTERN.  */
14409       if (DECL_DECLARED_INLINE_P (code_pattern)
14410           && !DECL_DECLARED_INLINE_P (decl))
14411         DECL_DECLARED_INLINE_P (decl) = 1;
14412       if (DECL_INLINE (code_pattern) && !DECL_INLINE (decl))
14413         DECL_INLINE (decl) = 1;
14414     }
14415   else if (TREE_CODE (decl) == VAR_DECL)
14416     DECL_INITIAL (decl) =
14417       tsubst_expr (DECL_INITIAL (code_pattern), args,
14418                    tf_error, DECL_TI_TEMPLATE (decl),
14419                    /*integral_constant_expression_p=*/false);
14420   else
14421     gcc_unreachable ();
14422
14423   pop_access_scope (decl);
14424 }
14425
14426 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
14427    substituted to get DECL.  */
14428
14429 tree
14430 template_for_substitution (tree decl)
14431 {
14432   tree tmpl = DECL_TI_TEMPLATE (decl);
14433
14434   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
14435      for the instantiation.  This is not always the most general
14436      template.  Consider, for example:
14437
14438         template <class T>
14439         struct S { template <class U> void f();
14440                    template <> void f<int>(); };
14441
14442      and an instantiation of S<double>::f<int>.  We want TD to be the
14443      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
14444   while (/* An instantiation cannot have a definition, so we need a
14445             more general template.  */
14446          DECL_TEMPLATE_INSTANTIATION (tmpl)
14447            /* We must also deal with friend templates.  Given:
14448
14449                 template <class T> struct S {
14450                   template <class U> friend void f() {};
14451                 };
14452
14453               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
14454               so far as the language is concerned, but that's still
14455               where we get the pattern for the instantiation from.  On
14456               other hand, if the definition comes outside the class, say:
14457
14458                 template <class T> struct S {
14459                   template <class U> friend void f();
14460                 };
14461                 template <class U> friend void f() {}
14462
14463               we don't need to look any further.  That's what the check for
14464               DECL_INITIAL is for.  */
14465           || (TREE_CODE (decl) == FUNCTION_DECL
14466               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
14467               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
14468     {
14469       /* The present template, TD, should not be a definition.  If it
14470          were a definition, we should be using it!  Note that we
14471          cannot restructure the loop to just keep going until we find
14472          a template with a definition, since that might go too far if
14473          a specialization was declared, but not defined.  */
14474       gcc_assert (TREE_CODE (decl) != VAR_DECL
14475                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
14476
14477       /* Fetch the more general template.  */
14478       tmpl = DECL_TI_TEMPLATE (tmpl);
14479     }
14480
14481   return tmpl;
14482 }
14483
14484 /* Produce the definition of D, a _DECL generated from a template.  If
14485    DEFER_OK is nonzero, then we don't have to actually do the
14486    instantiation now; we just have to do it sometime.  Normally it is
14487    an error if this is an explicit instantiation but D is undefined.
14488    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
14489    explicitly instantiated class template.  */
14490
14491 tree
14492 instantiate_decl (tree d, int defer_ok,
14493                   bool expl_inst_class_mem_p)
14494 {
14495   tree tmpl = DECL_TI_TEMPLATE (d);
14496   tree gen_args;
14497   tree args;
14498   tree td;
14499   tree code_pattern;
14500   tree spec;
14501   tree gen_tmpl;
14502   bool pattern_defined;
14503   int need_push;
14504   location_t saved_loc = input_location;
14505   int saved_in_system_header = in_system_header;
14506   bool external_p;
14507
14508   /* This function should only be used to instantiate templates for
14509      functions and static member variables.  */
14510   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
14511               || TREE_CODE (d) == VAR_DECL);
14512
14513   /* Variables are never deferred; if instantiation is required, they
14514      are instantiated right away.  That allows for better code in the
14515      case that an expression refers to the value of the variable --
14516      if the variable has a constant value the referring expression can
14517      take advantage of that fact.  */
14518   if (TREE_CODE (d) == VAR_DECL)
14519     defer_ok = 0;
14520
14521   /* Don't instantiate cloned functions.  Instead, instantiate the
14522      functions they cloned.  */
14523   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
14524     d = DECL_CLONED_FUNCTION (d);
14525
14526   if (DECL_TEMPLATE_INSTANTIATED (d))
14527     /* D has already been instantiated.  It might seem reasonable to
14528        check whether or not D is an explicit instantiation, and, if so,
14529        stop here.  But when an explicit instantiation is deferred
14530        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
14531        is set, even though we still need to do the instantiation.  */
14532     return d;
14533
14534   /* If we already have a specialization of this declaration, then
14535      there's no reason to instantiate it.  Note that
14536      retrieve_specialization gives us both instantiations and
14537      specializations, so we must explicitly check
14538      DECL_TEMPLATE_SPECIALIZATION.  */
14539   gen_tmpl = most_general_template (tmpl);
14540   gen_args = DECL_TI_ARGS (d);
14541   spec = retrieve_specialization (gen_tmpl, gen_args,
14542                                   /*class_specializations_p=*/false);
14543   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
14544     return spec;
14545
14546   /* This needs to happen before any tsubsting.  */
14547   if (! push_tinst_level (d))
14548     return d;
14549
14550   timevar_push (TV_PARSE);
14551
14552   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
14553      for the instantiation.  */
14554   td = template_for_substitution (d);
14555   code_pattern = DECL_TEMPLATE_RESULT (td);
14556
14557   /* We should never be trying to instantiate a member of a class
14558      template or partial specialization.  */
14559   gcc_assert (d != code_pattern);
14560
14561   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
14562       || DECL_TEMPLATE_SPECIALIZATION (td))
14563     /* In the case of a friend template whose definition is provided
14564        outside the class, we may have too many arguments.  Drop the
14565        ones we don't need.  The same is true for specializations.  */
14566     args = get_innermost_template_args
14567       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
14568   else
14569     args = gen_args;
14570
14571   if (TREE_CODE (d) == FUNCTION_DECL)
14572     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
14573   else
14574     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
14575
14576   /* We may be in the middle of deferred access check.  Disable it now.  */
14577   push_deferring_access_checks (dk_no_deferred);
14578
14579   /* Unless an explicit instantiation directive has already determined
14580      the linkage of D, remember that a definition is available for
14581      this entity.  */
14582   if (pattern_defined
14583       && !DECL_INTERFACE_KNOWN (d)
14584       && !DECL_NOT_REALLY_EXTERN (d))
14585     mark_definable (d);
14586
14587   input_location = DECL_SOURCE_LOCATION (d);
14588   in_system_header = DECL_IN_SYSTEM_HEADER (d);
14589
14590   /* If D is a member of an explicitly instantiated class template,
14591      and no definition is available, treat it like an implicit
14592      instantiation.  */
14593   if (!pattern_defined && expl_inst_class_mem_p
14594       && DECL_EXPLICIT_INSTANTIATION (d))
14595     {
14596       DECL_NOT_REALLY_EXTERN (d) = 0;
14597       DECL_INTERFACE_KNOWN (d) = 0;
14598       SET_DECL_IMPLICIT_INSTANTIATION (d);
14599     }
14600
14601   if (!defer_ok)
14602     {
14603       /* Recheck the substitutions to obtain any warning messages
14604          about ignoring cv qualifiers.  */
14605       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
14606       tree type = TREE_TYPE (gen);
14607
14608       /* Make sure that we can see identifiers, and compute access
14609          correctly.  D is already the target FUNCTION_DECL with the
14610          right context.  */
14611       push_access_scope (d);
14612
14613       if (TREE_CODE (gen) == FUNCTION_DECL)
14614         {
14615           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
14616           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
14617                                           d);
14618           /* Don't simply tsubst the function type, as that will give
14619              duplicate warnings about poor parameter qualifications.
14620              The function arguments are the same as the decl_arguments
14621              without the top level cv qualifiers.  */
14622           type = TREE_TYPE (type);
14623         }
14624       tsubst (type, gen_args, tf_warning_or_error, d);
14625
14626       pop_access_scope (d);
14627     }
14628
14629   /* Check to see whether we know that this template will be
14630      instantiated in some other file, as with "extern template"
14631      extension.  */
14632   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
14633   /* In general, we do not instantiate such templates...  */
14634   if (external_p
14635       /* ... but we instantiate inline functions so that we can inline
14636          them and ... */
14637       && ! (TREE_CODE (d) == FUNCTION_DECL && DECL_INLINE (d))
14638       /* ... we instantiate static data members whose values are
14639          needed in integral constant expressions.  */
14640       && ! (TREE_CODE (d) == VAR_DECL
14641             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
14642     goto out;
14643   /* Defer all other templates, unless we have been explicitly
14644      forbidden from doing so.  */
14645   if (/* If there is no definition, we cannot instantiate the
14646          template.  */
14647       ! pattern_defined
14648       /* If it's OK to postpone instantiation, do so.  */
14649       || defer_ok
14650       /* If this is a static data member that will be defined
14651          elsewhere, we don't want to instantiate the entire data
14652          member, but we do want to instantiate the initializer so that
14653          we can substitute that elsewhere.  */
14654       || (external_p && TREE_CODE (d) == VAR_DECL))
14655     {
14656       /* The definition of the static data member is now required so
14657          we must substitute the initializer.  */
14658       if (TREE_CODE (d) == VAR_DECL
14659           && !DECL_INITIAL (d)
14660           && DECL_INITIAL (code_pattern))
14661         {
14662           tree ns;
14663           tree init;
14664
14665           ns = decl_namespace_context (d);
14666           push_nested_namespace (ns);
14667           push_nested_class (DECL_CONTEXT (d));
14668           init = tsubst_expr (DECL_INITIAL (code_pattern),
14669                               args,
14670                               tf_warning_or_error, NULL_TREE,
14671                               /*integral_constant_expression_p=*/false);
14672           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
14673                           /*asmspec_tree=*/NULL_TREE,
14674                           LOOKUP_ONLYCONVERTING);
14675           pop_nested_class ();
14676           pop_nested_namespace (ns);
14677         }
14678
14679       /* We restore the source position here because it's used by
14680          add_pending_template.  */
14681       input_location = saved_loc;
14682
14683       if (at_eof && !pattern_defined
14684           && DECL_EXPLICIT_INSTANTIATION (d))
14685         /* [temp.explicit]
14686
14687            The definition of a non-exported function template, a
14688            non-exported member function template, or a non-exported
14689            member function or static data member of a class template
14690            shall be present in every translation unit in which it is
14691            explicitly instantiated.  */
14692         pedwarn
14693           ("explicit instantiation of %qD but no definition available", d);
14694
14695       /* ??? Historically, we have instantiated inline functions, even
14696          when marked as "extern template".  */
14697       if (!(external_p && TREE_CODE (d) == VAR_DECL))
14698         add_pending_template (d);
14699       goto out;
14700     }
14701   /* Tell the repository that D is available in this translation unit
14702      -- and see if it is supposed to be instantiated here.  */
14703   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
14704     {
14705       /* In a PCH file, despite the fact that the repository hasn't
14706          requested instantiation in the PCH it is still possible that
14707          an instantiation will be required in a file that includes the
14708          PCH.  */
14709       if (pch_file)
14710         add_pending_template (d);
14711       /* Instantiate inline functions so that the inliner can do its
14712          job, even though we'll not be emitting a copy of this
14713          function.  */
14714       if (!(TREE_CODE (d) == FUNCTION_DECL
14715             && flag_inline_trees
14716             && DECL_DECLARED_INLINE_P (d)))
14717         goto out;
14718     }
14719
14720   need_push = !cfun || !global_bindings_p ();
14721   if (need_push)
14722     push_to_top_level ();
14723
14724   /* Mark D as instantiated so that recursive calls to
14725      instantiate_decl do not try to instantiate it again.  */
14726   DECL_TEMPLATE_INSTANTIATED (d) = 1;
14727
14728   /* Regenerate the declaration in case the template has been modified
14729      by a subsequent redeclaration.  */
14730   regenerate_decl_from_template (d, td);
14731
14732   /* We already set the file and line above.  Reset them now in case
14733      they changed as a result of calling regenerate_decl_from_template.  */
14734   input_location = DECL_SOURCE_LOCATION (d);
14735
14736   if (TREE_CODE (d) == VAR_DECL)
14737     {
14738       tree init;
14739
14740       /* Clear out DECL_RTL; whatever was there before may not be right
14741          since we've reset the type of the declaration.  */
14742       SET_DECL_RTL (d, NULL_RTX);
14743       DECL_IN_AGGR_P (d) = 0;
14744
14745       /* The initializer is placed in DECL_INITIAL by
14746          regenerate_decl_from_template.  Pull it out so that
14747          finish_decl can process it.  */
14748       init = DECL_INITIAL (d);
14749       DECL_INITIAL (d) = NULL_TREE;
14750       DECL_INITIALIZED_P (d) = 0;
14751
14752       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
14753          initializer.  That function will defer actual emission until
14754          we have a chance to determine linkage.  */
14755       DECL_EXTERNAL (d) = 0;
14756
14757       /* Enter the scope of D so that access-checking works correctly.  */
14758       push_nested_class (DECL_CONTEXT (d));
14759       finish_decl (d, init, NULL_TREE);
14760       pop_nested_class ();
14761     }
14762   else if (TREE_CODE (d) == FUNCTION_DECL)
14763     {
14764       htab_t saved_local_specializations;
14765       tree subst_decl;
14766       tree tmpl_parm;
14767       tree spec_parm;
14768
14769       /* Save away the current list, in case we are instantiating one
14770          template from within the body of another.  */
14771       saved_local_specializations = local_specializations;
14772
14773       /* Set up the list of local specializations.  */
14774       local_specializations = htab_create (37,
14775                                            hash_local_specialization,
14776                                            eq_local_specializations,
14777                                            NULL);
14778
14779       /* Set up context.  */
14780       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
14781
14782       /* Create substitution entries for the parameters.  */
14783       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
14784       tmpl_parm = DECL_ARGUMENTS (subst_decl);
14785       spec_parm = DECL_ARGUMENTS (d);
14786       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
14787         {
14788           register_local_specialization (spec_parm, tmpl_parm);
14789           spec_parm = skip_artificial_parms_for (d, spec_parm);
14790           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
14791         }
14792       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
14793         {
14794           register_local_specialization (spec_parm, tmpl_parm);
14795           tmpl_parm = TREE_CHAIN (tmpl_parm);
14796           spec_parm = TREE_CHAIN (spec_parm);
14797         }
14798       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
14799         {
14800           /* Collect all of the extra "packed" parameters into an
14801              argument pack.  */
14802           tree parmvec;
14803           tree parmtypevec;
14804           tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
14805           tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
14806           int i, len = 0;
14807           tree t;
14808           
14809           /* Count how many parameters remain.  */
14810           for (t = spec_parm; t; t = TREE_CHAIN (t))
14811             len++;
14812
14813           /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
14814           parmvec = make_tree_vec (len);
14815           parmtypevec = make_tree_vec (len);
14816           for(i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
14817             {
14818               TREE_VEC_ELT (parmvec, i) = spec_parm;
14819               TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
14820             }
14821
14822           /* Build the argument packs.  */
14823           SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
14824           SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
14825           TREE_TYPE (argpack) = argtypepack;
14826           
14827           /* Register the (value) argument pack as a specialization of
14828              TMPL_PARM, then move on.  */
14829           register_local_specialization (argpack, tmpl_parm);
14830           tmpl_parm = TREE_CHAIN (tmpl_parm);
14831         }
14832       gcc_assert (!spec_parm);
14833
14834       /* Substitute into the body of the function.  */
14835       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
14836                    tf_warning_or_error, tmpl,
14837                    /*integral_constant_expression_p=*/false);
14838
14839       /* Set the current input_location to the end of the function
14840          so that finish_function knows where we are.  */
14841       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
14842
14843       /* We don't need the local specializations any more.  */
14844       htab_delete (local_specializations);
14845       local_specializations = saved_local_specializations;
14846
14847       /* Finish the function.  */
14848       d = finish_function (0);
14849       expand_or_defer_fn (d);
14850     }
14851
14852   /* We're not deferring instantiation any more.  */
14853   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
14854
14855   if (need_push)
14856     pop_from_top_level ();
14857
14858 out:
14859   input_location = saved_loc;
14860   in_system_header = saved_in_system_header;
14861   pop_deferring_access_checks ();
14862   pop_tinst_level ();
14863
14864   timevar_pop (TV_PARSE);
14865
14866   return d;
14867 }
14868
14869 /* Run through the list of templates that we wish we could
14870    instantiate, and instantiate any we can.  RETRIES is the
14871    number of times we retry pending template instantiation.  */
14872
14873 void
14874 instantiate_pending_templates (int retries)
14875 {
14876   int reconsider;
14877   location_t saved_loc = input_location;
14878   int saved_in_system_header = in_system_header;
14879
14880   /* Instantiating templates may trigger vtable generation.  This in turn
14881      may require further template instantiations.  We place a limit here
14882      to avoid infinite loop.  */
14883   if (pending_templates && retries >= max_tinst_depth)
14884     {
14885       tree decl = pending_templates->tinst->decl;
14886
14887       error ("template instantiation depth exceeds maximum of %d"
14888              " instantiating %q+D, possibly from virtual table generation"
14889              " (use -ftemplate-depth-NN to increase the maximum)",
14890              max_tinst_depth, decl);
14891       if (TREE_CODE (decl) == FUNCTION_DECL)
14892         /* Pretend that we defined it.  */
14893         DECL_INITIAL (decl) = error_mark_node;
14894       return;
14895     }
14896
14897   do
14898     {
14899       struct pending_template **t = &pending_templates;
14900       struct pending_template *last = NULL;
14901       reconsider = 0;
14902       while (*t)
14903         {
14904           tree instantiation = reopen_tinst_level ((*t)->tinst);
14905           bool complete = false;
14906
14907           if (TYPE_P (instantiation))
14908             {
14909               tree fn;
14910
14911               if (!COMPLETE_TYPE_P (instantiation))
14912                 {
14913                   instantiate_class_template (instantiation);
14914                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
14915                     for (fn = TYPE_METHODS (instantiation);
14916                          fn;
14917                          fn = TREE_CHAIN (fn))
14918                       if (! DECL_ARTIFICIAL (fn))
14919                         instantiate_decl (fn,
14920                                           /*defer_ok=*/0,
14921                                           /*expl_inst_class_mem_p=*/false);
14922                   if (COMPLETE_TYPE_P (instantiation))
14923                     reconsider = 1;
14924                 }
14925
14926               complete = COMPLETE_TYPE_P (instantiation);
14927             }
14928           else
14929             {
14930               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
14931                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
14932                 {
14933                   instantiation
14934                     = instantiate_decl (instantiation,
14935                                         /*defer_ok=*/0,
14936                                         /*expl_inst_class_mem_p=*/false);
14937                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
14938                     reconsider = 1;
14939                 }
14940
14941               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
14942                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
14943             }
14944
14945           if (complete)
14946             /* If INSTANTIATION has been instantiated, then we don't
14947                need to consider it again in the future.  */
14948             *t = (*t)->next;
14949           else
14950             {
14951               last = *t;
14952               t = &(*t)->next;
14953             }
14954           tinst_depth = 0;
14955           current_tinst_level = NULL;
14956         }
14957       last_pending_template = last;
14958     }
14959   while (reconsider);
14960
14961   input_location = saved_loc;
14962   in_system_header = saved_in_system_header;
14963 }
14964
14965 /* Substitute ARGVEC into T, which is a list of initializers for
14966    either base class or a non-static data member.  The TREE_PURPOSEs
14967    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
14968    instantiate_decl.  */
14969
14970 static tree
14971 tsubst_initializer_list (tree t, tree argvec)
14972 {
14973   tree inits = NULL_TREE;
14974
14975   for (; t; t = TREE_CHAIN (t))
14976     {
14977       tree decl;
14978       tree init;
14979       tree expanded_bases = NULL_TREE;
14980       tree expanded_arguments = NULL_TREE;
14981       int i, len = 1;
14982
14983       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
14984         {
14985           tree expr;
14986           tree arg;
14987
14988           /* Expand the base class expansion type into separate base
14989              classes.  */
14990           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
14991                                                  tf_warning_or_error,
14992                                                  NULL_TREE);
14993           if (expanded_bases == error_mark_node)
14994             continue;
14995           
14996           /* We'll be building separate TREE_LISTs of arguments for
14997              each base.  */
14998           len = TREE_VEC_LENGTH (expanded_bases);
14999           expanded_arguments = make_tree_vec (len);
15000           for (i = 0; i < len; i++)
15001             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15002
15003           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15004              expand each argument in the TREE_VALUE of t.  */
15005           expr = make_node (EXPR_PACK_EXPANSION);
15006           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15007             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15008
15009           /* Substitute parameter packs into each argument in the
15010              TREE_LIST.  */
15011           in_base_initializer = 1;
15012           for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15013             {
15014               tree expanded_exprs;
15015
15016               /* Expand the argument.  */
15017               SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15018               expanded_exprs = tsubst_pack_expansion (expr, argvec,
15019                                                       tf_warning_or_error,
15020                                                       NULL_TREE);
15021
15022               /* Prepend each of the expanded expressions to the
15023                  corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15024               for (i = 0; i < len; i++)
15025                 {
15026                   TREE_VEC_ELT (expanded_arguments, i) = 
15027                     tree_cons (NULL_TREE, TREE_VEC_ELT (expanded_exprs, i),
15028                                TREE_VEC_ELT (expanded_arguments, i));
15029                 }
15030             }
15031           in_base_initializer = 0;
15032
15033           /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15034              since we built them backwards.  */
15035           for (i = 0; i < len; i++)
15036             {
15037               TREE_VEC_ELT (expanded_arguments, i) = 
15038                 nreverse (TREE_VEC_ELT (expanded_arguments, i));
15039             }
15040         }
15041
15042       for (i = 0; i < len; ++i)
15043         {
15044           if (expanded_bases)
15045             {
15046               decl = TREE_VEC_ELT (expanded_bases, i);
15047               decl = expand_member_init (decl);
15048               init = TREE_VEC_ELT (expanded_arguments, i);
15049             }
15050           else
15051             {
15052               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15053                                   tf_warning_or_error, NULL_TREE);
15054
15055               decl = expand_member_init (decl);
15056               if (decl && !DECL_P (decl))
15057                 in_base_initializer = 1;
15058
15059               init = tsubst_expr (TREE_VALUE (t), argvec, 
15060                                   tf_warning_or_error, NULL_TREE,
15061                                   /*integral_constant_expression_p=*/false);
15062               in_base_initializer = 0;
15063             }
15064
15065           if (decl)
15066             {
15067               init = build_tree_list (decl, init);
15068               TREE_CHAIN (init) = inits;
15069               inits = init;
15070             }
15071         }
15072     }
15073   return inits;
15074 }
15075
15076 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
15077
15078 static void
15079 set_current_access_from_decl (tree decl)
15080 {
15081   if (TREE_PRIVATE (decl))
15082     current_access_specifier = access_private_node;
15083   else if (TREE_PROTECTED (decl))
15084     current_access_specifier = access_protected_node;
15085   else
15086     current_access_specifier = access_public_node;
15087 }
15088
15089 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
15090    is the instantiation (which should have been created with
15091    start_enum) and ARGS are the template arguments to use.  */
15092
15093 static void
15094 tsubst_enum (tree tag, tree newtag, tree args)
15095 {
15096   tree e;
15097
15098   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
15099     {
15100       tree value;
15101       tree decl;
15102
15103       decl = TREE_VALUE (e);
15104       /* Note that in a template enum, the TREE_VALUE is the
15105          CONST_DECL, not the corresponding INTEGER_CST.  */
15106       value = tsubst_expr (DECL_INITIAL (decl),
15107                            args, tf_warning_or_error, NULL_TREE,
15108                            /*integral_constant_expression_p=*/true);
15109
15110       /* Give this enumeration constant the correct access.  */
15111       set_current_access_from_decl (decl);
15112
15113       /* Actually build the enumerator itself.  */
15114       build_enumerator (DECL_NAME (decl), value, newtag);
15115     }
15116
15117   finish_enum (newtag);
15118   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
15119     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
15120 }
15121
15122 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
15123    its type -- but without substituting the innermost set of template
15124    arguments.  So, innermost set of template parameters will appear in
15125    the type.  */
15126
15127 tree
15128 get_mostly_instantiated_function_type (tree decl)
15129 {
15130   tree fn_type;
15131   tree tmpl;
15132   tree targs;
15133   tree tparms;
15134   int parm_depth;
15135
15136   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15137   targs = DECL_TI_ARGS (decl);
15138   tparms = DECL_TEMPLATE_PARMS (tmpl);
15139   parm_depth = TMPL_PARMS_DEPTH (tparms);
15140
15141   /* There should be as many levels of arguments as there are levels
15142      of parameters.  */
15143   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
15144
15145   fn_type = TREE_TYPE (tmpl);
15146
15147   if (parm_depth == 1)
15148     /* No substitution is necessary.  */
15149     ;
15150   else
15151     {
15152       int i, save_access_control;
15153       tree partial_args;
15154
15155       /* Replace the innermost level of the TARGS with NULL_TREEs to
15156          let tsubst know not to substitute for those parameters.  */
15157       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
15158       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
15159         SET_TMPL_ARGS_LEVEL (partial_args, i,
15160                              TMPL_ARGS_LEVEL (targs, i));
15161       SET_TMPL_ARGS_LEVEL (partial_args,
15162                            TMPL_ARGS_DEPTH (targs),
15163                            make_tree_vec (DECL_NTPARMS (tmpl)));
15164
15165       /* Disable access control as this function is used only during
15166          name-mangling.  */
15167       save_access_control = flag_access_control;
15168       flag_access_control = 0;
15169
15170       ++processing_template_decl;
15171       /* Now, do the (partial) substitution to figure out the
15172          appropriate function type.  */
15173       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
15174       --processing_template_decl;
15175
15176       /* Substitute into the template parameters to obtain the real
15177          innermost set of parameters.  This step is important if the
15178          innermost set of template parameters contains value
15179          parameters whose types depend on outer template parameters.  */
15180       TREE_VEC_LENGTH (partial_args)--;
15181       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
15182
15183       flag_access_control = save_access_control;
15184     }
15185
15186   return fn_type;
15187 }
15188
15189 /* Return truthvalue if we're processing a template different from
15190    the last one involved in diagnostics.  */
15191 int
15192 problematic_instantiation_changed (void)
15193 {
15194   return last_template_error_tick != tinst_level_tick;
15195 }
15196
15197 /* Remember current template involved in diagnostics.  */
15198 void
15199 record_last_problematic_instantiation (void)
15200 {
15201   last_template_error_tick = tinst_level_tick;
15202 }
15203
15204 struct tinst_level *
15205 current_instantiation (void)
15206 {
15207   return current_tinst_level;
15208 }
15209
15210 /* [temp.param] Check that template non-type parm TYPE is of an allowable
15211    type. Return zero for ok, nonzero for disallowed. Issue error and
15212    warning messages under control of COMPLAIN.  */
15213
15214 static int
15215 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
15216 {
15217   if (INTEGRAL_TYPE_P (type))
15218     return 0;
15219   else if (POINTER_TYPE_P (type))
15220     return 0;
15221   else if (TYPE_PTR_TO_MEMBER_P (type))
15222     return 0;
15223   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15224     return 0;
15225   else if (TREE_CODE (type) == TYPENAME_TYPE)
15226     return 0;
15227
15228   if (complain & tf_error)
15229     error ("%q#T is not a valid type for a template constant parameter", type);
15230   return 1;
15231 }
15232
15233 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
15234    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
15235
15236 static bool
15237 dependent_type_p_r (tree type)
15238 {
15239   tree scope;
15240
15241   /* [temp.dep.type]
15242
15243      A type is dependent if it is:
15244
15245      -- a template parameter. Template template parameters are types
15246         for us (since TYPE_P holds true for them) so we handle
15247         them here.  */
15248   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
15249       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
15250     return true;
15251   /* -- a qualified-id with a nested-name-specifier which contains a
15252         class-name that names a dependent type or whose unqualified-id
15253         names a dependent type.  */
15254   if (TREE_CODE (type) == TYPENAME_TYPE)
15255     return true;
15256   /* -- a cv-qualified type where the cv-unqualified type is
15257         dependent.  */
15258   type = TYPE_MAIN_VARIANT (type);
15259   /* -- a compound type constructed from any dependent type.  */
15260   if (TYPE_PTR_TO_MEMBER_P (type))
15261     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
15262             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
15263                                            (type)));
15264   else if (TREE_CODE (type) == POINTER_TYPE
15265            || TREE_CODE (type) == REFERENCE_TYPE)
15266     return dependent_type_p (TREE_TYPE (type));
15267   else if (TREE_CODE (type) == FUNCTION_TYPE
15268            || TREE_CODE (type) == METHOD_TYPE)
15269     {
15270       tree arg_type;
15271
15272       if (dependent_type_p (TREE_TYPE (type)))
15273         return true;
15274       for (arg_type = TYPE_ARG_TYPES (type);
15275            arg_type;
15276            arg_type = TREE_CHAIN (arg_type))
15277         if (dependent_type_p (TREE_VALUE (arg_type)))
15278           return true;
15279       return false;
15280     }
15281   /* -- an array type constructed from any dependent type or whose
15282         size is specified by a constant expression that is
15283         value-dependent.  */
15284   if (TREE_CODE (type) == ARRAY_TYPE)
15285     {
15286       if (TYPE_DOMAIN (type)
15287           && ((value_dependent_expression_p
15288                (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))
15289               || (type_dependent_expression_p
15290                   (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))))
15291         return true;
15292       return dependent_type_p (TREE_TYPE (type));
15293     }
15294
15295   /* -- a template-id in which either the template name is a template
15296      parameter ...  */
15297   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
15298     return true;
15299   /* ... or any of the template arguments is a dependent type or
15300         an expression that is type-dependent or value-dependent.  */
15301   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
15302            && (any_dependent_template_arguments_p
15303                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
15304     return true;
15305
15306   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
15307      argument of the `typeof' expression is not type-dependent, then
15308      it should already been have resolved.  */
15309   if (TREE_CODE (type) == TYPEOF_TYPE
15310       || TREE_CODE (type) == DECLTYPE_TYPE)
15311     return true;
15312
15313   /* A template argument pack is dependent if any of its packed
15314      arguments are.  */
15315   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
15316     {
15317       tree args = ARGUMENT_PACK_ARGS (type);
15318       int i, len = TREE_VEC_LENGTH (args);
15319       for (i = 0; i < len; ++i)
15320         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
15321           return true;
15322     }
15323
15324   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
15325      be template parameters.  */
15326   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
15327     return true;
15328
15329   /* The standard does not specifically mention types that are local
15330      to template functions or local classes, but they should be
15331      considered dependent too.  For example:
15332
15333        template <int I> void f() {
15334          enum E { a = I };
15335          S<sizeof (E)> s;
15336        }
15337
15338      The size of `E' cannot be known until the value of `I' has been
15339      determined.  Therefore, `E' must be considered dependent.  */
15340   scope = TYPE_CONTEXT (type);
15341   if (scope && TYPE_P (scope))
15342     return dependent_type_p (scope);
15343   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
15344     return type_dependent_expression_p (scope);
15345
15346   /* Other types are non-dependent.  */
15347   return false;
15348 }
15349
15350 /* Returns TRUE if TYPE is dependent, in the sense of
15351    [temp.dep.type].  */
15352
15353 bool
15354 dependent_type_p (tree type)
15355 {
15356   /* If there are no template parameters in scope, then there can't be
15357      any dependent types.  */
15358   if (!processing_template_decl)
15359     {
15360       /* If we are not processing a template, then nobody should be
15361          providing us with a dependent type.  */
15362       gcc_assert (type);
15363       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM);
15364       return false;
15365     }
15366
15367   /* If the type is NULL, we have not computed a type for the entity
15368      in question; in that case, the type is dependent.  */
15369   if (!type)
15370     return true;
15371
15372   /* Erroneous types can be considered non-dependent.  */
15373   if (type == error_mark_node)
15374     return false;
15375
15376   /* If we have not already computed the appropriate value for TYPE,
15377      do so now.  */
15378   if (!TYPE_DEPENDENT_P_VALID (type))
15379     {
15380       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
15381       TYPE_DEPENDENT_P_VALID (type) = 1;
15382     }
15383
15384   return TYPE_DEPENDENT_P (type);
15385 }
15386
15387 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
15388
15389 static bool
15390 dependent_scope_ref_p (tree expression, bool criterion (tree))
15391 {
15392   tree scope;
15393   tree name;
15394
15395   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
15396
15397   if (!TYPE_P (TREE_OPERAND (expression, 0)))
15398     return true;
15399
15400   scope = TREE_OPERAND (expression, 0);
15401   name = TREE_OPERAND (expression, 1);
15402
15403   /* [temp.dep.expr]
15404
15405      An id-expression is type-dependent if it contains a
15406      nested-name-specifier that contains a class-name that names a
15407      dependent type.  */
15408   /* The suggested resolution to Core Issue 2 implies that if the
15409      qualifying type is the current class, then we must peek
15410      inside it.  */
15411   if (DECL_P (name)
15412       && currently_open_class (scope)
15413       && !criterion (name))
15414     return false;
15415   if (dependent_type_p (scope))
15416     return true;
15417
15418   return false;
15419 }
15420
15421 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
15422    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
15423    expression.  */
15424
15425 bool
15426 value_dependent_expression_p (tree expression)
15427 {
15428   if (!processing_template_decl)
15429     return false;
15430
15431   /* A name declared with a dependent type.  */
15432   if (DECL_P (expression) && type_dependent_expression_p (expression))
15433     return true;
15434
15435   switch (TREE_CODE (expression))
15436     {
15437     case IDENTIFIER_NODE:
15438       /* A name that has not been looked up -- must be dependent.  */
15439       return true;
15440
15441     case TEMPLATE_PARM_INDEX:
15442       /* A non-type template parm.  */
15443       return true;
15444
15445     case CONST_DECL:
15446       /* A non-type template parm.  */
15447       if (DECL_TEMPLATE_PARM_P (expression))
15448         return true;
15449       return false;
15450
15451     case VAR_DECL:
15452        /* A constant with integral or enumeration type and is initialized
15453           with an expression that is value-dependent.  */
15454       if (DECL_INITIAL (expression)
15455           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
15456           && value_dependent_expression_p (DECL_INITIAL (expression)))
15457         return true;
15458       return false;
15459
15460     case DYNAMIC_CAST_EXPR:
15461     case STATIC_CAST_EXPR:
15462     case CONST_CAST_EXPR:
15463     case REINTERPRET_CAST_EXPR:
15464     case CAST_EXPR:
15465       /* These expressions are value-dependent if the type to which
15466          the cast occurs is dependent or the expression being casted
15467          is value-dependent.  */
15468       {
15469         tree type = TREE_TYPE (expression);
15470
15471         if (dependent_type_p (type))
15472           return true;
15473
15474         /* A functional cast has a list of operands.  */
15475         expression = TREE_OPERAND (expression, 0);
15476         if (!expression)
15477           {
15478             /* If there are no operands, it must be an expression such
15479                as "int()". This should not happen for aggregate types
15480                because it would form non-constant expressions.  */
15481             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
15482
15483             return false;
15484           }
15485
15486         if (TREE_CODE (expression) == TREE_LIST)
15487           return any_value_dependent_elements_p (expression);
15488
15489         return value_dependent_expression_p (expression);
15490       }
15491
15492     case SIZEOF_EXPR:
15493     case ALIGNOF_EXPR:
15494       /* A `sizeof' expression is value-dependent if the operand is
15495          type-dependent or is a pack expansion.  */
15496       expression = TREE_OPERAND (expression, 0);
15497       if (PACK_EXPANSION_P (expression))
15498         return true;
15499       else if (TYPE_P (expression))
15500         return dependent_type_p (expression);
15501       return type_dependent_expression_p (expression);
15502
15503     case SCOPE_REF:
15504       return dependent_scope_ref_p (expression, value_dependent_expression_p);
15505
15506     case COMPONENT_REF:
15507       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
15508               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
15509
15510     case CALL_EXPR:
15511       /* A CALL_EXPR may appear in a constant expression if it is a
15512          call to a builtin function, e.g., __builtin_constant_p.  All
15513          such calls are value-dependent.  */
15514       return true;
15515
15516     case NONTYPE_ARGUMENT_PACK:
15517       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
15518          is value-dependent.  */
15519       {
15520         tree values = ARGUMENT_PACK_ARGS (expression);
15521         int i, len = TREE_VEC_LENGTH (values);
15522         
15523         for (i = 0; i < len; ++i)
15524           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
15525             return true;
15526         
15527         return false;
15528       }
15529
15530     case TRAIT_EXPR:
15531       {
15532         tree type2 = TRAIT_EXPR_TYPE2 (expression);
15533         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
15534                 || (type2 ? dependent_type_p (type2) : false));
15535       }
15536
15537     case MODOP_EXPR:
15538       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
15539               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
15540
15541     default:
15542       /* A constant expression is value-dependent if any subexpression is
15543          value-dependent.  */
15544       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
15545         {
15546         case tcc_reference:
15547         case tcc_unary:
15548           return (value_dependent_expression_p
15549                   (TREE_OPERAND (expression, 0)));
15550
15551         case tcc_comparison:
15552         case tcc_binary:
15553           return ((value_dependent_expression_p
15554                    (TREE_OPERAND (expression, 0)))
15555                   || (value_dependent_expression_p
15556                       (TREE_OPERAND (expression, 1))));
15557
15558         case tcc_expression:
15559         case tcc_vl_exp:
15560           {
15561             int i;
15562             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
15563               /* In some cases, some of the operands may be missing.
15564                  (For example, in the case of PREDECREMENT_EXPR, the
15565                  amount to increment by may be missing.)  That doesn't
15566                  make the expression dependent.  */
15567               if (TREE_OPERAND (expression, i)
15568                   && (value_dependent_expression_p
15569                       (TREE_OPERAND (expression, i))))
15570                 return true;
15571             return false;
15572           }
15573
15574         default:
15575           break;
15576         }
15577     }
15578
15579   /* The expression is not value-dependent.  */
15580   return false;
15581 }
15582
15583 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
15584    [temp.dep.expr].  */
15585
15586 bool
15587 type_dependent_expression_p (tree expression)
15588 {
15589   if (!processing_template_decl)
15590     return false;
15591
15592   if (expression == error_mark_node)
15593     return false;
15594
15595   /* An unresolved name is always dependent.  */
15596   if (TREE_CODE (expression) == IDENTIFIER_NODE
15597       || TREE_CODE (expression) == USING_DECL)
15598     return true;
15599
15600   /* Some expression forms are never type-dependent.  */
15601   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
15602       || TREE_CODE (expression) == SIZEOF_EXPR
15603       || TREE_CODE (expression) == ALIGNOF_EXPR
15604       || TREE_CODE (expression) == TRAIT_EXPR
15605       || TREE_CODE (expression) == TYPEID_EXPR
15606       || TREE_CODE (expression) == DELETE_EXPR
15607       || TREE_CODE (expression) == VEC_DELETE_EXPR
15608       || TREE_CODE (expression) == THROW_EXPR)
15609     return false;
15610
15611   /* The types of these expressions depends only on the type to which
15612      the cast occurs.  */
15613   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
15614       || TREE_CODE (expression) == STATIC_CAST_EXPR
15615       || TREE_CODE (expression) == CONST_CAST_EXPR
15616       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
15617       || TREE_CODE (expression) == CAST_EXPR)
15618     return dependent_type_p (TREE_TYPE (expression));
15619
15620   /* The types of these expressions depends only on the type created
15621      by the expression.  */
15622   if (TREE_CODE (expression) == NEW_EXPR
15623       || TREE_CODE (expression) == VEC_NEW_EXPR)
15624     {
15625       /* For NEW_EXPR tree nodes created inside a template, either
15626          the object type itself or a TREE_LIST may appear as the
15627          operand 1.  */
15628       tree type = TREE_OPERAND (expression, 1);
15629       if (TREE_CODE (type) == TREE_LIST)
15630         /* This is an array type.  We need to check array dimensions
15631            as well.  */
15632         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
15633                || value_dependent_expression_p
15634                     (TREE_OPERAND (TREE_VALUE (type), 1));
15635       else
15636         return dependent_type_p (type);
15637     }
15638
15639   if (TREE_CODE (expression) == SCOPE_REF
15640       && dependent_scope_ref_p (expression,
15641                                 type_dependent_expression_p))
15642     return true;
15643
15644   if (TREE_CODE (expression) == FUNCTION_DECL
15645       && DECL_LANG_SPECIFIC (expression)
15646       && DECL_TEMPLATE_INFO (expression)
15647       && (any_dependent_template_arguments_p
15648           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
15649     return true;
15650
15651   if (TREE_CODE (expression) == TEMPLATE_DECL
15652       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
15653     return false;
15654
15655   if (TREE_CODE (expression) == STMT_EXPR)
15656     expression = stmt_expr_value_expr (expression);
15657
15658   if (TREE_TYPE (expression) == unknown_type_node)
15659     {
15660       if (TREE_CODE (expression) == ADDR_EXPR)
15661         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
15662       if (TREE_CODE (expression) == COMPONENT_REF
15663           || TREE_CODE (expression) == OFFSET_REF)
15664         {
15665           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
15666             return true;
15667           expression = TREE_OPERAND (expression, 1);
15668           if (TREE_CODE (expression) == IDENTIFIER_NODE)
15669             return false;
15670         }
15671       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
15672       if (TREE_CODE (expression) == SCOPE_REF)
15673         return false;
15674
15675       if (TREE_CODE (expression) == BASELINK)
15676         expression = BASELINK_FUNCTIONS (expression);
15677
15678       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
15679         {
15680           if (any_dependent_template_arguments_p
15681               (TREE_OPERAND (expression, 1)))
15682             return true;
15683           expression = TREE_OPERAND (expression, 0);
15684         }
15685       gcc_assert (TREE_CODE (expression) == OVERLOAD
15686                   || TREE_CODE (expression) == FUNCTION_DECL);
15687
15688       while (expression)
15689         {
15690           if (type_dependent_expression_p (OVL_CURRENT (expression)))
15691             return true;
15692           expression = OVL_NEXT (expression);
15693         }
15694       return false;
15695     }
15696
15697   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
15698
15699   return (dependent_type_p (TREE_TYPE (expression)));
15700 }
15701
15702 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
15703    contains a type-dependent expression.  */
15704
15705 bool
15706 any_type_dependent_arguments_p (const_tree args)
15707 {
15708   while (args)
15709     {
15710       tree arg = TREE_VALUE (args);
15711
15712       if (type_dependent_expression_p (arg))
15713         return true;
15714       args = TREE_CHAIN (args);
15715     }
15716   return false;
15717 }
15718
15719 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
15720    expressions) contains any value-dependent expressions.  */
15721
15722 bool
15723 any_value_dependent_elements_p (const_tree list)
15724 {
15725   for (; list; list = TREE_CHAIN (list))
15726     if (value_dependent_expression_p (TREE_VALUE (list)))
15727       return true;
15728
15729   return false;
15730 }
15731
15732 /* Returns TRUE if the ARG (a template argument) is dependent.  */
15733
15734 bool
15735 dependent_template_arg_p (tree arg)
15736 {
15737   if (!processing_template_decl)
15738     return false;
15739
15740   if (TREE_CODE (arg) == TEMPLATE_DECL
15741       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15742     return dependent_template_p (arg);
15743   else if (ARGUMENT_PACK_P (arg))
15744     {
15745       tree args = ARGUMENT_PACK_ARGS (arg);
15746       int i, len = TREE_VEC_LENGTH (args);
15747       for (i = 0; i < len; ++i)
15748         {
15749           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
15750             return true;
15751         }
15752
15753       return false;
15754     }
15755   else if (TYPE_P (arg))
15756     return dependent_type_p (arg);
15757   else
15758     return (type_dependent_expression_p (arg)
15759             || value_dependent_expression_p (arg));
15760 }
15761
15762 /* Returns true if ARGS (a collection of template arguments) contains
15763    any types that require structural equality testing.  */
15764
15765 bool
15766 any_template_arguments_need_structural_equality_p (tree args)
15767 {
15768   int i;
15769   int j;
15770
15771   if (!args)
15772     return false;
15773   if (args == error_mark_node)
15774     return true;
15775
15776   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
15777     {
15778       tree level = TMPL_ARGS_LEVEL (args, i + 1);
15779       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
15780         {
15781           tree arg = TREE_VEC_ELT (level, j);
15782           tree packed_args = NULL_TREE;
15783           int k, len = 1;
15784
15785           if (ARGUMENT_PACK_P (arg))
15786             {
15787               /* Look inside the argument pack.  */
15788               packed_args = ARGUMENT_PACK_ARGS (arg);
15789               len = TREE_VEC_LENGTH (packed_args);
15790             }
15791
15792           for (k = 0; k < len; ++k)
15793             {
15794               if (packed_args)
15795                 arg = TREE_VEC_ELT (packed_args, k);
15796
15797               if (error_operand_p (arg))
15798                 return true;
15799               else if (TREE_CODE (arg) == TEMPLATE_DECL
15800                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15801                 continue;
15802               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
15803                 return true;
15804               else if (!TYPE_P (arg) && TREE_TYPE (arg)
15805                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
15806                 return true;
15807             }
15808         }
15809     }
15810
15811   return false;
15812 }
15813
15814 /* Returns true if ARGS (a collection of template arguments) contains
15815    any dependent arguments.  */
15816
15817 bool
15818 any_dependent_template_arguments_p (const_tree args)
15819 {
15820   int i;
15821   int j;
15822
15823   if (!args)
15824     return false;
15825   if (args == error_mark_node)
15826     return true;
15827
15828   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
15829     {
15830       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
15831       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
15832         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
15833           return true;
15834     }
15835
15836   return false;
15837 }
15838
15839 /* Returns TRUE if the template TMPL is dependent.  */
15840
15841 bool
15842 dependent_template_p (tree tmpl)
15843 {
15844   if (TREE_CODE (tmpl) == OVERLOAD)
15845     {
15846       while (tmpl)
15847         {
15848           if (dependent_template_p (OVL_FUNCTION (tmpl)))
15849             return true;
15850           tmpl = OVL_CHAIN (tmpl);
15851         }
15852       return false;
15853     }
15854
15855   /* Template template parameters are dependent.  */
15856   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
15857       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
15858     return true;
15859   /* So are names that have not been looked up.  */
15860   if (TREE_CODE (tmpl) == SCOPE_REF
15861       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
15862     return true;
15863   /* So are member templates of dependent classes.  */
15864   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
15865     return dependent_type_p (DECL_CONTEXT (tmpl));
15866   return false;
15867 }
15868
15869 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
15870
15871 bool
15872 dependent_template_id_p (tree tmpl, tree args)
15873 {
15874   return (dependent_template_p (tmpl)
15875           || any_dependent_template_arguments_p (args));
15876 }
15877
15878 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
15879    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
15880    no such TYPE can be found.  Note that this function peers inside
15881    uninstantiated templates and therefore should be used only in
15882    extremely limited situations.  ONLY_CURRENT_P restricts this
15883    peering to the currently open classes hierarchy (which is required
15884    when comparing types).  */
15885
15886 tree
15887 resolve_typename_type (tree type, bool only_current_p)
15888 {
15889   tree scope;
15890   tree name;
15891   tree decl;
15892   int quals;
15893   tree pushed_scope;
15894   tree result;
15895
15896   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
15897
15898   scope = TYPE_CONTEXT (type);
15899   name = TYPE_IDENTIFIER (type);
15900
15901   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
15902      it first before we can figure out what NAME refers to.  */
15903   if (TREE_CODE (scope) == TYPENAME_TYPE)
15904     scope = resolve_typename_type (scope, only_current_p);
15905   /* If we don't know what SCOPE refers to, then we cannot resolve the
15906      TYPENAME_TYPE.  */
15907   if (TREE_CODE (scope) == TYPENAME_TYPE)
15908     return type;
15909   /* If the SCOPE is a template type parameter, we have no way of
15910      resolving the name.  */
15911   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
15912     return type;
15913   /* If the SCOPE is not the current instantiation, there's no reason
15914      to look inside it.  */
15915   if (only_current_p && !currently_open_class (scope))
15916     return type;
15917   /* If SCOPE isn't the template itself, it will not have a valid
15918      TYPE_FIELDS list.  */
15919   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
15920     /* scope is either the template itself or a compatible instantiation
15921        like X<T>, so look up the name in the original template.  */
15922     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
15923   else
15924     /* scope is a partial instantiation, so we can't do the lookup or we
15925        will lose the template arguments.  */
15926     return type;
15927   /* Enter the SCOPE so that name lookup will be resolved as if we
15928      were in the class definition.  In particular, SCOPE will no
15929      longer be considered a dependent type.  */
15930   pushed_scope = push_scope (scope);
15931   /* Look up the declaration.  */
15932   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
15933
15934   result = NULL_TREE;
15935   
15936   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
15937      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
15938   if (!decl)
15939     /*nop*/;
15940   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
15941            && TREE_CODE (decl) == TYPE_DECL)
15942     {
15943       result = TREE_TYPE (decl);
15944       if (result == error_mark_node)
15945         result = NULL_TREE;
15946     }
15947   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
15948            && DECL_CLASS_TEMPLATE_P (decl))
15949     {
15950       tree tmpl;
15951       tree args;
15952       /* Obtain the template and the arguments.  */
15953       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
15954       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
15955       /* Instantiate the template.  */
15956       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
15957                                       /*entering_scope=*/0,
15958                                       tf_error | tf_user);
15959       if (result == error_mark_node)
15960         result = NULL_TREE;
15961     }
15962   
15963   /* Leave the SCOPE.  */
15964   if (pushed_scope)
15965     pop_scope (pushed_scope);
15966
15967   /* If we failed to resolve it, return the original typename.  */
15968   if (!result)
15969     return type;
15970   
15971   /* If lookup found a typename type, resolve that too.  */
15972   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
15973     {
15974       /* Ill-formed programs can cause infinite recursion here, so we
15975          must catch that.  */
15976       TYPENAME_IS_RESOLVING_P (type) = 1;
15977       result = resolve_typename_type (result, only_current_p);
15978       TYPENAME_IS_RESOLVING_P (type) = 0;
15979     }
15980   
15981   /* Qualify the resulting type.  */
15982   quals = cp_type_quals (type);
15983   if (quals)
15984     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
15985
15986   return result;
15987 }
15988
15989 /* EXPR is an expression which is not type-dependent.  Return a proxy
15990    for EXPR that can be used to compute the types of larger
15991    expressions containing EXPR.  */
15992
15993 tree
15994 build_non_dependent_expr (tree expr)
15995 {
15996   tree inner_expr;
15997
15998   /* Preserve null pointer constants so that the type of things like
15999      "p == 0" where "p" is a pointer can be determined.  */
16000   if (null_ptr_cst_p (expr))
16001     return expr;
16002   /* Preserve OVERLOADs; the functions must be available to resolve
16003      types.  */
16004   inner_expr = expr;
16005   if (TREE_CODE (inner_expr) == STMT_EXPR)
16006     inner_expr = stmt_expr_value_expr (inner_expr);
16007   if (TREE_CODE (inner_expr) == ADDR_EXPR)
16008     inner_expr = TREE_OPERAND (inner_expr, 0);
16009   if (TREE_CODE (inner_expr) == COMPONENT_REF)
16010     inner_expr = TREE_OPERAND (inner_expr, 1);
16011   if (is_overloaded_fn (inner_expr)
16012       || TREE_CODE (inner_expr) == OFFSET_REF)
16013     return expr;
16014   /* There is no need to return a proxy for a variable.  */
16015   if (TREE_CODE (expr) == VAR_DECL)
16016     return expr;
16017   /* Preserve string constants; conversions from string constants to
16018      "char *" are allowed, even though normally a "const char *"
16019      cannot be used to initialize a "char *".  */
16020   if (TREE_CODE (expr) == STRING_CST)
16021     return expr;
16022   /* Preserve arithmetic constants, as an optimization -- there is no
16023      reason to create a new node.  */
16024   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
16025     return expr;
16026   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
16027      There is at least one place where we want to know that a
16028      particular expression is a throw-expression: when checking a ?:
16029      expression, there are special rules if the second or third
16030      argument is a throw-expression.  */
16031   if (TREE_CODE (expr) == THROW_EXPR)
16032     return expr;
16033
16034   if (TREE_CODE (expr) == COND_EXPR)
16035     return build3 (COND_EXPR,
16036                    TREE_TYPE (expr),
16037                    TREE_OPERAND (expr, 0),
16038                    (TREE_OPERAND (expr, 1)
16039                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
16040                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
16041                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
16042   if (TREE_CODE (expr) == COMPOUND_EXPR
16043       && !COMPOUND_EXPR_OVERLOADED (expr))
16044     return build2 (COMPOUND_EXPR,
16045                    TREE_TYPE (expr),
16046                    TREE_OPERAND (expr, 0),
16047                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
16048
16049   /* If the type is unknown, it can't really be non-dependent */
16050   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
16051
16052   /* Otherwise, build a NON_DEPENDENT_EXPR.
16053
16054      REFERENCE_TYPEs are not stripped for expressions in templates
16055      because doing so would play havoc with mangling.  Consider, for
16056      example:
16057
16058        template <typename T> void f<T& g>() { g(); }
16059
16060      In the body of "f", the expression for "g" will have
16061      REFERENCE_TYPE, even though the standard says that it should
16062      not.  The reason is that we must preserve the syntactic form of
16063      the expression so that mangling (say) "f<g>" inside the body of
16064      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
16065      stripped here.  */
16066   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
16067 }
16068
16069 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
16070    Return a new TREE_LIST with the various arguments replaced with
16071    equivalent non-dependent expressions.  */
16072
16073 tree
16074 build_non_dependent_args (tree args)
16075 {
16076   tree a;
16077   tree new_args;
16078
16079   new_args = NULL_TREE;
16080   for (a = args; a; a = TREE_CHAIN (a))
16081     new_args = tree_cons (NULL_TREE,
16082                           build_non_dependent_expr (TREE_VALUE (a)),
16083                           new_args);
16084   return nreverse (new_args);
16085 }
16086
16087 #include "gt-cp-pt.h"