OSDN Git Service

PR c++/49663
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010, 2011
4    Free Software Foundation, Inc.
5    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6    Rewritten by Jason Merrill (jason@cygnus.com).
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* Known bugs or deficiencies include:
25
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "tree.h"
34 #include "intl.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "cp-tree.h"
38 #include "c-family/c-common.h"
39 #include "c-family/c-objc.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "toplev.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 GTY ((chain_next ("%h.next"))) pending_template {
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 typedef struct GTY(()) spec_entry
85 {
86   tree tmpl;
87   tree args;
88   tree spec;
89 } spec_entry;
90
91 static GTY ((param_is (spec_entry)))
92   htab_t decl_specializations;
93
94 static GTY ((param_is (spec_entry)))
95   htab_t type_specializations;
96
97 /* Contains canonical template parameter types. The vector is indexed by
98    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
99    TREE_LIST, whose TREE_VALUEs contain the canonical template
100    parameters of various types and levels.  */
101 static GTY(()) VEC(tree,gc) *canonical_template_parms;
102
103 #define UNIFY_ALLOW_NONE 0
104 #define UNIFY_ALLOW_MORE_CV_QUAL 1
105 #define UNIFY_ALLOW_LESS_CV_QUAL 2
106 #define UNIFY_ALLOW_DERIVED 4
107 #define UNIFY_ALLOW_INTEGER 8
108 #define UNIFY_ALLOW_OUTER_LEVEL 16
109 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
110 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
111
112 static void push_access_scope (tree);
113 static void pop_access_scope (tree);
114 static void push_deduction_access_scope (tree);
115 static void pop_deduction_access_scope (tree);
116 static bool resolve_overloaded_unification (tree, tree, tree, tree,
117                                             unification_kind_t, int);
118 static int try_one_overload (tree, tree, tree, tree, tree,
119                              unification_kind_t, int, bool);
120 static int unify (tree, tree, tree, tree, int);
121 static void add_pending_template (tree);
122 static tree reopen_tinst_level (struct tinst_level *);
123 static tree tsubst_initializer_list (tree, tree);
124 static tree get_class_bindings (tree, tree, tree);
125 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
126                                    bool, bool);
127 static void tsubst_enum (tree, tree, tree);
128 static tree add_to_template_args (tree, tree);
129 static tree add_outermost_template_args (tree, tree);
130 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
131 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
132                                              tree);
133 static int type_unification_real (tree, tree, tree, const tree *,
134                                   unsigned int, int, unification_kind_t, int);
135 static void note_template_header (int);
136 static tree convert_nontype_argument_function (tree, tree);
137 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
138 static tree convert_template_argument (tree, tree, tree,
139                                        tsubst_flags_t, int, tree);
140 static int for_each_template_parm (tree, tree_fn_t, void*,
141                                    struct pointer_set_t*, bool);
142 static tree expand_template_argument_pack (tree);
143 static tree build_template_parm_index (int, int, int, int, tree, tree);
144 static bool inline_needs_template_parms (tree);
145 static void push_inline_template_parms_recursive (tree, int);
146 static tree retrieve_local_specialization (tree);
147 static void register_local_specialization (tree, tree);
148 static hashval_t hash_specialization (const void *p);
149 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
150 static int mark_template_parm (tree, void *);
151 static int template_parm_this_level_p (tree, void *);
152 static tree tsubst_friend_function (tree, tree);
153 static tree tsubst_friend_class (tree, tree);
154 static int can_complete_type_without_circularity (tree);
155 static tree get_bindings (tree, tree, tree, bool);
156 static int template_decl_level (tree);
157 static int check_cv_quals_for_unify (int, tree, tree);
158 static void template_parm_level_and_index (tree, int*, int*);
159 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
160 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
161 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
162 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
163 static void regenerate_decl_from_template (tree, tree);
164 static tree most_specialized_class (tree, tree, tsubst_flags_t);
165 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
166 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
167 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
168 static bool check_specialization_scope (void);
169 static tree process_partial_specialization (tree);
170 static void set_current_access_from_decl (tree);
171 static tree get_template_base (tree, tree, tree, tree);
172 static tree try_class_unification (tree, tree, tree, tree);
173 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
174                                            tree, tree);
175 static bool template_template_parm_bindings_ok_p (tree, tree);
176 static int template_args_equal (tree, tree);
177 static void tsubst_default_arguments (tree);
178 static tree for_each_template_parm_r (tree *, int *, void *);
179 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
180 static void copy_default_args_to_explicit_spec (tree);
181 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
182 static int eq_local_specializations (const void *, const void *);
183 static bool dependent_template_arg_p (tree);
184 static bool any_template_arguments_need_structural_equality_p (tree);
185 static bool dependent_type_p_r (tree);
186 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
187 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
188 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_decl (tree, tree, tsubst_flags_t);
190 static void perform_typedefs_access_check (tree tmpl, tree targs);
191 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
192                                                         location_t);
193 static tree listify (tree);
194 static tree listify_autos (tree, tree);
195 static tree template_parm_to_arg (tree t);
196 static tree current_template_args (void);
197 static tree fixup_template_type_parm_type (tree, int);
198 static tree fixup_template_parm_index (tree, tree, int);
199 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
200
201 /* Make the current scope suitable for access checking when we are
202    processing T.  T can be FUNCTION_DECL for instantiated function
203    template, or VAR_DECL for static member variable (need by
204    instantiate_decl).  */
205
206 static void
207 push_access_scope (tree t)
208 {
209   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
210               || TREE_CODE (t) == VAR_DECL);
211
212   if (DECL_FRIEND_CONTEXT (t))
213     push_nested_class (DECL_FRIEND_CONTEXT (t));
214   else if (DECL_CLASS_SCOPE_P (t))
215     push_nested_class (DECL_CONTEXT (t));
216   else
217     push_to_top_level ();
218
219   if (TREE_CODE (t) == FUNCTION_DECL)
220     {
221       saved_access_scope = tree_cons
222         (NULL_TREE, current_function_decl, saved_access_scope);
223       current_function_decl = t;
224     }
225 }
226
227 /* Restore the scope set up by push_access_scope.  T is the node we
228    are processing.  */
229
230 static void
231 pop_access_scope (tree t)
232 {
233   if (TREE_CODE (t) == FUNCTION_DECL)
234     {
235       current_function_decl = TREE_VALUE (saved_access_scope);
236       saved_access_scope = TREE_CHAIN (saved_access_scope);
237     }
238
239   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
240     pop_nested_class ();
241   else
242     pop_from_top_level ();
243 }
244
245 /* Do any processing required when DECL (a member template
246    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
247    to DECL, unless it is a specialization, in which case the DECL
248    itself is returned.  */
249
250 tree
251 finish_member_template_decl (tree decl)
252 {
253   if (decl == error_mark_node)
254     return error_mark_node;
255
256   gcc_assert (DECL_P (decl));
257
258   if (TREE_CODE (decl) == TYPE_DECL)
259     {
260       tree type;
261
262       type = TREE_TYPE (decl);
263       if (type == error_mark_node)
264         return error_mark_node;
265       if (MAYBE_CLASS_TYPE_P (type)
266           && CLASSTYPE_TEMPLATE_INFO (type)
267           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
268         {
269           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
270           check_member_template (tmpl);
271           return tmpl;
272         }
273       return NULL_TREE;
274     }
275   else if (TREE_CODE (decl) == FIELD_DECL)
276     error ("data member %qD cannot be a member template", decl);
277   else if (DECL_TEMPLATE_INFO (decl))
278     {
279       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
280         {
281           check_member_template (DECL_TI_TEMPLATE (decl));
282           return DECL_TI_TEMPLATE (decl);
283         }
284       else
285         return decl;
286     }
287   else
288     error ("invalid member template declaration %qD", decl);
289
290   return error_mark_node;
291 }
292
293 /* Create a template info node.  */
294
295 tree
296 build_template_info (tree template_decl, tree template_args)
297 {
298   tree result = make_node (TEMPLATE_INFO);
299   TI_TEMPLATE (result) = template_decl;
300   TI_ARGS (result) = template_args;
301   return result;
302 }
303
304 /* Return the template info node corresponding to T, whatever T is.  */
305
306 tree
307 get_template_info (const_tree t)
308 {
309   tree tinfo = NULL_TREE;
310
311   if (!t || t == error_mark_node)
312     return NULL;
313
314   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
315     tinfo = DECL_TEMPLATE_INFO (t);
316
317   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
318     t = TREE_TYPE (t);
319
320   if (TAGGED_TYPE_P (t))
321     tinfo = TYPE_TEMPLATE_INFO (t);
322   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
323     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
324
325   return tinfo;
326 }
327
328 /* Returns the template nesting level of the indicated class TYPE.
329
330    For example, in:
331      template <class T>
332      struct A
333      {
334        template <class U>
335        struct B {};
336      };
337
338    A<T>::B<U> has depth two, while A<T> has depth one.
339    Both A<T>::B<int> and A<int>::B<U> have depth one, if
340    they are instantiations, not specializations.
341
342    This function is guaranteed to return 0 if passed NULL_TREE so
343    that, for example, `template_class_depth (current_class_type)' is
344    always safe.  */
345
346 int
347 template_class_depth (tree type)
348 {
349   int depth;
350
351   for (depth = 0;
352        type && TREE_CODE (type) != NAMESPACE_DECL;
353        type = (TREE_CODE (type) == FUNCTION_DECL)
354          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
355     {
356       tree tinfo = get_template_info (type);
357
358       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
359           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
360         ++depth;
361     }
362
363   return depth;
364 }
365
366 /* Subroutine of maybe_begin_member_template_processing.
367    Returns true if processing DECL needs us to push template parms.  */
368
369 static bool
370 inline_needs_template_parms (tree decl)
371 {
372   if (! DECL_TEMPLATE_INFO (decl))
373     return false;
374
375   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
376           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
377 }
378
379 /* Subroutine of maybe_begin_member_template_processing.
380    Push the template parms in PARMS, starting from LEVELS steps into the
381    chain, and ending at the beginning, since template parms are listed
382    innermost first.  */
383
384 static void
385 push_inline_template_parms_recursive (tree parmlist, int levels)
386 {
387   tree parms = TREE_VALUE (parmlist);
388   int i;
389
390   if (levels > 1)
391     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
392
393   ++processing_template_decl;
394   current_template_parms
395     = tree_cons (size_int (processing_template_decl),
396                  parms, current_template_parms);
397   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
398
399   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
400                NULL);
401   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
402     {
403       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
404
405       if (parm == error_mark_node)
406         continue;
407
408       gcc_assert (DECL_P (parm));
409
410       switch (TREE_CODE (parm))
411         {
412         case TYPE_DECL:
413         case TEMPLATE_DECL:
414           pushdecl (parm);
415           break;
416
417         case PARM_DECL:
418           {
419             /* Make a CONST_DECL as is done in process_template_parm.
420                It is ugly that we recreate this here; the original
421                version built in process_template_parm is no longer
422                available.  */
423             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
424                                     CONST_DECL, DECL_NAME (parm),
425                                     TREE_TYPE (parm));
426             DECL_ARTIFICIAL (decl) = 1;
427             TREE_CONSTANT (decl) = 1;
428             TREE_READONLY (decl) = 1;
429             DECL_INITIAL (decl) = DECL_INITIAL (parm);
430             SET_DECL_TEMPLATE_PARM_P (decl);
431             pushdecl (decl);
432           }
433           break;
434
435         default:
436           gcc_unreachable ();
437         }
438     }
439 }
440
441 /* Restore the template parameter context for a member template or
442    a friend template defined in a class definition.  */
443
444 void
445 maybe_begin_member_template_processing (tree decl)
446 {
447   tree parms;
448   int levels = 0;
449
450   if (inline_needs_template_parms (decl))
451     {
452       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
453       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
454
455       if (DECL_TEMPLATE_SPECIALIZATION (decl))
456         {
457           --levels;
458           parms = TREE_CHAIN (parms);
459         }
460
461       push_inline_template_parms_recursive (parms, levels);
462     }
463
464   /* Remember how many levels of template parameters we pushed so that
465      we can pop them later.  */
466   VEC_safe_push (int, heap, inline_parm_levels, levels);
467 }
468
469 /* Undo the effects of maybe_begin_member_template_processing.  */
470
471 void
472 maybe_end_member_template_processing (void)
473 {
474   int i;
475   int last;
476
477   if (VEC_length (int, inline_parm_levels) == 0)
478     return;
479
480   last = VEC_pop (int, inline_parm_levels);
481   for (i = 0; i < last; ++i)
482     {
483       --processing_template_decl;
484       current_template_parms = TREE_CHAIN (current_template_parms);
485       poplevel (0, 0, 0);
486     }
487 }
488
489 /* Return a new template argument vector which contains all of ARGS,
490    but has as its innermost set of arguments the EXTRA_ARGS.  */
491
492 static tree
493 add_to_template_args (tree args, tree extra_args)
494 {
495   tree new_args;
496   int extra_depth;
497   int i;
498   int j;
499
500   if (args == NULL_TREE || extra_args == error_mark_node)
501     return extra_args;
502
503   extra_depth = TMPL_ARGS_DEPTH (extra_args);
504   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
505
506   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
507     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
508
509   for (j = 1; j <= extra_depth; ++j, ++i)
510     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
511
512   return new_args;
513 }
514
515 /* Like add_to_template_args, but only the outermost ARGS are added to
516    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
517    (EXTRA_ARGS) levels are added.  This function is used to combine
518    the template arguments from a partial instantiation with the
519    template arguments used to attain the full instantiation from the
520    partial instantiation.  */
521
522 static tree
523 add_outermost_template_args (tree args, tree extra_args)
524 {
525   tree new_args;
526
527   /* If there are more levels of EXTRA_ARGS than there are ARGS,
528      something very fishy is going on.  */
529   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
530
531   /* If *all* the new arguments will be the EXTRA_ARGS, just return
532      them.  */
533   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
534     return extra_args;
535
536   /* For the moment, we make ARGS look like it contains fewer levels.  */
537   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
538
539   new_args = add_to_template_args (args, extra_args);
540
541   /* Now, we restore ARGS to its full dimensions.  */
542   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
543
544   return new_args;
545 }
546
547 /* Return the N levels of innermost template arguments from the ARGS.  */
548
549 tree
550 get_innermost_template_args (tree args, int n)
551 {
552   tree new_args;
553   int extra_levels;
554   int i;
555
556   gcc_assert (n >= 0);
557
558   /* If N is 1, just return the innermost set of template arguments.  */
559   if (n == 1)
560     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
561
562   /* If we're not removing anything, just return the arguments we were
563      given.  */
564   extra_levels = TMPL_ARGS_DEPTH (args) - n;
565   gcc_assert (extra_levels >= 0);
566   if (extra_levels == 0)
567     return args;
568
569   /* Make a new set of arguments, not containing the outer arguments.  */
570   new_args = make_tree_vec (n);
571   for (i = 1; i <= n; ++i)
572     SET_TMPL_ARGS_LEVEL (new_args, i,
573                          TMPL_ARGS_LEVEL (args, i + extra_levels));
574
575   return new_args;
576 }
577
578 /* The inverse of get_innermost_template_args: Return all but the innermost
579    EXTRA_LEVELS levels of template arguments from the ARGS.  */
580
581 static tree
582 strip_innermost_template_args (tree args, int extra_levels)
583 {
584   tree new_args;
585   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
586   int i;
587
588   gcc_assert (n >= 0);
589
590   /* If N is 1, just return the outermost set of template arguments.  */
591   if (n == 1)
592     return TMPL_ARGS_LEVEL (args, 1);
593
594   /* If we're not removing anything, just return the arguments we were
595      given.  */
596   gcc_assert (extra_levels >= 0);
597   if (extra_levels == 0)
598     return args;
599
600   /* Make a new set of arguments, not containing the inner arguments.  */
601   new_args = make_tree_vec (n);
602   for (i = 1; i <= n; ++i)
603     SET_TMPL_ARGS_LEVEL (new_args, i,
604                          TMPL_ARGS_LEVEL (args, i));
605
606   return new_args;
607 }
608
609 /* We've got a template header coming up; push to a new level for storing
610    the parms.  */
611
612 void
613 begin_template_parm_list (void)
614 {
615   /* We use a non-tag-transparent scope here, which causes pushtag to
616      put tags in this scope, rather than in the enclosing class or
617      namespace scope.  This is the right thing, since we want
618      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
619      global template class, push_template_decl handles putting the
620      TEMPLATE_DECL into top-level scope.  For a nested template class,
621      e.g.:
622
623        template <class T> struct S1 {
624          template <class T> struct S2 {};
625        };
626
627      pushtag contains special code to call pushdecl_with_scope on the
628      TEMPLATE_DECL for S2.  */
629   begin_scope (sk_template_parms, NULL);
630   ++processing_template_decl;
631   ++processing_template_parmlist;
632   note_template_header (0);
633 }
634
635 /* This routine is called when a specialization is declared.  If it is
636    invalid to declare a specialization here, an error is reported and
637    false is returned, otherwise this routine will return true.  */
638
639 static bool
640 check_specialization_scope (void)
641 {
642   tree scope = current_scope ();
643
644   /* [temp.expl.spec]
645
646      An explicit specialization shall be declared in the namespace of
647      which the template is a member, or, for member templates, in the
648      namespace of which the enclosing class or enclosing class
649      template is a member.  An explicit specialization of a member
650      function, member class or static data member of a class template
651      shall be declared in the namespace of which the class template
652      is a member.  */
653   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
654     {
655       error ("explicit specialization in non-namespace scope %qD", scope);
656       return false;
657     }
658
659   /* [temp.expl.spec]
660
661      In an explicit specialization declaration for a member of a class
662      template or a member template that appears in namespace scope,
663      the member template and some of its enclosing class templates may
664      remain unspecialized, except that the declaration shall not
665      explicitly specialize a class member template if its enclosing
666      class templates are not explicitly specialized as well.  */
667   if (current_template_parms)
668     {
669       error ("enclosing class templates are not explicitly specialized");
670       return false;
671     }
672
673   return true;
674 }
675
676 /* We've just seen template <>.  */
677
678 bool
679 begin_specialization (void)
680 {
681   begin_scope (sk_template_spec, NULL);
682   note_template_header (1);
683   return check_specialization_scope ();
684 }
685
686 /* Called at then end of processing a declaration preceded by
687    template<>.  */
688
689 void
690 end_specialization (void)
691 {
692   finish_scope ();
693   reset_specialization ();
694 }
695
696 /* Any template <>'s that we have seen thus far are not referring to a
697    function specialization.  */
698
699 void
700 reset_specialization (void)
701 {
702   processing_specialization = 0;
703   template_header_count = 0;
704 }
705
706 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
707    it was of the form template <>.  */
708
709 static void
710 note_template_header (int specialization)
711 {
712   processing_specialization = specialization;
713   template_header_count++;
714 }
715
716 /* We're beginning an explicit instantiation.  */
717
718 void
719 begin_explicit_instantiation (void)
720 {
721   gcc_assert (!processing_explicit_instantiation);
722   processing_explicit_instantiation = true;
723 }
724
725
726 void
727 end_explicit_instantiation (void)
728 {
729   gcc_assert (processing_explicit_instantiation);
730   processing_explicit_instantiation = false;
731 }
732
733 /* An explicit specialization or partial specialization TMPL is being
734    declared.  Check that the namespace in which the specialization is
735    occurring is permissible.  Returns false iff it is invalid to
736    specialize TMPL in the current namespace.  */
737
738 static bool
739 check_specialization_namespace (tree tmpl)
740 {
741   tree tpl_ns = decl_namespace_context (tmpl);
742
743   /* [tmpl.expl.spec]
744
745      An explicit specialization shall be declared in the namespace of
746      which the template is a member, or, for member templates, in the
747      namespace of which the enclosing class or enclosing class
748      template is a member.  An explicit specialization of a member
749      function, member class or static data member of a class template
750      shall be declared in the namespace of which the class template is
751      a member.  */
752   if (current_scope() != DECL_CONTEXT (tmpl)
753       && !at_namespace_scope_p ())
754     {
755       error ("specialization of %qD must appear at namespace scope", tmpl);
756       return false;
757     }
758   if (is_associated_namespace (current_namespace, tpl_ns))
759     /* Same or super-using namespace.  */
760     return true;
761   else
762     {
763       permerror (input_location, "specialization of %qD in different namespace", tmpl);
764       permerror (input_location, "  from definition of %q+#D", tmpl);
765       return false;
766     }
767 }
768
769 /* SPEC is an explicit instantiation.  Check that it is valid to
770    perform this explicit instantiation in the current namespace.  */
771
772 static void
773 check_explicit_instantiation_namespace (tree spec)
774 {
775   tree ns;
776
777   /* DR 275: An explicit instantiation shall appear in an enclosing
778      namespace of its template.  */
779   ns = decl_namespace_context (spec);
780   if (!is_ancestor (current_namespace, ns))
781     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
782                "(which does not enclose namespace %qD)",
783                spec, current_namespace, ns);
784 }
785
786 /* The TYPE is being declared.  If it is a template type, that means it
787    is a partial specialization.  Do appropriate error-checking.  */
788
789 tree
790 maybe_process_partial_specialization (tree type)
791 {
792   tree context;
793
794   if (type == error_mark_node)
795     return error_mark_node;
796
797   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
798     {
799       error ("name of class shadows template template parameter %qD",
800              TYPE_NAME (type));
801       return error_mark_node;
802     }
803
804   context = TYPE_CONTEXT (type);
805
806   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
807     {
808       /* This is for ordinary explicit specialization and partial
809          specialization of a template class such as:
810
811            template <> class C<int>;
812
813          or:
814
815            template <class T> class C<T*>;
816
817          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
818
819       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
820           && !COMPLETE_TYPE_P (type))
821         {
822           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
823           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
824           if (processing_template_decl)
825             {
826               if (push_template_decl (TYPE_MAIN_DECL (type))
827                   == error_mark_node)
828                 return error_mark_node;
829             }
830         }
831       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
832         error ("specialization of %qT after instantiation", type);
833     }
834   else if (CLASS_TYPE_P (type)
835            && !CLASSTYPE_USE_TEMPLATE (type)
836            && CLASSTYPE_TEMPLATE_INFO (type)
837            && context && CLASS_TYPE_P (context)
838            && CLASSTYPE_TEMPLATE_INFO (context))
839     {
840       /* This is for an explicit specialization of member class
841          template according to [temp.expl.spec/18]:
842
843            template <> template <class U> class C<int>::D;
844
845          The context `C<int>' must be an implicit instantiation.
846          Otherwise this is just a member class template declared
847          earlier like:
848
849            template <> class C<int> { template <class U> class D; };
850            template <> template <class U> class C<int>::D;
851
852          In the first case, `C<int>::D' is a specialization of `C<T>::D'
853          while in the second case, `C<int>::D' is a primary template
854          and `C<T>::D' may not exist.  */
855
856       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
857           && !COMPLETE_TYPE_P (type))
858         {
859           tree t;
860           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
861
862           if (current_namespace
863               != decl_namespace_context (tmpl))
864             {
865               permerror (input_location, "specializing %q#T in different namespace", type);
866               permerror (input_location, "  from definition of %q+#D", tmpl);
867             }
868
869           /* Check for invalid specialization after instantiation:
870
871                template <> template <> class C<int>::D<int>;
872                template <> template <class U> class C<int>::D;  */
873
874           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
875                t; t = TREE_CHAIN (t))
876             {
877               tree inst = TREE_VALUE (t);
878               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
879                 {
880                   /* We already have a full specialization of this partial
881                      instantiation.  Reassign it to the new member
882                      specialization template.  */
883                   spec_entry elt;
884                   spec_entry **slot;
885
886                   elt.tmpl = most_general_template (tmpl);
887                   elt.args = CLASSTYPE_TI_ARGS (inst);
888                   elt.spec = inst;
889
890                   htab_remove_elt (type_specializations, &elt);
891
892                   elt.tmpl = tmpl;
893                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
894
895                   slot = (spec_entry **)
896                     htab_find_slot (type_specializations, &elt, INSERT);
897                   *slot = ggc_alloc_spec_entry ();
898                   **slot = elt;
899                 }
900               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
901                 /* But if we've had an implicit instantiation, that's a
902                    problem ([temp.expl.spec]/6).  */
903                 error ("specialization %qT after instantiation %qT",
904                        type, inst);
905             }
906
907           /* Mark TYPE as a specialization.  And as a result, we only
908              have one level of template argument for the innermost
909              class template.  */
910           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
911           CLASSTYPE_TI_ARGS (type)
912             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
913         }
914     }
915   else if (processing_specialization)
916     {
917        /* Someday C++0x may allow for enum template specialization.  */
918       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
919           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
920         pedwarn (input_location, OPT_pedantic, "template specialization "
921                  "of %qD not allowed by ISO C++", type);
922       else
923         {
924           error ("explicit specialization of non-template %qT", type);
925           return error_mark_node;
926         }
927     }
928
929   return type;
930 }
931
932 /* Returns nonzero if we can optimize the retrieval of specializations
933    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
934    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
935
936 static inline bool
937 optimize_specialization_lookup_p (tree tmpl)
938 {
939   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
940           && DECL_CLASS_SCOPE_P (tmpl)
941           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
942              parameter.  */
943           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
944           /* The optimized lookup depends on the fact that the
945              template arguments for the member function template apply
946              purely to the containing class, which is not true if the
947              containing class is an explicit or partial
948              specialization.  */
949           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
950           && !DECL_MEMBER_TEMPLATE_P (tmpl)
951           && !DECL_CONV_FN_P (tmpl)
952           /* It is possible to have a template that is not a member
953              template and is not a member of a template class:
954
955              template <typename T>
956              struct S { friend A::f(); };
957
958              Here, the friend function is a template, but the context does
959              not have template information.  The optimized lookup relies
960              on having ARGS be the template arguments for both the class
961              and the function template.  */
962           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
963 }
964
965 /* Retrieve the specialization (in the sense of [temp.spec] - a
966    specialization is either an instantiation or an explicit
967    specialization) of TMPL for the given template ARGS.  If there is
968    no such specialization, return NULL_TREE.  The ARGS are a vector of
969    arguments, or a vector of vectors of arguments, in the case of
970    templates with more than one level of parameters.
971
972    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
973    then we search for a partial specialization matching ARGS.  This
974    parameter is ignored if TMPL is not a class template.  */
975
976 static tree
977 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
978 {
979   if (args == error_mark_node)
980     return NULL_TREE;
981
982   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
983
984   /* There should be as many levels of arguments as there are
985      levels of parameters.  */
986   gcc_assert (TMPL_ARGS_DEPTH (args)
987               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
988
989   if (optimize_specialization_lookup_p (tmpl))
990     {
991       tree class_template;
992       tree class_specialization;
993       VEC(tree,gc) *methods;
994       tree fns;
995       int idx;
996
997       /* The template arguments actually apply to the containing
998          class.  Find the class specialization with those
999          arguments.  */
1000       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1001       class_specialization
1002         = retrieve_specialization (class_template, args, 0);
1003       if (!class_specialization)
1004         return NULL_TREE;
1005       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1006          for the specialization.  */
1007       idx = class_method_index_for_fn (class_specialization, tmpl);
1008       if (idx == -1)
1009         return NULL_TREE;
1010       /* Iterate through the methods with the indicated name, looking
1011          for the one that has an instance of TMPL.  */
1012       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1013       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1014         {
1015           tree fn = OVL_CURRENT (fns);
1016           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1017               /* using-declarations can add base methods to the method vec,
1018                  and we don't want those here.  */
1019               && DECL_CONTEXT (fn) == class_specialization)
1020             return fn;
1021         }
1022       return NULL_TREE;
1023     }
1024   else
1025     {
1026       spec_entry *found;
1027       spec_entry elt;
1028       htab_t specializations;
1029
1030       elt.tmpl = tmpl;
1031       elt.args = args;
1032       elt.spec = NULL_TREE;
1033
1034       if (DECL_CLASS_TEMPLATE_P (tmpl))
1035         specializations = type_specializations;
1036       else
1037         specializations = decl_specializations;
1038
1039       if (hash == 0)
1040         hash = hash_specialization (&elt);
1041       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1042       if (found)
1043         return found->spec;
1044     }
1045
1046   return NULL_TREE;
1047 }
1048
1049 /* Like retrieve_specialization, but for local declarations.  */
1050
1051 static tree
1052 retrieve_local_specialization (tree tmpl)
1053 {
1054   tree spec;
1055
1056   if (local_specializations == NULL)
1057     return NULL_TREE;
1058
1059   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1060                                      htab_hash_pointer (tmpl));
1061   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1062 }
1063
1064 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1065
1066 int
1067 is_specialization_of (tree decl, tree tmpl)
1068 {
1069   tree t;
1070
1071   if (TREE_CODE (decl) == FUNCTION_DECL)
1072     {
1073       for (t = decl;
1074            t != NULL_TREE;
1075            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1076         if (t == tmpl)
1077           return 1;
1078     }
1079   else
1080     {
1081       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1082
1083       for (t = TREE_TYPE (decl);
1084            t != NULL_TREE;
1085            t = CLASSTYPE_USE_TEMPLATE (t)
1086              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1087         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1088           return 1;
1089     }
1090
1091   return 0;
1092 }
1093
1094 /* Returns nonzero iff DECL is a specialization of friend declaration
1095    FRIEND_DECL according to [temp.friend].  */
1096
1097 bool
1098 is_specialization_of_friend (tree decl, tree friend_decl)
1099 {
1100   bool need_template = true;
1101   int template_depth;
1102
1103   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1104               || TREE_CODE (decl) == TYPE_DECL);
1105
1106   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1107      of a template class, we want to check if DECL is a specialization
1108      if this.  */
1109   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1110       && DECL_TEMPLATE_INFO (friend_decl)
1111       && !DECL_USE_TEMPLATE (friend_decl))
1112     {
1113       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1114       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1115       need_template = false;
1116     }
1117   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1118            && !PRIMARY_TEMPLATE_P (friend_decl))
1119     need_template = false;
1120
1121   /* There is nothing to do if this is not a template friend.  */
1122   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1123     return false;
1124
1125   if (is_specialization_of (decl, friend_decl))
1126     return true;
1127
1128   /* [temp.friend/6]
1129      A member of a class template may be declared to be a friend of a
1130      non-template class.  In this case, the corresponding member of
1131      every specialization of the class template is a friend of the
1132      class granting friendship.
1133
1134      For example, given a template friend declaration
1135
1136        template <class T> friend void A<T>::f();
1137
1138      the member function below is considered a friend
1139
1140        template <> struct A<int> {
1141          void f();
1142        };
1143
1144      For this type of template friend, TEMPLATE_DEPTH below will be
1145      nonzero.  To determine if DECL is a friend of FRIEND, we first
1146      check if the enclosing class is a specialization of another.  */
1147
1148   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1149   if (template_depth
1150       && DECL_CLASS_SCOPE_P (decl)
1151       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1152                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1153     {
1154       /* Next, we check the members themselves.  In order to handle
1155          a few tricky cases, such as when FRIEND_DECL's are
1156
1157            template <class T> friend void A<T>::g(T t);
1158            template <class T> template <T t> friend void A<T>::h();
1159
1160          and DECL's are
1161
1162            void A<int>::g(int);
1163            template <int> void A<int>::h();
1164
1165          we need to figure out ARGS, the template arguments from
1166          the context of DECL.  This is required for template substitution
1167          of `T' in the function parameter of `g' and template parameter
1168          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1169
1170       tree context = DECL_CONTEXT (decl);
1171       tree args = NULL_TREE;
1172       int current_depth = 0;
1173
1174       while (current_depth < template_depth)
1175         {
1176           if (CLASSTYPE_TEMPLATE_INFO (context))
1177             {
1178               if (current_depth == 0)
1179                 args = TYPE_TI_ARGS (context);
1180               else
1181                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1182               current_depth++;
1183             }
1184           context = TYPE_CONTEXT (context);
1185         }
1186
1187       if (TREE_CODE (decl) == FUNCTION_DECL)
1188         {
1189           bool is_template;
1190           tree friend_type;
1191           tree decl_type;
1192           tree friend_args_type;
1193           tree decl_args_type;
1194
1195           /* Make sure that both DECL and FRIEND_DECL are templates or
1196              non-templates.  */
1197           is_template = DECL_TEMPLATE_INFO (decl)
1198                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1199           if (need_template ^ is_template)
1200             return false;
1201           else if (is_template)
1202             {
1203               /* If both are templates, check template parameter list.  */
1204               tree friend_parms
1205                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1206                                          args, tf_none);
1207               if (!comp_template_parms
1208                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1209                       friend_parms))
1210                 return false;
1211
1212               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1213             }
1214           else
1215             decl_type = TREE_TYPE (decl);
1216
1217           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1218                                               tf_none, NULL_TREE);
1219           if (friend_type == error_mark_node)
1220             return false;
1221
1222           /* Check if return types match.  */
1223           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1224             return false;
1225
1226           /* Check if function parameter types match, ignoring the
1227              `this' parameter.  */
1228           friend_args_type = TYPE_ARG_TYPES (friend_type);
1229           decl_args_type = TYPE_ARG_TYPES (decl_type);
1230           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1231             friend_args_type = TREE_CHAIN (friend_args_type);
1232           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1233             decl_args_type = TREE_CHAIN (decl_args_type);
1234
1235           return compparms (decl_args_type, friend_args_type);
1236         }
1237       else
1238         {
1239           /* DECL is a TYPE_DECL */
1240           bool is_template;
1241           tree decl_type = TREE_TYPE (decl);
1242
1243           /* Make sure that both DECL and FRIEND_DECL are templates or
1244              non-templates.  */
1245           is_template
1246             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1247               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1248
1249           if (need_template ^ is_template)
1250             return false;
1251           else if (is_template)
1252             {
1253               tree friend_parms;
1254               /* If both are templates, check the name of the two
1255                  TEMPLATE_DECL's first because is_friend didn't.  */
1256               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1257                   != DECL_NAME (friend_decl))
1258                 return false;
1259
1260               /* Now check template parameter list.  */
1261               friend_parms
1262                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1263                                          args, tf_none);
1264               return comp_template_parms
1265                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1266                  friend_parms);
1267             }
1268           else
1269             return (DECL_NAME (decl)
1270                     == DECL_NAME (friend_decl));
1271         }
1272     }
1273   return false;
1274 }
1275
1276 /* Register the specialization SPEC as a specialization of TMPL with
1277    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1278    is actually just a friend declaration.  Returns SPEC, or an
1279    equivalent prior declaration, if available.  */
1280
1281 static tree
1282 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1283                          hashval_t hash)
1284 {
1285   tree fn;
1286   spec_entry **slot = NULL;
1287   spec_entry elt;
1288
1289   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1290
1291   if (TREE_CODE (spec) == FUNCTION_DECL
1292       && uses_template_parms (DECL_TI_ARGS (spec)))
1293     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1294        register it; we want the corresponding TEMPLATE_DECL instead.
1295        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1296        the more obvious `uses_template_parms (spec)' to avoid problems
1297        with default function arguments.  In particular, given
1298        something like this:
1299
1300           template <class T> void f(T t1, T t = T())
1301
1302        the default argument expression is not substituted for in an
1303        instantiation unless and until it is actually needed.  */
1304     return spec;
1305
1306   if (optimize_specialization_lookup_p (tmpl))
1307     /* We don't put these specializations in the hash table, but we might
1308        want to give an error about a mismatch.  */
1309     fn = retrieve_specialization (tmpl, args, 0);
1310   else
1311     {
1312       elt.tmpl = tmpl;
1313       elt.args = args;
1314       elt.spec = spec;
1315
1316       if (hash == 0)
1317         hash = hash_specialization (&elt);
1318
1319       slot = (spec_entry **)
1320         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1321       if (*slot)
1322         fn = (*slot)->spec;
1323       else
1324         fn = NULL_TREE;
1325     }
1326
1327   /* We can sometimes try to re-register a specialization that we've
1328      already got.  In particular, regenerate_decl_from_template calls
1329      duplicate_decls which will update the specialization list.  But,
1330      we'll still get called again here anyhow.  It's more convenient
1331      to simply allow this than to try to prevent it.  */
1332   if (fn == spec)
1333     return spec;
1334   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1335     {
1336       if (DECL_TEMPLATE_INSTANTIATION (fn))
1337         {
1338           if (DECL_ODR_USED (fn)
1339               || DECL_EXPLICIT_INSTANTIATION (fn))
1340             {
1341               error ("specialization of %qD after instantiation",
1342                      fn);
1343               return error_mark_node;
1344             }
1345           else
1346             {
1347               tree clone;
1348               /* This situation should occur only if the first
1349                  specialization is an implicit instantiation, the
1350                  second is an explicit specialization, and the
1351                  implicit instantiation has not yet been used.  That
1352                  situation can occur if we have implicitly
1353                  instantiated a member function and then specialized
1354                  it later.
1355
1356                  We can also wind up here if a friend declaration that
1357                  looked like an instantiation turns out to be a
1358                  specialization:
1359
1360                    template <class T> void foo(T);
1361                    class S { friend void foo<>(int) };
1362                    template <> void foo(int);
1363
1364                  We transform the existing DECL in place so that any
1365                  pointers to it become pointers to the updated
1366                  declaration.
1367
1368                  If there was a definition for the template, but not
1369                  for the specialization, we want this to look as if
1370                  there were no definition, and vice versa.  */
1371               DECL_INITIAL (fn) = NULL_TREE;
1372               duplicate_decls (spec, fn, is_friend);
1373               /* The call to duplicate_decls will have applied
1374                  [temp.expl.spec]:
1375
1376                    An explicit specialization of a function template
1377                    is inline only if it is explicitly declared to be,
1378                    and independently of whether its function template
1379                    is.
1380
1381                 to the primary function; now copy the inline bits to
1382                 the various clones.  */
1383               FOR_EACH_CLONE (clone, fn)
1384                 {
1385                   DECL_DECLARED_INLINE_P (clone)
1386                     = DECL_DECLARED_INLINE_P (fn);
1387                   DECL_SOURCE_LOCATION (clone)
1388                     = DECL_SOURCE_LOCATION (fn);
1389                 }
1390               check_specialization_namespace (fn);
1391
1392               return fn;
1393             }
1394         }
1395       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1396         {
1397           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1398             /* Dup decl failed, but this is a new definition. Set the
1399                line number so any errors match this new
1400                definition.  */
1401             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1402
1403           return fn;
1404         }
1405     }
1406   else if (fn)
1407     return duplicate_decls (spec, fn, is_friend);
1408
1409   /* A specialization must be declared in the same namespace as the
1410      template it is specializing.  */
1411   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1412       && !check_specialization_namespace (tmpl))
1413     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1414
1415   if (!optimize_specialization_lookup_p (tmpl))
1416     {
1417       gcc_assert (tmpl && args && spec);
1418       *slot = ggc_alloc_spec_entry ();
1419       **slot = elt;
1420       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1421           && PRIMARY_TEMPLATE_P (tmpl)
1422           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1423         /* TMPL is a forward declaration of a template function; keep a list
1424            of all specializations in case we need to reassign them to a friend
1425            template later in tsubst_friend_function.  */
1426         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1427           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1428     }
1429
1430   return spec;
1431 }
1432
1433 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1434    TMPL and ARGS members, ignores SPEC.  */
1435
1436 static int
1437 eq_specializations (const void *p1, const void *p2)
1438 {
1439   const spec_entry *e1 = (const spec_entry *)p1;
1440   const spec_entry *e2 = (const spec_entry *)p2;
1441
1442   return (e1->tmpl == e2->tmpl
1443           && comp_template_args (e1->args, e2->args));
1444 }
1445
1446 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1447
1448 static hashval_t
1449 hash_tmpl_and_args (tree tmpl, tree args)
1450 {
1451   hashval_t val = DECL_UID (tmpl);
1452   return iterative_hash_template_arg (args, val);
1453 }
1454
1455 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1456    ignoring SPEC.  */
1457
1458 static hashval_t
1459 hash_specialization (const void *p)
1460 {
1461   const spec_entry *e = (const spec_entry *)p;
1462   return hash_tmpl_and_args (e->tmpl, e->args);
1463 }
1464
1465 /* Recursively calculate a hash value for a template argument ARG, for use
1466    in the hash tables of template specializations.  */
1467
1468 hashval_t
1469 iterative_hash_template_arg (tree arg, hashval_t val)
1470 {
1471   unsigned HOST_WIDE_INT i;
1472   enum tree_code code;
1473   char tclass;
1474
1475   if (arg == NULL_TREE)
1476     return iterative_hash_object (arg, val);
1477
1478   if (!TYPE_P (arg))
1479     STRIP_NOPS (arg);
1480
1481   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1482     /* We can get one of these when re-hashing a previous entry in the middle
1483        of substituting into a pack expansion.  Just look through it.  */
1484     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1485
1486   code = TREE_CODE (arg);
1487   tclass = TREE_CODE_CLASS (code);
1488
1489   val = iterative_hash_object (code, val);
1490
1491   switch (code)
1492     {
1493     case ERROR_MARK:
1494       return val;
1495
1496     case IDENTIFIER_NODE:
1497       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1498
1499     case TREE_VEC:
1500       {
1501         int i, len = TREE_VEC_LENGTH (arg);
1502         for (i = 0; i < len; ++i)
1503           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1504         return val;
1505       }
1506
1507     case TYPE_PACK_EXPANSION:
1508     case EXPR_PACK_EXPANSION:
1509       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1510
1511     case TYPE_ARGUMENT_PACK:
1512     case NONTYPE_ARGUMENT_PACK:
1513       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1514
1515     case TREE_LIST:
1516       for (; arg; arg = TREE_CHAIN (arg))
1517         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1518       return val;
1519
1520     case OVERLOAD:
1521       for (; arg; arg = OVL_NEXT (arg))
1522         val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1523       return val;
1524
1525     case CONSTRUCTOR:
1526       {
1527         tree field, value;
1528         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1529           {
1530             val = iterative_hash_template_arg (field, val);
1531             val = iterative_hash_template_arg (value, val);
1532           }
1533         return val;
1534       }
1535
1536     case PARM_DECL:
1537       if (!DECL_ARTIFICIAL (arg))
1538         {
1539           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1540           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1541         }
1542       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1543
1544     case TARGET_EXPR:
1545       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1546
1547     case PTRMEM_CST:
1548       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1549       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1550
1551     case TEMPLATE_PARM_INDEX:
1552       val = iterative_hash_template_arg
1553         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1554       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1555       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1556
1557     case TRAIT_EXPR:
1558       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1559       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1560       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1561
1562     case BASELINK:
1563       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1564                                          val);
1565       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1566                                           val);
1567
1568     case MODOP_EXPR:
1569       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1570       code = TREE_CODE (TREE_OPERAND (arg, 1));
1571       val = iterative_hash_object (code, val);
1572       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1573
1574     case LAMBDA_EXPR:
1575       /* A lambda can't appear in a template arg, but don't crash on
1576          erroneous input.  */
1577       gcc_assert (seen_error ());
1578       return val;
1579
1580     case CAST_EXPR:
1581     case STATIC_CAST_EXPR:
1582     case REINTERPRET_CAST_EXPR:
1583     case CONST_CAST_EXPR:
1584     case DYNAMIC_CAST_EXPR:
1585     case NEW_EXPR:
1586       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1587       /* Now hash operands as usual.  */
1588       break;
1589
1590     default:
1591       break;
1592     }
1593
1594   switch (tclass)
1595     {
1596     case tcc_type:
1597       if (TYPE_CANONICAL (arg))
1598         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1599                                       val);
1600       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1601         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1602       /* Otherwise just compare the types during lookup.  */
1603       return val;
1604
1605     case tcc_declaration:
1606     case tcc_constant:
1607       return iterative_hash_expr (arg, val);
1608
1609     default:
1610       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1611       {
1612         unsigned n = cp_tree_operand_length (arg);
1613         for (i = 0; i < n; ++i)
1614           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1615         return val;
1616       }
1617     }
1618   gcc_unreachable ();
1619   return 0;
1620 }
1621
1622 /* Unregister the specialization SPEC as a specialization of TMPL.
1623    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1624    if the SPEC was listed as a specialization of TMPL.
1625
1626    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1627
1628 bool
1629 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1630 {
1631   spec_entry **slot;
1632   spec_entry elt;
1633
1634   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1635   elt.args = TI_ARGS (tinfo);
1636   elt.spec = NULL_TREE;
1637
1638   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1639   if (*slot)
1640     {
1641       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1642       gcc_assert (new_spec != NULL_TREE);
1643       (*slot)->spec = new_spec;
1644       return 1;
1645     }
1646
1647   return 0;
1648 }
1649
1650 /* Compare an entry in the local specializations hash table P1 (which
1651    is really a pointer to a TREE_LIST) with P2 (which is really a
1652    DECL).  */
1653
1654 static int
1655 eq_local_specializations (const void *p1, const void *p2)
1656 {
1657   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1658 }
1659
1660 /* Hash P1, an entry in the local specializations table.  */
1661
1662 static hashval_t
1663 hash_local_specialization (const void* p1)
1664 {
1665   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1666 }
1667
1668 /* Like register_specialization, but for local declarations.  We are
1669    registering SPEC, an instantiation of TMPL.  */
1670
1671 static void
1672 register_local_specialization (tree spec, tree tmpl)
1673 {
1674   void **slot;
1675
1676   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1677                                    htab_hash_pointer (tmpl), INSERT);
1678   *slot = build_tree_list (spec, tmpl);
1679 }
1680
1681 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1682    specialized class.  */
1683
1684 bool
1685 explicit_class_specialization_p (tree type)
1686 {
1687   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1688     return false;
1689   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1690 }
1691
1692 /* Print the list of functions at FNS, going through all the overloads
1693    for each element of the list.  Alternatively, FNS can not be a
1694    TREE_LIST, in which case it will be printed together with all the
1695    overloads.
1696
1697    MORE and *STR should respectively be FALSE and NULL when the function
1698    is called from the outside.  They are used internally on recursive
1699    calls.  print_candidates manages the two parameters and leaves NULL
1700    in *STR when it ends.  */
1701
1702 static void
1703 print_candidates_1 (tree fns, bool more, const char **str)
1704 {
1705   tree fn, fn2;
1706   char *spaces = NULL;
1707
1708   for (fn = fns; fn; fn = OVL_NEXT (fn))
1709     if (TREE_CODE (fn) == TREE_LIST)
1710       {
1711         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1712           print_candidates_1 (TREE_VALUE (fn2),
1713                               TREE_CHAIN (fn2) || more, str);
1714       }
1715     else
1716       {
1717         if (!*str)
1718           {
1719             /* Pick the prefix string.  */
1720             if (!more && !OVL_NEXT (fns))
1721               {
1722                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1723                 continue;
1724               }
1725
1726             *str = _("candidates are:");
1727             spaces = get_spaces (*str);
1728           }
1729         error ("%s %+#D", *str, OVL_CURRENT (fn));
1730         *str = spaces ? spaces : *str;
1731       }
1732
1733   if (!more)
1734     {
1735       free (spaces);
1736       *str = NULL;
1737     }
1738 }
1739
1740 /* Print the list of candidate FNS in an error message.  FNS can also
1741    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1742
1743 void
1744 print_candidates (tree fns)
1745 {
1746   const char *str = NULL;
1747   print_candidates_1 (fns, false, &str);
1748   gcc_assert (str == NULL);
1749 }
1750
1751 /* Returns the template (one of the functions given by TEMPLATE_ID)
1752    which can be specialized to match the indicated DECL with the
1753    explicit template args given in TEMPLATE_ID.  The DECL may be
1754    NULL_TREE if none is available.  In that case, the functions in
1755    TEMPLATE_ID are non-members.
1756
1757    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1758    specialization of a member template.
1759
1760    The TEMPLATE_COUNT is the number of references to qualifying
1761    template classes that appeared in the name of the function. See
1762    check_explicit_specialization for a more accurate description.
1763
1764    TSK indicates what kind of template declaration (if any) is being
1765    declared.  TSK_TEMPLATE indicates that the declaration given by
1766    DECL, though a FUNCTION_DECL, has template parameters, and is
1767    therefore a template function.
1768
1769    The template args (those explicitly specified and those deduced)
1770    are output in a newly created vector *TARGS_OUT.
1771
1772    If it is impossible to determine the result, an error message is
1773    issued.  The error_mark_node is returned to indicate failure.  */
1774
1775 static tree
1776 determine_specialization (tree template_id,
1777                           tree decl,
1778                           tree* targs_out,
1779                           int need_member_template,
1780                           int template_count,
1781                           tmpl_spec_kind tsk)
1782 {
1783   tree fns;
1784   tree targs;
1785   tree explicit_targs;
1786   tree candidates = NULL_TREE;
1787   /* A TREE_LIST of templates of which DECL may be a specialization.
1788      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1789      corresponding TREE_PURPOSE is the set of template arguments that,
1790      when used to instantiate the template, would produce a function
1791      with the signature of DECL.  */
1792   tree templates = NULL_TREE;
1793   int header_count;
1794   struct cp_binding_level *b;
1795
1796   *targs_out = NULL_TREE;
1797
1798   if (template_id == error_mark_node || decl == error_mark_node)
1799     return error_mark_node;
1800
1801   fns = TREE_OPERAND (template_id, 0);
1802   explicit_targs = TREE_OPERAND (template_id, 1);
1803
1804   if (fns == error_mark_node)
1805     return error_mark_node;
1806
1807   /* Check for baselinks.  */
1808   if (BASELINK_P (fns))
1809     fns = BASELINK_FUNCTIONS (fns);
1810
1811   if (!is_overloaded_fn (fns))
1812     {
1813       error ("%qD is not a function template", fns);
1814       return error_mark_node;
1815     }
1816
1817   /* Count the number of template headers specified for this
1818      specialization.  */
1819   header_count = 0;
1820   for (b = current_binding_level;
1821        b->kind == sk_template_parms;
1822        b = b->level_chain)
1823     ++header_count;
1824
1825   for (; fns; fns = OVL_NEXT (fns))
1826     {
1827       tree fn = OVL_CURRENT (fns);
1828
1829       if (TREE_CODE (fn) == TEMPLATE_DECL)
1830         {
1831           tree decl_arg_types;
1832           tree fn_arg_types;
1833
1834           /* In case of explicit specialization, we need to check if
1835              the number of template headers appearing in the specialization
1836              is correct. This is usually done in check_explicit_specialization,
1837              but the check done there cannot be exhaustive when specializing
1838              member functions. Consider the following code:
1839
1840              template <> void A<int>::f(int);
1841              template <> template <> void A<int>::f(int);
1842
1843              Assuming that A<int> is not itself an explicit specialization
1844              already, the first line specializes "f" which is a non-template
1845              member function, whilst the second line specializes "f" which
1846              is a template member function. So both lines are syntactically
1847              correct, and check_explicit_specialization does not reject
1848              them.
1849
1850              Here, we can do better, as we are matching the specialization
1851              against the declarations. We count the number of template
1852              headers, and we check if they match TEMPLATE_COUNT + 1
1853              (TEMPLATE_COUNT is the number of qualifying template classes,
1854              plus there must be another header for the member template
1855              itself).
1856
1857              Notice that if header_count is zero, this is not a
1858              specialization but rather a template instantiation, so there
1859              is no check we can perform here.  */
1860           if (header_count && header_count != template_count + 1)
1861             continue;
1862
1863           /* Check that the number of template arguments at the
1864              innermost level for DECL is the same as for FN.  */
1865           if (current_binding_level->kind == sk_template_parms
1866               && !current_binding_level->explicit_spec_p
1867               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1868                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1869                                       (current_template_parms))))
1870             continue;
1871
1872           /* DECL might be a specialization of FN.  */
1873           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1874           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1875
1876           /* For a non-static member function, we need to make sure
1877              that the const qualification is the same.  Since
1878              get_bindings does not try to merge the "this" parameter,
1879              we must do the comparison explicitly.  */
1880           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1881               && !same_type_p (TREE_VALUE (fn_arg_types),
1882                                TREE_VALUE (decl_arg_types)))
1883             continue;
1884
1885           /* Skip the "this" parameter and, for constructors of
1886              classes with virtual bases, the VTT parameter.  A
1887              full specialization of a constructor will have a VTT
1888              parameter, but a template never will.  */ 
1889           decl_arg_types 
1890             = skip_artificial_parms_for (decl, decl_arg_types);
1891           fn_arg_types 
1892             = skip_artificial_parms_for (fn, fn_arg_types);
1893
1894           /* Check that the number of function parameters matches.
1895              For example,
1896                template <class T> void f(int i = 0);
1897                template <> void f<int>();
1898              The specialization f<int> is invalid but is not caught
1899              by get_bindings below.  */
1900           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1901             continue;
1902
1903           /* Function templates cannot be specializations; there are
1904              no partial specializations of functions.  Therefore, if
1905              the type of DECL does not match FN, there is no
1906              match.  */
1907           if (tsk == tsk_template)
1908             {
1909               if (compparms (fn_arg_types, decl_arg_types))
1910                 candidates = tree_cons (NULL_TREE, fn, candidates);
1911               continue;
1912             }
1913
1914           /* See whether this function might be a specialization of this
1915              template.  */
1916           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1917
1918           if (!targs)
1919             /* We cannot deduce template arguments that when used to
1920                specialize TMPL will produce DECL.  */
1921             continue;
1922
1923           /* Save this template, and the arguments deduced.  */
1924           templates = tree_cons (targs, fn, templates);
1925         }
1926       else if (need_member_template)
1927         /* FN is an ordinary member function, and we need a
1928            specialization of a member template.  */
1929         ;
1930       else if (TREE_CODE (fn) != FUNCTION_DECL)
1931         /* We can get IDENTIFIER_NODEs here in certain erroneous
1932            cases.  */
1933         ;
1934       else if (!DECL_FUNCTION_MEMBER_P (fn))
1935         /* This is just an ordinary non-member function.  Nothing can
1936            be a specialization of that.  */
1937         ;
1938       else if (DECL_ARTIFICIAL (fn))
1939         /* Cannot specialize functions that are created implicitly.  */
1940         ;
1941       else
1942         {
1943           tree decl_arg_types;
1944
1945           /* This is an ordinary member function.  However, since
1946              we're here, we can assume it's enclosing class is a
1947              template class.  For example,
1948
1949                template <typename T> struct S { void f(); };
1950                template <> void S<int>::f() {}
1951
1952              Here, S<int>::f is a non-template, but S<int> is a
1953              template class.  If FN has the same type as DECL, we
1954              might be in business.  */
1955
1956           if (!DECL_TEMPLATE_INFO (fn))
1957             /* Its enclosing class is an explicit specialization
1958                of a template class.  This is not a candidate.  */
1959             continue;
1960
1961           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1962                             TREE_TYPE (TREE_TYPE (fn))))
1963             /* The return types differ.  */
1964             continue;
1965
1966           /* Adjust the type of DECL in case FN is a static member.  */
1967           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1968           if (DECL_STATIC_FUNCTION_P (fn)
1969               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1970             decl_arg_types = TREE_CHAIN (decl_arg_types);
1971
1972           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1973                          decl_arg_types))
1974             /* They match!  */
1975             candidates = tree_cons (NULL_TREE, fn, candidates);
1976         }
1977     }
1978
1979   if (templates && TREE_CHAIN (templates))
1980     {
1981       /* We have:
1982
1983            [temp.expl.spec]
1984
1985            It is possible for a specialization with a given function
1986            signature to be instantiated from more than one function
1987            template.  In such cases, explicit specification of the
1988            template arguments must be used to uniquely identify the
1989            function template specialization being specialized.
1990
1991          Note that here, there's no suggestion that we're supposed to
1992          determine which of the candidate templates is most
1993          specialized.  However, we, also have:
1994
1995            [temp.func.order]
1996
1997            Partial ordering of overloaded function template
1998            declarations is used in the following contexts to select
1999            the function template to which a function template
2000            specialization refers:
2001
2002            -- when an explicit specialization refers to a function
2003               template.
2004
2005          So, we do use the partial ordering rules, at least for now.
2006          This extension can only serve to make invalid programs valid,
2007          so it's safe.  And, there is strong anecdotal evidence that
2008          the committee intended the partial ordering rules to apply;
2009          the EDG front end has that behavior, and John Spicer claims
2010          that the committee simply forgot to delete the wording in
2011          [temp.expl.spec].  */
2012       tree tmpl = most_specialized_instantiation (templates);
2013       if (tmpl != error_mark_node)
2014         {
2015           templates = tmpl;
2016           TREE_CHAIN (templates) = NULL_TREE;
2017         }
2018     }
2019
2020   if (templates == NULL_TREE && candidates == NULL_TREE)
2021     {
2022       error ("template-id %qD for %q+D does not match any template "
2023              "declaration", template_id, decl);
2024       if (header_count && header_count != template_count + 1)
2025         inform (input_location, "saw %d %<template<>%>, need %d for "
2026                 "specializing a member function template",
2027                 header_count, template_count + 1);
2028       return error_mark_node;
2029     }
2030   else if ((templates && TREE_CHAIN (templates))
2031            || (candidates && TREE_CHAIN (candidates))
2032            || (templates && candidates))
2033     {
2034       error ("ambiguous template specialization %qD for %q+D",
2035              template_id, decl);
2036       candidates = chainon (candidates, templates);
2037       print_candidates (candidates);
2038       return error_mark_node;
2039     }
2040
2041   /* We have one, and exactly one, match.  */
2042   if (candidates)
2043     {
2044       tree fn = TREE_VALUE (candidates);
2045       *targs_out = copy_node (DECL_TI_ARGS (fn));
2046       /* DECL is a re-declaration or partial instantiation of a template
2047          function.  */
2048       if (TREE_CODE (fn) == TEMPLATE_DECL)
2049         return fn;
2050       /* It was a specialization of an ordinary member function in a
2051          template class.  */
2052       return DECL_TI_TEMPLATE (fn);
2053     }
2054
2055   /* It was a specialization of a template.  */
2056   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2057   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2058     {
2059       *targs_out = copy_node (targs);
2060       SET_TMPL_ARGS_LEVEL (*targs_out,
2061                            TMPL_ARGS_DEPTH (*targs_out),
2062                            TREE_PURPOSE (templates));
2063     }
2064   else
2065     *targs_out = TREE_PURPOSE (templates);
2066   return TREE_VALUE (templates);
2067 }
2068
2069 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2070    but with the default argument values filled in from those in the
2071    TMPL_TYPES.  */
2072
2073 static tree
2074 copy_default_args_to_explicit_spec_1 (tree spec_types,
2075                                       tree tmpl_types)
2076 {
2077   tree new_spec_types;
2078
2079   if (!spec_types)
2080     return NULL_TREE;
2081
2082   if (spec_types == void_list_node)
2083     return void_list_node;
2084
2085   /* Substitute into the rest of the list.  */
2086   new_spec_types =
2087     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2088                                           TREE_CHAIN (tmpl_types));
2089
2090   /* Add the default argument for this parameter.  */
2091   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2092                          TREE_VALUE (spec_types),
2093                          new_spec_types);
2094 }
2095
2096 /* DECL is an explicit specialization.  Replicate default arguments
2097    from the template it specializes.  (That way, code like:
2098
2099      template <class T> void f(T = 3);
2100      template <> void f(double);
2101      void g () { f (); }
2102
2103    works, as required.)  An alternative approach would be to look up
2104    the correct default arguments at the call-site, but this approach
2105    is consistent with how implicit instantiations are handled.  */
2106
2107 static void
2108 copy_default_args_to_explicit_spec (tree decl)
2109 {
2110   tree tmpl;
2111   tree spec_types;
2112   tree tmpl_types;
2113   tree new_spec_types;
2114   tree old_type;
2115   tree new_type;
2116   tree t;
2117   tree object_type = NULL_TREE;
2118   tree in_charge = NULL_TREE;
2119   tree vtt = NULL_TREE;
2120
2121   /* See if there's anything we need to do.  */
2122   tmpl = DECL_TI_TEMPLATE (decl);
2123   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2124   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2125     if (TREE_PURPOSE (t))
2126       break;
2127   if (!t)
2128     return;
2129
2130   old_type = TREE_TYPE (decl);
2131   spec_types = TYPE_ARG_TYPES (old_type);
2132
2133   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2134     {
2135       /* Remove the this pointer, but remember the object's type for
2136          CV quals.  */
2137       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2138       spec_types = TREE_CHAIN (spec_types);
2139       tmpl_types = TREE_CHAIN (tmpl_types);
2140
2141       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2142         {
2143           /* DECL may contain more parameters than TMPL due to the extra
2144              in-charge parameter in constructors and destructors.  */
2145           in_charge = spec_types;
2146           spec_types = TREE_CHAIN (spec_types);
2147         }
2148       if (DECL_HAS_VTT_PARM_P (decl))
2149         {
2150           vtt = spec_types;
2151           spec_types = TREE_CHAIN (spec_types);
2152         }
2153     }
2154
2155   /* Compute the merged default arguments.  */
2156   new_spec_types =
2157     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2158
2159   /* Compute the new FUNCTION_TYPE.  */
2160   if (object_type)
2161     {
2162       if (vtt)
2163         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2164                                          TREE_VALUE (vtt),
2165                                          new_spec_types);
2166
2167       if (in_charge)
2168         /* Put the in-charge parameter back.  */
2169         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2170                                          TREE_VALUE (in_charge),
2171                                          new_spec_types);
2172
2173       new_type = build_method_type_directly (object_type,
2174                                              TREE_TYPE (old_type),
2175                                              new_spec_types);
2176     }
2177   else
2178     new_type = build_function_type (TREE_TYPE (old_type),
2179                                     new_spec_types);
2180   new_type = cp_build_type_attribute_variant (new_type,
2181                                               TYPE_ATTRIBUTES (old_type));
2182   new_type = build_exception_variant (new_type,
2183                                       TYPE_RAISES_EXCEPTIONS (old_type));
2184   TREE_TYPE (decl) = new_type;
2185 }
2186
2187 /* Check to see if the function just declared, as indicated in
2188    DECLARATOR, and in DECL, is a specialization of a function
2189    template.  We may also discover that the declaration is an explicit
2190    instantiation at this point.
2191
2192    Returns DECL, or an equivalent declaration that should be used
2193    instead if all goes well.  Issues an error message if something is
2194    amiss.  Returns error_mark_node if the error is not easily
2195    recoverable.
2196
2197    FLAGS is a bitmask consisting of the following flags:
2198
2199    2: The function has a definition.
2200    4: The function is a friend.
2201
2202    The TEMPLATE_COUNT is the number of references to qualifying
2203    template classes that appeared in the name of the function.  For
2204    example, in
2205
2206      template <class T> struct S { void f(); };
2207      void S<int>::f();
2208
2209    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2210    classes are not counted in the TEMPLATE_COUNT, so that in
2211
2212      template <class T> struct S {};
2213      template <> struct S<int> { void f(); }
2214      template <> void S<int>::f();
2215
2216    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2217    invalid; there should be no template <>.)
2218
2219    If the function is a specialization, it is marked as such via
2220    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2221    is set up correctly, and it is added to the list of specializations
2222    for that template.  */
2223
2224 tree
2225 check_explicit_specialization (tree declarator,
2226                                tree decl,
2227                                int template_count,
2228                                int flags)
2229 {
2230   int have_def = flags & 2;
2231   int is_friend = flags & 4;
2232   int specialization = 0;
2233   int explicit_instantiation = 0;
2234   int member_specialization = 0;
2235   tree ctype = DECL_CLASS_CONTEXT (decl);
2236   tree dname = DECL_NAME (decl);
2237   tmpl_spec_kind tsk;
2238
2239   if (is_friend)
2240     {
2241       if (!processing_specialization)
2242         tsk = tsk_none;
2243       else
2244         tsk = tsk_excessive_parms;
2245     }
2246   else
2247     tsk = current_tmpl_spec_kind (template_count);
2248
2249   switch (tsk)
2250     {
2251     case tsk_none:
2252       if (processing_specialization)
2253         {
2254           specialization = 1;
2255           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2256         }
2257       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2258         {
2259           if (is_friend)
2260             /* This could be something like:
2261
2262                template <class T> void f(T);
2263                class S { friend void f<>(int); }  */
2264             specialization = 1;
2265           else
2266             {
2267               /* This case handles bogus declarations like template <>
2268                  template <class T> void f<int>(); */
2269
2270               error ("template-id %qD in declaration of primary template",
2271                      declarator);
2272               return decl;
2273             }
2274         }
2275       break;
2276
2277     case tsk_invalid_member_spec:
2278       /* The error has already been reported in
2279          check_specialization_scope.  */
2280       return error_mark_node;
2281
2282     case tsk_invalid_expl_inst:
2283       error ("template parameter list used in explicit instantiation");
2284
2285       /* Fall through.  */
2286
2287     case tsk_expl_inst:
2288       if (have_def)
2289         error ("definition provided for explicit instantiation");
2290
2291       explicit_instantiation = 1;
2292       break;
2293
2294     case tsk_excessive_parms:
2295     case tsk_insufficient_parms:
2296       if (tsk == tsk_excessive_parms)
2297         error ("too many template parameter lists in declaration of %qD",
2298                decl);
2299       else if (template_header_count)
2300         error("too few template parameter lists in declaration of %qD", decl);
2301       else
2302         error("explicit specialization of %qD must be introduced by "
2303               "%<template <>%>", decl);
2304
2305       /* Fall through.  */
2306     case tsk_expl_spec:
2307       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2308       if (ctype)
2309         member_specialization = 1;
2310       else
2311         specialization = 1;
2312       break;
2313
2314     case tsk_template:
2315       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2316         {
2317           /* This case handles bogus declarations like template <>
2318              template <class T> void f<int>(); */
2319
2320           if (uses_template_parms (declarator))
2321             error ("function template partial specialization %qD "
2322                    "is not allowed", declarator);
2323           else
2324             error ("template-id %qD in declaration of primary template",
2325                    declarator);
2326           return decl;
2327         }
2328
2329       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2330         /* This is a specialization of a member template, without
2331            specialization the containing class.  Something like:
2332
2333              template <class T> struct S {
2334                template <class U> void f (U);
2335              };
2336              template <> template <class U> void S<int>::f(U) {}
2337
2338            That's a specialization -- but of the entire template.  */
2339         specialization = 1;
2340       break;
2341
2342     default:
2343       gcc_unreachable ();
2344     }
2345
2346   if (specialization || member_specialization)
2347     {
2348       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2349       for (; t; t = TREE_CHAIN (t))
2350         if (TREE_PURPOSE (t))
2351           {
2352             permerror (input_location, 
2353                        "default argument specified in explicit specialization");
2354             break;
2355           }
2356     }
2357
2358   if (specialization || member_specialization || explicit_instantiation)
2359     {
2360       tree tmpl = NULL_TREE;
2361       tree targs = NULL_TREE;
2362
2363       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2364       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2365         {
2366           tree fns;
2367
2368           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2369           if (ctype)
2370             fns = dname;
2371           else
2372             {
2373               /* If there is no class context, the explicit instantiation
2374                  must be at namespace scope.  */
2375               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2376
2377               /* Find the namespace binding, using the declaration
2378                  context.  */
2379               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2380                                            false, true);
2381               if (fns == error_mark_node || !is_overloaded_fn (fns))
2382                 {
2383                   error ("%qD is not a template function", dname);
2384                   fns = error_mark_node;
2385                 }
2386               else
2387                 {
2388                   tree fn = OVL_CURRENT (fns);
2389                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2390                                                 CP_DECL_CONTEXT (fn)))
2391                     error ("%qD is not declared in %qD",
2392                            decl, current_namespace);
2393                 }
2394             }
2395
2396           declarator = lookup_template_function (fns, NULL_TREE);
2397         }
2398
2399       if (declarator == error_mark_node)
2400         return error_mark_node;
2401
2402       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2403         {
2404           if (!explicit_instantiation)
2405             /* A specialization in class scope.  This is invalid,
2406                but the error will already have been flagged by
2407                check_specialization_scope.  */
2408             return error_mark_node;
2409           else
2410             {
2411               /* It's not valid to write an explicit instantiation in
2412                  class scope, e.g.:
2413
2414                    class C { template void f(); }
2415
2416                    This case is caught by the parser.  However, on
2417                    something like:
2418
2419                    template class C { void f(); };
2420
2421                    (which is invalid) we can get here.  The error will be
2422                    issued later.  */
2423               ;
2424             }
2425
2426           return decl;
2427         }
2428       else if (ctype != NULL_TREE
2429                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2430                    IDENTIFIER_NODE))
2431         {
2432           /* Find the list of functions in ctype that have the same
2433              name as the declared function.  */
2434           tree name = TREE_OPERAND (declarator, 0);
2435           tree fns = NULL_TREE;
2436           int idx;
2437
2438           if (constructor_name_p (name, ctype))
2439             {
2440               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2441
2442               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2443                   : !CLASSTYPE_DESTRUCTORS (ctype))
2444                 {
2445                   /* From [temp.expl.spec]:
2446
2447                      If such an explicit specialization for the member
2448                      of a class template names an implicitly-declared
2449                      special member function (clause _special_), the
2450                      program is ill-formed.
2451
2452                      Similar language is found in [temp.explicit].  */
2453                   error ("specialization of implicitly-declared special member function");
2454                   return error_mark_node;
2455                 }
2456
2457               name = is_constructor ? ctor_identifier : dtor_identifier;
2458             }
2459
2460           if (!DECL_CONV_FN_P (decl))
2461             {
2462               idx = lookup_fnfields_1 (ctype, name);
2463               if (idx >= 0)
2464                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2465             }
2466           else
2467             {
2468               VEC(tree,gc) *methods;
2469               tree ovl;
2470
2471               /* For a type-conversion operator, we cannot do a
2472                  name-based lookup.  We might be looking for `operator
2473                  int' which will be a specialization of `operator T'.
2474                  So, we find *all* the conversion operators, and then
2475                  select from them.  */
2476               fns = NULL_TREE;
2477
2478               methods = CLASSTYPE_METHOD_VEC (ctype);
2479               if (methods)
2480                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2481                      VEC_iterate (tree, methods, idx, ovl);
2482                      ++idx)
2483                   {
2484                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2485                       /* There are no more conversion functions.  */
2486                       break;
2487
2488                     /* Glue all these conversion functions together
2489                        with those we already have.  */
2490                     for (; ovl; ovl = OVL_NEXT (ovl))
2491                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2492                   }
2493             }
2494
2495           if (fns == NULL_TREE)
2496             {
2497               error ("no member function %qD declared in %qT", name, ctype);
2498               return error_mark_node;
2499             }
2500           else
2501             TREE_OPERAND (declarator, 0) = fns;
2502         }
2503
2504       /* Figure out what exactly is being specialized at this point.
2505          Note that for an explicit instantiation, even one for a
2506          member function, we cannot tell apriori whether the
2507          instantiation is for a member template, or just a member
2508          function of a template class.  Even if a member template is
2509          being instantiated, the member template arguments may be
2510          elided if they can be deduced from the rest of the
2511          declaration.  */
2512       tmpl = determine_specialization (declarator, decl,
2513                                        &targs,
2514                                        member_specialization,
2515                                        template_count,
2516                                        tsk);
2517
2518       if (!tmpl || tmpl == error_mark_node)
2519         /* We couldn't figure out what this declaration was
2520            specializing.  */
2521         return error_mark_node;
2522       else
2523         {
2524           tree gen_tmpl = most_general_template (tmpl);
2525
2526           if (explicit_instantiation)
2527             {
2528               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2529                  is done by do_decl_instantiation later.  */
2530
2531               int arg_depth = TMPL_ARGS_DEPTH (targs);
2532               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2533
2534               if (arg_depth > parm_depth)
2535                 {
2536                   /* If TMPL is not the most general template (for
2537                      example, if TMPL is a friend template that is
2538                      injected into namespace scope), then there will
2539                      be too many levels of TARGS.  Remove some of them
2540                      here.  */
2541                   int i;
2542                   tree new_targs;
2543
2544                   new_targs = make_tree_vec (parm_depth);
2545                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2546                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2547                       = TREE_VEC_ELT (targs, i);
2548                   targs = new_targs;
2549                 }
2550
2551               return instantiate_template (tmpl, targs, tf_error);
2552             }
2553
2554           /* If we thought that the DECL was a member function, but it
2555              turns out to be specializing a static member function,
2556              make DECL a static member function as well.  */
2557           if (DECL_STATIC_FUNCTION_P (tmpl)
2558               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2559             revert_static_member_fn (decl);
2560
2561           /* If this is a specialization of a member template of a
2562              template class, we want to return the TEMPLATE_DECL, not
2563              the specialization of it.  */
2564           if (tsk == tsk_template)
2565             {
2566               tree result = DECL_TEMPLATE_RESULT (tmpl);
2567               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2568               DECL_INITIAL (result) = NULL_TREE;
2569               if (have_def)
2570                 {
2571                   tree parm;
2572                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2573                   DECL_SOURCE_LOCATION (result)
2574                     = DECL_SOURCE_LOCATION (decl);
2575                   /* We want to use the argument list specified in the
2576                      definition, not in the original declaration.  */
2577                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2578                   for (parm = DECL_ARGUMENTS (result); parm;
2579                        parm = DECL_CHAIN (parm))
2580                     DECL_CONTEXT (parm) = result;
2581                 }
2582               return register_specialization (tmpl, gen_tmpl, targs,
2583                                               is_friend, 0);
2584             }
2585
2586           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2587           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2588
2589           /* Inherit default function arguments from the template
2590              DECL is specializing.  */
2591           copy_default_args_to_explicit_spec (decl);
2592
2593           /* This specialization has the same protection as the
2594              template it specializes.  */
2595           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2596           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2597
2598           /* 7.1.1-1 [dcl.stc]
2599
2600              A storage-class-specifier shall not be specified in an
2601              explicit specialization...
2602
2603              The parser rejects these, so unless action is taken here,
2604              explicit function specializations will always appear with
2605              global linkage.
2606
2607              The action recommended by the C++ CWG in response to C++
2608              defect report 605 is to make the storage class and linkage
2609              of the explicit specialization match the templated function:
2610
2611              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2612            */
2613           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2614             {
2615               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2616               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2617
2618               /* This specialization has the same linkage and visibility as
2619                  the function template it specializes.  */
2620               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2621               if (! TREE_PUBLIC (decl))
2622                 {
2623                   DECL_INTERFACE_KNOWN (decl) = 1;
2624                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2625                 }
2626               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2627               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2628                 {
2629                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2630                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2631                 }
2632             }
2633
2634           /* If DECL is a friend declaration, declared using an
2635              unqualified name, the namespace associated with DECL may
2636              have been set incorrectly.  For example, in:
2637
2638                template <typename T> void f(T);
2639                namespace N {
2640                  struct S { friend void f<int>(int); }
2641                }
2642
2643              we will have set the DECL_CONTEXT for the friend
2644              declaration to N, rather than to the global namespace.  */
2645           if (DECL_NAMESPACE_SCOPE_P (decl))
2646             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2647
2648           if (is_friend && !have_def)
2649             /* This is not really a declaration of a specialization.
2650                It's just the name of an instantiation.  But, it's not
2651                a request for an instantiation, either.  */
2652             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2653           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2654             /* This is indeed a specialization.  In case of constructors
2655                and destructors, we need in-charge and not-in-charge
2656                versions in V3 ABI.  */
2657             clone_function_decl (decl, /*update_method_vec_p=*/0);
2658
2659           /* Register this specialization so that we can find it
2660              again.  */
2661           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2662         }
2663     }
2664
2665   return decl;
2666 }
2667
2668 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2669    parameters.  These are represented in the same format used for
2670    DECL_TEMPLATE_PARMS.  */
2671
2672 int
2673 comp_template_parms (const_tree parms1, const_tree parms2)
2674 {
2675   const_tree p1;
2676   const_tree p2;
2677
2678   if (parms1 == parms2)
2679     return 1;
2680
2681   for (p1 = parms1, p2 = parms2;
2682        p1 != NULL_TREE && p2 != NULL_TREE;
2683        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2684     {
2685       tree t1 = TREE_VALUE (p1);
2686       tree t2 = TREE_VALUE (p2);
2687       int i;
2688
2689       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2690       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2691
2692       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2693         return 0;
2694
2695       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2696         {
2697           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2698           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2699
2700           /* If either of the template parameters are invalid, assume
2701              they match for the sake of error recovery. */
2702           if (parm1 == error_mark_node || parm2 == error_mark_node)
2703             return 1;
2704
2705           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2706             return 0;
2707
2708           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2709               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2710                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2711             continue;
2712           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2713             return 0;
2714         }
2715     }
2716
2717   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2718     /* One set of parameters has more parameters lists than the
2719        other.  */
2720     return 0;
2721
2722   return 1;
2723 }
2724
2725 /* Determine whether PARM is a parameter pack.  */
2726
2727 bool 
2728 template_parameter_pack_p (const_tree parm)
2729 {
2730   /* Determine if we have a non-type template parameter pack.  */
2731   if (TREE_CODE (parm) == PARM_DECL)
2732     return (DECL_TEMPLATE_PARM_P (parm) 
2733             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2734
2735   /* If this is a list of template parameters, we could get a
2736      TYPE_DECL or a TEMPLATE_DECL.  */ 
2737   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2738     parm = TREE_TYPE (parm);
2739
2740   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2741            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2742           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2743 }
2744
2745 /* Determine if T is a function parameter pack.  */
2746
2747 bool
2748 function_parameter_pack_p (const_tree t)
2749 {
2750   if (t && TREE_CODE (t) == PARM_DECL)
2751     return FUNCTION_PARAMETER_PACK_P (t);
2752   return false;
2753 }
2754
2755 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2756    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2757
2758 tree
2759 get_function_template_decl (const_tree primary_func_tmpl_inst)
2760 {
2761   if (! primary_func_tmpl_inst
2762       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2763       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2764     return NULL;
2765
2766   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2767 }
2768
2769 /* Return true iff the function parameter PARAM_DECL was expanded
2770    from the function parameter pack PACK.  */
2771
2772 bool
2773 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2774 {
2775   if (DECL_ARTIFICIAL (param_decl)
2776       || !function_parameter_pack_p (pack))
2777     return false;
2778
2779   /* The parameter pack and its pack arguments have the same
2780      DECL_PARM_INDEX.  */
2781   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2782 }
2783
2784 /* Determine whether ARGS describes a variadic template args list,
2785    i.e., one that is terminated by a template argument pack.  */
2786
2787 static bool 
2788 template_args_variadic_p (tree args)
2789 {
2790   int nargs;
2791   tree last_parm;
2792
2793   if (args == NULL_TREE)
2794     return false;
2795
2796   args = INNERMOST_TEMPLATE_ARGS (args);
2797   nargs = TREE_VEC_LENGTH (args);
2798
2799   if (nargs == 0)
2800     return false;
2801
2802   last_parm = TREE_VEC_ELT (args, nargs - 1);
2803
2804   return ARGUMENT_PACK_P (last_parm);
2805 }
2806
2807 /* Generate a new name for the parameter pack name NAME (an
2808    IDENTIFIER_NODE) that incorporates its */
2809
2810 static tree
2811 make_ith_pack_parameter_name (tree name, int i)
2812 {
2813   /* Munge the name to include the parameter index.  */
2814 #define NUMBUF_LEN 128
2815   char numbuf[NUMBUF_LEN];
2816   char* newname;
2817   int newname_len;
2818
2819   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2820   newname_len = IDENTIFIER_LENGTH (name)
2821                 + strlen (numbuf) + 2;
2822   newname = (char*)alloca (newname_len);
2823   snprintf (newname, newname_len,
2824             "%s#%i", IDENTIFIER_POINTER (name), i);
2825   return get_identifier (newname);
2826 }
2827
2828 /* Return true if T is a primary function
2829    or class template instantiation.  */
2830
2831 bool
2832 primary_template_instantiation_p (const_tree t)
2833 {
2834   if (!t)
2835     return false;
2836
2837   if (TREE_CODE (t) == FUNCTION_DECL)
2838     return DECL_LANG_SPECIFIC (t)
2839            && DECL_TEMPLATE_INSTANTIATION (t)
2840            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2841   else if (CLASS_TYPE_P (t))
2842     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2843            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2844   return false;
2845 }
2846
2847 /* Return true if PARM is a template template parameter.  */
2848
2849 bool
2850 template_template_parameter_p (const_tree parm)
2851 {
2852   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2853 }
2854
2855 /* Return the template parameters of T if T is a
2856    primary template instantiation, NULL otherwise.  */
2857
2858 tree
2859 get_primary_template_innermost_parameters (const_tree t)
2860 {
2861   tree parms = NULL, template_info = NULL;
2862
2863   if ((template_info = get_template_info (t))
2864       && primary_template_instantiation_p (t))
2865     parms = INNERMOST_TEMPLATE_PARMS
2866         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2867
2868   return parms;
2869 }
2870
2871 /* Return the template parameters of the LEVELth level from the full list
2872    of template parameters PARMS.  */
2873
2874 tree
2875 get_template_parms_at_level (tree parms, int level)
2876 {
2877   tree p;
2878   if (!parms
2879       || TREE_CODE (parms) != TREE_LIST
2880       || level > TMPL_PARMS_DEPTH (parms))
2881     return NULL_TREE;
2882
2883   for (p = parms; p; p = TREE_CHAIN (p))
2884     if (TMPL_PARMS_DEPTH (p) == level)
2885       return p;
2886
2887   return NULL_TREE;
2888 }
2889
2890 /* Returns the template arguments of T if T is a template instantiation,
2891    NULL otherwise.  */
2892
2893 tree
2894 get_template_innermost_arguments (const_tree t)
2895 {
2896   tree args = NULL, template_info = NULL;
2897
2898   if ((template_info = get_template_info (t))
2899       && TI_ARGS (template_info))
2900     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2901
2902   return args;
2903 }
2904
2905 /* Return the argument pack elements of T if T is a template argument pack,
2906    NULL otherwise.  */
2907
2908 tree
2909 get_template_argument_pack_elems (const_tree t)
2910 {
2911   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2912       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2913     return NULL;
2914
2915   return ARGUMENT_PACK_ARGS (t);
2916 }
2917
2918 /* Structure used to track the progress of find_parameter_packs_r.  */
2919 struct find_parameter_pack_data 
2920 {
2921   /* TREE_LIST that will contain all of the parameter packs found by
2922      the traversal.  */
2923   tree* parameter_packs;
2924
2925   /* Set of AST nodes that have been visited by the traversal.  */
2926   struct pointer_set_t *visited;
2927 };
2928
2929 /* Identifies all of the argument packs that occur in a template
2930    argument and appends them to the TREE_LIST inside DATA, which is a
2931    find_parameter_pack_data structure. This is a subroutine of
2932    make_pack_expansion and uses_parameter_packs.  */
2933 static tree
2934 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2935 {
2936   tree t = *tp;
2937   struct find_parameter_pack_data* ppd = 
2938     (struct find_parameter_pack_data*)data;
2939   bool parameter_pack_p = false;
2940
2941   /* Identify whether this is a parameter pack or not.  */
2942   switch (TREE_CODE (t))
2943     {
2944     case TEMPLATE_PARM_INDEX:
2945       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2946         parameter_pack_p = true;
2947       break;
2948
2949     case TEMPLATE_TYPE_PARM:
2950     case TEMPLATE_TEMPLATE_PARM:
2951       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2952         parameter_pack_p = true;
2953       break;
2954
2955     case PARM_DECL:
2956       if (FUNCTION_PARAMETER_PACK_P (t))
2957         {
2958           /* We don't want to walk into the type of a PARM_DECL,
2959              because we don't want to see the type parameter pack.  */
2960           *walk_subtrees = 0;
2961           parameter_pack_p = true;
2962         }
2963       break;
2964
2965     default:
2966       /* Not a parameter pack.  */
2967       break;
2968     }
2969
2970   if (parameter_pack_p)
2971     {
2972       /* Add this parameter pack to the list.  */
2973       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2974     }
2975
2976   if (TYPE_P (t))
2977     cp_walk_tree (&TYPE_CONTEXT (t), 
2978                   &find_parameter_packs_r, ppd, ppd->visited);
2979
2980   /* This switch statement will return immediately if we don't find a
2981      parameter pack.  */
2982   switch (TREE_CODE (t)) 
2983     {
2984     case TEMPLATE_PARM_INDEX:
2985       return NULL_TREE;
2986
2987     case BOUND_TEMPLATE_TEMPLATE_PARM:
2988       /* Check the template itself.  */
2989       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2990                     &find_parameter_packs_r, ppd, ppd->visited);
2991       /* Check the template arguments.  */
2992       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2993                     ppd->visited);
2994       *walk_subtrees = 0;
2995       return NULL_TREE;
2996
2997     case TEMPLATE_TYPE_PARM:
2998     case TEMPLATE_TEMPLATE_PARM:
2999       return NULL_TREE;
3000
3001     case PARM_DECL:
3002       return NULL_TREE;
3003
3004     case RECORD_TYPE:
3005       if (TYPE_PTRMEMFUNC_P (t))
3006         return NULL_TREE;
3007       /* Fall through.  */
3008
3009     case UNION_TYPE:
3010     case ENUMERAL_TYPE:
3011       if (TYPE_TEMPLATE_INFO (t))
3012         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3013                       &find_parameter_packs_r, ppd, ppd->visited);
3014
3015       *walk_subtrees = 0;
3016       return NULL_TREE;
3017
3018     case TEMPLATE_DECL:
3019       cp_walk_tree (&TREE_TYPE (t),
3020                     &find_parameter_packs_r, ppd, ppd->visited);
3021       return NULL_TREE;
3022  
3023     case TYPENAME_TYPE:
3024       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3025                    ppd, ppd->visited);
3026       *walk_subtrees = 0;
3027       return NULL_TREE;
3028       
3029     case TYPE_PACK_EXPANSION:
3030     case EXPR_PACK_EXPANSION:
3031       *walk_subtrees = 0;
3032       return NULL_TREE;
3033
3034     case INTEGER_TYPE:
3035       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3036                     ppd, ppd->visited);
3037       *walk_subtrees = 0;
3038       return NULL_TREE;
3039
3040     case IDENTIFIER_NODE:
3041       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3042                     ppd->visited);
3043       *walk_subtrees = 0;
3044       return NULL_TREE;
3045
3046     default:
3047       return NULL_TREE;
3048     }
3049
3050   return NULL_TREE;
3051 }
3052
3053 /* Determines if the expression or type T uses any parameter packs.  */
3054 bool
3055 uses_parameter_packs (tree t)
3056 {
3057   tree parameter_packs = NULL_TREE;
3058   struct find_parameter_pack_data ppd;
3059   ppd.parameter_packs = &parameter_packs;
3060   ppd.visited = pointer_set_create ();
3061   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3062   pointer_set_destroy (ppd.visited);
3063   return parameter_packs != NULL_TREE;
3064 }
3065
3066 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3067    representation a base-class initializer into a parameter pack
3068    expansion. If all goes well, the resulting node will be an
3069    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3070    respectively.  */
3071 tree 
3072 make_pack_expansion (tree arg)
3073 {
3074   tree result;
3075   tree parameter_packs = NULL_TREE;
3076   bool for_types = false;
3077   struct find_parameter_pack_data ppd;
3078
3079   if (!arg || arg == error_mark_node)
3080     return arg;
3081
3082   if (TREE_CODE (arg) == TREE_LIST)
3083     {
3084       /* The only time we will see a TREE_LIST here is for a base
3085          class initializer.  In this case, the TREE_PURPOSE will be a
3086          _TYPE node (representing the base class expansion we're
3087          initializing) and the TREE_VALUE will be a TREE_LIST
3088          containing the initialization arguments. 
3089
3090          The resulting expansion looks somewhat different from most
3091          expansions. Rather than returning just one _EXPANSION, we
3092          return a TREE_LIST whose TREE_PURPOSE is a
3093          TYPE_PACK_EXPANSION containing the bases that will be
3094          initialized.  The TREE_VALUE will be identical to the
3095          original TREE_VALUE, which is a list of arguments that will
3096          be passed to each base.  We do not introduce any new pack
3097          expansion nodes into the TREE_VALUE (although it is possible
3098          that some already exist), because the TREE_PURPOSE and
3099          TREE_VALUE all need to be expanded together with the same
3100          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3101          resulting TREE_PURPOSE will mention the parameter packs in
3102          both the bases and the arguments to the bases.  */
3103       tree purpose;
3104       tree value;
3105       tree parameter_packs = NULL_TREE;
3106
3107       /* Determine which parameter packs will be used by the base
3108          class expansion.  */
3109       ppd.visited = pointer_set_create ();
3110       ppd.parameter_packs = &parameter_packs;
3111       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3112                     &ppd, ppd.visited);
3113
3114       if (parameter_packs == NULL_TREE)
3115         {
3116           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3117           pointer_set_destroy (ppd.visited);
3118           return error_mark_node;
3119         }
3120
3121       if (TREE_VALUE (arg) != void_type_node)
3122         {
3123           /* Collect the sets of parameter packs used in each of the
3124              initialization arguments.  */
3125           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3126             {
3127               /* Determine which parameter packs will be expanded in this
3128                  argument.  */
3129               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3130                             &ppd, ppd.visited);
3131             }
3132         }
3133
3134       pointer_set_destroy (ppd.visited);
3135
3136       /* Create the pack expansion type for the base type.  */
3137       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3138       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3139       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3140
3141       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3142          they will rarely be compared to anything.  */
3143       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3144
3145       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3146     }
3147
3148   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3149     for_types = true;
3150
3151   /* Build the PACK_EXPANSION_* node.  */
3152   result = for_types
3153      ? cxx_make_type (TYPE_PACK_EXPANSION)
3154      : make_node (EXPR_PACK_EXPANSION);
3155   SET_PACK_EXPANSION_PATTERN (result, arg);
3156   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3157     {
3158       /* Propagate type and const-expression information.  */
3159       TREE_TYPE (result) = TREE_TYPE (arg);
3160       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3161     }
3162   else
3163     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3164        they will rarely be compared to anything.  */
3165     SET_TYPE_STRUCTURAL_EQUALITY (result);
3166
3167   /* Determine which parameter packs will be expanded.  */
3168   ppd.parameter_packs = &parameter_packs;
3169   ppd.visited = pointer_set_create ();
3170   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3171   pointer_set_destroy (ppd.visited);
3172
3173   /* Make sure we found some parameter packs.  */
3174   if (parameter_packs == NULL_TREE)
3175     {
3176       if (TYPE_P (arg))
3177         error ("expansion pattern %<%T%> contains no argument packs", arg);
3178       else
3179         error ("expansion pattern %<%E%> contains no argument packs", arg);
3180       return error_mark_node;
3181     }
3182   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3183
3184   return result;
3185 }
3186
3187 /* Checks T for any "bare" parameter packs, which have not yet been
3188    expanded, and issues an error if any are found. This operation can
3189    only be done on full expressions or types (e.g., an expression
3190    statement, "if" condition, etc.), because we could have expressions like:
3191
3192      foo(f(g(h(args)))...)
3193
3194    where "args" is a parameter pack. check_for_bare_parameter_packs
3195    should not be called for the subexpressions args, h(args),
3196    g(h(args)), or f(g(h(args))), because we would produce erroneous
3197    error messages. 
3198
3199    Returns TRUE and emits an error if there were bare parameter packs,
3200    returns FALSE otherwise.  */
3201 bool 
3202 check_for_bare_parameter_packs (tree t)
3203 {
3204   tree parameter_packs = NULL_TREE;
3205   struct find_parameter_pack_data ppd;
3206
3207   if (!processing_template_decl || !t || t == error_mark_node)
3208     return false;
3209
3210   if (TREE_CODE (t) == TYPE_DECL)
3211     t = TREE_TYPE (t);
3212
3213   ppd.parameter_packs = &parameter_packs;
3214   ppd.visited = pointer_set_create ();
3215   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3216   pointer_set_destroy (ppd.visited);
3217
3218   if (parameter_packs) 
3219     {
3220       error ("parameter packs not expanded with %<...%>:");
3221       while (parameter_packs)
3222         {
3223           tree pack = TREE_VALUE (parameter_packs);
3224           tree name = NULL_TREE;
3225
3226           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3227               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3228             name = TYPE_NAME (pack);
3229           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3230             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3231           else
3232             name = DECL_NAME (pack);
3233
3234           if (name)
3235             inform (input_location, "        %qD", name);
3236           else
3237             inform (input_location, "        <anonymous>");
3238
3239           parameter_packs = TREE_CHAIN (parameter_packs);
3240         }
3241
3242       return true;
3243     }
3244
3245   return false;
3246 }
3247
3248 /* Expand any parameter packs that occur in the template arguments in
3249    ARGS.  */
3250 tree
3251 expand_template_argument_pack (tree args)
3252 {
3253   tree result_args = NULL_TREE;
3254   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3255   int num_result_args = -1;
3256   int non_default_args_count = -1;
3257
3258   /* First, determine if we need to expand anything, and the number of
3259      slots we'll need.  */
3260   for (in_arg = 0; in_arg < nargs; ++in_arg)
3261     {
3262       tree arg = TREE_VEC_ELT (args, in_arg);
3263       if (arg == NULL_TREE)
3264         return args;
3265       if (ARGUMENT_PACK_P (arg))
3266         {
3267           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3268           if (num_result_args < 0)
3269             num_result_args = in_arg + num_packed;
3270           else
3271             num_result_args += num_packed;
3272         }
3273       else
3274         {
3275           if (num_result_args >= 0)
3276             num_result_args++;
3277         }
3278     }
3279
3280   /* If no expansion is necessary, we're done.  */
3281   if (num_result_args < 0)
3282     return args;
3283
3284   /* Expand arguments.  */
3285   result_args = make_tree_vec (num_result_args);
3286   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3287     non_default_args_count =
3288       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3289   for (in_arg = 0; in_arg < nargs; ++in_arg)
3290     {
3291       tree arg = TREE_VEC_ELT (args, in_arg);
3292       if (ARGUMENT_PACK_P (arg))
3293         {
3294           tree packed = ARGUMENT_PACK_ARGS (arg);
3295           int i, num_packed = TREE_VEC_LENGTH (packed);
3296           for (i = 0; i < num_packed; ++i, ++out_arg)
3297             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3298           if (non_default_args_count > 0)
3299             non_default_args_count += num_packed;
3300         }
3301       else
3302         {
3303           TREE_VEC_ELT (result_args, out_arg) = arg;
3304           ++out_arg;
3305         }
3306     }
3307   if (non_default_args_count >= 0)
3308     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3309   return result_args;
3310 }
3311
3312 /* Checks if DECL shadows a template parameter.
3313
3314    [temp.local]: A template-parameter shall not be redeclared within its
3315    scope (including nested scopes).
3316
3317    Emits an error and returns TRUE if the DECL shadows a parameter,
3318    returns FALSE otherwise.  */
3319
3320 bool
3321 check_template_shadow (tree decl)
3322 {
3323   tree olddecl;
3324
3325   /* If we're not in a template, we can't possibly shadow a template
3326      parameter.  */
3327   if (!current_template_parms)
3328     return true;
3329
3330   /* Figure out what we're shadowing.  */
3331   if (TREE_CODE (decl) == OVERLOAD)
3332     decl = OVL_CURRENT (decl);
3333   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3334
3335   /* If there's no previous binding for this name, we're not shadowing
3336      anything, let alone a template parameter.  */
3337   if (!olddecl)
3338     return true;
3339
3340   /* If we're not shadowing a template parameter, we're done.  Note
3341      that OLDDECL might be an OVERLOAD (or perhaps even an
3342      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3343      node.  */
3344   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3345     return true;
3346
3347   /* We check for decl != olddecl to avoid bogus errors for using a
3348      name inside a class.  We check TPFI to avoid duplicate errors for
3349      inline member templates.  */
3350   if (decl == olddecl
3351       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3352     return true;
3353
3354   error ("declaration of %q+#D", decl);
3355   error (" shadows template parm %q+#D", olddecl);
3356   return false;
3357 }
3358
3359 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3360    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3361    template parameters.  */
3362
3363 static tree
3364 build_template_parm_index (int index,
3365                            int level,
3366                            int orig_level,
3367                            int num_siblings,
3368                            tree decl,
3369                            tree type)
3370 {
3371   tree t = make_node (TEMPLATE_PARM_INDEX);
3372   TEMPLATE_PARM_IDX (t) = index;
3373   TEMPLATE_PARM_LEVEL (t) = level;
3374   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3375   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3376   TEMPLATE_PARM_DECL (t) = decl;
3377   TREE_TYPE (t) = type;
3378   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3379   TREE_READONLY (t) = TREE_READONLY (decl);
3380
3381   return t;
3382 }
3383
3384 /* Find the canonical type parameter for the given template type
3385    parameter.  Returns the canonical type parameter, which may be TYPE
3386    if no such parameter existed.  */
3387
3388 static tree
3389 canonical_type_parameter (tree type)
3390 {
3391   tree list;
3392   int idx = TEMPLATE_TYPE_IDX (type);
3393   if (!canonical_template_parms)
3394     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3395
3396   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3397     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3398
3399   list = VEC_index (tree, canonical_template_parms, idx);
3400   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3401     list = TREE_CHAIN (list);
3402
3403   if (list)
3404     return TREE_VALUE (list);
3405   else
3406     {
3407       VEC_replace(tree, canonical_template_parms, idx,
3408                   tree_cons (NULL_TREE, type, 
3409                              VEC_index (tree, canonical_template_parms, idx)));
3410       return type;
3411     }
3412 }
3413
3414 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3415    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3416    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3417    new one is created.  */
3418
3419 static tree
3420 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3421                             tsubst_flags_t complain)
3422 {
3423   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3424       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3425           != TEMPLATE_PARM_LEVEL (index) - levels)
3426       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3427     {
3428       tree orig_decl = TEMPLATE_PARM_DECL (index);
3429       tree decl, t;
3430
3431       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3432                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3433       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3434       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3435       DECL_ARTIFICIAL (decl) = 1;
3436       SET_DECL_TEMPLATE_PARM_P (decl);
3437
3438       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3439                                      TEMPLATE_PARM_LEVEL (index) - levels,
3440                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3441                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3442                                      decl, type);
3443       TEMPLATE_PARM_DESCENDANTS (index) = t;
3444       TEMPLATE_PARM_PARAMETER_PACK (t) 
3445         = TEMPLATE_PARM_PARAMETER_PACK (index);
3446
3447         /* Template template parameters need this.  */
3448       if (TREE_CODE (decl) == TEMPLATE_DECL)
3449         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3450           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3451            args, complain);
3452     }
3453
3454   return TEMPLATE_PARM_DESCENDANTS (index);
3455 }
3456
3457 /* Process information from new template parameter PARM and append it
3458    to the LIST being built.  This new parameter is a non-type
3459    parameter iff IS_NON_TYPE is true. This new parameter is a
3460    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3461    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3462    parameter list PARM belongs to. This is used used to create a
3463    proper canonical type for the type of PARM that is to be created,
3464    iff PARM is a type.  If the size is not known, this parameter shall
3465    be set to 0.  */
3466
3467 tree
3468 process_template_parm (tree list, location_t parm_loc, tree parm,
3469                        bool is_non_type, bool is_parameter_pack,
3470                        unsigned num_template_parms)
3471 {
3472   tree decl = 0;
3473   tree defval;
3474   tree err_parm_list;
3475   int idx = 0;
3476
3477   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3478   defval = TREE_PURPOSE (parm);
3479
3480   if (list)
3481     {
3482       tree p = tree_last (list);
3483
3484       if (p && TREE_VALUE (p) != error_mark_node)
3485         {
3486           p = TREE_VALUE (p);
3487           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3488             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3489           else
3490             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3491         }
3492
3493       ++idx;
3494     }
3495   else
3496     idx = 0;
3497
3498   if (is_non_type)
3499     {
3500       parm = TREE_VALUE (parm);
3501
3502       SET_DECL_TEMPLATE_PARM_P (parm);
3503
3504       if (TREE_TYPE (parm) == error_mark_node)
3505         {
3506           err_parm_list = build_tree_list (defval, parm);
3507           TREE_VALUE (err_parm_list) = error_mark_node;
3508            return chainon (list, err_parm_list);
3509         }
3510       else
3511       {
3512         /* [temp.param]
3513
3514            The top-level cv-qualifiers on the template-parameter are
3515            ignored when determining its type.  */
3516         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3517         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3518           {
3519             err_parm_list = build_tree_list (defval, parm);
3520             TREE_VALUE (err_parm_list) = error_mark_node;
3521              return chainon (list, err_parm_list);
3522           }
3523
3524         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3525           {
3526             /* This template parameter is not a parameter pack, but it
3527                should be. Complain about "bare" parameter packs.  */
3528             check_for_bare_parameter_packs (TREE_TYPE (parm));
3529             
3530             /* Recover by calling this a parameter pack.  */
3531             is_parameter_pack = true;
3532           }
3533       }
3534
3535       /* A template parameter is not modifiable.  */
3536       TREE_CONSTANT (parm) = 1;
3537       TREE_READONLY (parm) = 1;
3538       decl = build_decl (parm_loc,
3539                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3540       TREE_CONSTANT (decl) = 1;
3541       TREE_READONLY (decl) = 1;
3542       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3543         = build_template_parm_index (idx, processing_template_decl,
3544                                      processing_template_decl,
3545                                      num_template_parms,
3546                                      decl, TREE_TYPE (parm));
3547
3548       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3549         = is_parameter_pack;
3550     }
3551   else
3552     {
3553       tree t;
3554       parm = TREE_VALUE (TREE_VALUE (parm));
3555
3556       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3557         {
3558           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3559           /* This is for distinguishing between real templates and template
3560              template parameters */
3561           TREE_TYPE (parm) = t;
3562           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3563           decl = parm;
3564         }
3565       else
3566         {
3567           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3568           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3569           decl = build_decl (parm_loc,
3570                              TYPE_DECL, parm, t);
3571         }
3572
3573       TYPE_NAME (t) = decl;
3574       TYPE_STUB_DECL (t) = decl;
3575       parm = decl;
3576       TEMPLATE_TYPE_PARM_INDEX (t)
3577         = build_template_parm_index (idx, processing_template_decl,
3578                                      processing_template_decl,
3579                                      num_template_parms,
3580                                      decl, TREE_TYPE (parm));
3581       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3582       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3583     }
3584   DECL_ARTIFICIAL (decl) = 1;
3585   SET_DECL_TEMPLATE_PARM_P (decl);
3586   pushdecl (decl);
3587   parm = build_tree_list (defval, parm);
3588   return chainon (list, parm);
3589 }
3590
3591 /* The end of a template parameter list has been reached.  Process the
3592    tree list into a parameter vector, converting each parameter into a more
3593    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3594    as PARM_DECLs.  */
3595
3596 tree
3597 end_template_parm_list (tree parms)
3598 {
3599   int nparms;
3600   tree parm, next;
3601   tree saved_parmlist = make_tree_vec (list_length (parms));
3602
3603   current_template_parms
3604     = tree_cons (size_int (processing_template_decl),
3605                  saved_parmlist, current_template_parms);
3606
3607   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3608     {
3609       next = TREE_CHAIN (parm);
3610       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3611       TREE_CHAIN (parm) = NULL_TREE;
3612     }
3613
3614   --processing_template_parmlist;
3615
3616   return saved_parmlist;
3617 }
3618
3619 /* Create a new type almost identical to TYPE but which has the
3620    following differences:
3621
3622      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3623      template sibling parameters of T.
3624
3625      2/ T has a new canonical type that matches the new number
3626      of sibling parms.
3627
3628      3/ From now on, T is going to be what lookups referring to the
3629      name of TYPE will return. No lookup should return TYPE anymore.
3630
3631    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3632
3633    This is a subroutine of fixup_template_parms.  */
3634
3635 static tree
3636 fixup_template_type_parm_type (tree type, int num_parms)
3637 {
3638   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3639   tree t;
3640   /* This is the decl which name is inserted into the symbol table for
3641      the template parm type. So whenever we lookup the type name, this
3642      is the DECL we get.  */
3643   tree decl;
3644
3645   /* Do not fix up the type twice.  */
3646   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3647     return type;
3648
3649   t = copy_type (type);
3650   decl = TYPE_NAME (t);
3651
3652   TYPE_MAIN_VARIANT (t) = t;
3653   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3654   TYPE_POINTER_TO (t) = 0;
3655   TYPE_REFERENCE_TO (t) = 0;
3656
3657   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3658                                    TEMPLATE_PARM_LEVEL (orig_idx),
3659                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3660                                    num_parms,
3661                                    decl, t);
3662   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3663   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3664   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3665
3666   TYPE_STUB_DECL (t) = decl;
3667   TEMPLATE_TYPE_DECL (t) = decl;
3668   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3669     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3670
3671   /* Update the type associated to the type name stored in the symbol
3672      table. Now, whenever the type name is looked up, the resulting
3673      type is properly fixed up.  */
3674   TREE_TYPE (decl) = t;
3675
3676   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3677
3678   return t;
3679 }
3680
3681 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3682    identical to I, but that is fixed up as to:
3683
3684    1/ carry the number of sibling parms (NUM_PARMS) of the template
3685    parm represented by I.
3686
3687    2/ replace all references to template parm types declared before I
3688    (in the same template parm list as I) by references to template
3689    parm types contained in ARGS. ARGS should contain the list of
3690    template parms that have been fixed up so far, in a form suitable
3691    to be passed to tsubst.
3692
3693    This is a subroutine of fixup_template_parms.  */
3694
3695 static tree
3696 fixup_template_parm_index (tree i, tree args, int num_parms)
3697 {
3698   tree index, decl, type;
3699
3700   if (i == NULL_TREE
3701       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3702       /* Do not fix up the index twice.  */
3703       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3704     return i;
3705
3706   decl = TEMPLATE_PARM_DECL (i);
3707   type = TREE_TYPE (decl);
3708
3709   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3710                                      TEMPLATE_PARM_LEVEL (i),
3711                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3712                                      num_parms,
3713                                      decl, type);
3714
3715   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3716   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3717
3718   type = tsubst (type, args, tf_none, NULL_TREE);
3719   
3720   TREE_TYPE (decl) = type;
3721   TREE_TYPE (index) = type;
3722
3723   return index;
3724 }
3725
3726 /* 
3727    This is a subroutine of fixup_template_parms.
3728
3729    It computes the canonical type of the type of the template
3730    parameter PARM_DESC and update all references to that type so that
3731    they use the newly computed canonical type. No access check is
3732    performed during the fixup. PARM_DESC is a TREE_LIST which
3733    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3734    default argument of the template parm if any. IDX is the index of
3735    the template parameter, starting at 0. NUM_PARMS is the number of
3736    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3737    TREE_VEC containing the full set of template parameters in a form
3738    suitable to be passed to substs functions as their ARGS
3739    argument. This is what current_template_args returns for a given
3740    template. The innermost vector of args in ARGLIST is the set of
3741    template parms that have been fixed up so far. This function adds
3742    the fixed up parameter into that vector.  */
3743
3744 static void
3745 fixup_template_parm (tree parm_desc,
3746                      int idx,
3747                      int num_parms,
3748                      tree arglist)
3749 {
3750   tree parm = TREE_VALUE (parm_desc);
3751   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3752
3753   push_deferring_access_checks (dk_no_check);
3754
3755   if (TREE_CODE (parm) == TYPE_DECL)
3756     {
3757       /* PARM is a template type parameter. Fix up its type, add
3758          the fixed-up template parm to the vector of fixed-up
3759          template parms so far, and substitute the fixed-up
3760          template parms into the default argument of this
3761          parameter.  */
3762       tree t =
3763         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3764       TREE_TYPE (parm) = t;
3765
3766       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3767     }
3768   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3769     {
3770       /* PARM is a template template parameter. This is going to
3771          be interesting.  */
3772       tree tparms, targs, innermost_args, t;
3773       int j;
3774
3775       /* First, fix up the parms of the template template parm
3776          because the parms are involved in defining the new canonical
3777          type of the template template parm.  */
3778
3779       /* So we need to substitute the template parm types that have
3780          been fixed up so far into the template parms of this template
3781          template parm. E.g, consider this:
3782
3783          template<class T, template<T u> class TT> class S;
3784
3785          In this case we want to substitute T into the
3786          template parameters of TT.
3787
3788          So let's walk the template parms of PARM here, and
3789          tsubst ARGLIST into into each of the template
3790          parms.   */
3791
3792       /* For this substitution we need to build the full set of
3793          template parameters and use that as arguments for the
3794          tsubsting function.  */
3795       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3796
3797       /* This will contain the innermost parms of PARM into which
3798          we have substituted so far.  */
3799       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3800       targs = add_to_template_args (arglist, innermost_args);
3801       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3802         {
3803           tree parameter;
3804
3805           parameter = TREE_VEC_ELT (tparms, j);
3806
3807           /* INNERMOST_ARGS needs to have at least the same number
3808              of elements as the index PARAMETER, ortherwise
3809              tsubsting into PARAMETER will result in partially
3810              instantiating it, reducing its tempate parm
3811              level. Let's tactically fill INNERMOST_ARGS for that
3812              purpose.  */
3813           TREE_VEC_ELT (innermost_args, j) =
3814             template_parm_to_arg (parameter);
3815
3816           fixup_template_parm (parameter, j,
3817                                TREE_VEC_LENGTH (tparms),
3818                                targs);
3819         }
3820
3821       /* Now fix up the type of the template template parm.  */
3822
3823       t = fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3824       TREE_TYPE (parm) = t;
3825
3826       TREE_VEC_ELT (fixedup_args, idx) =
3827         template_parm_to_arg (parm_desc);
3828     }
3829   else if (TREE_CODE (parm) == PARM_DECL)
3830     {
3831       /* PARM is a non-type template parameter. We need to:
3832
3833        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3834        proper number of sibling parameters.
3835
3836        * Make lookups of the template parameter return a reference
3837        to the fixed-up index. No lookup should return references
3838        to the former index anymore.
3839
3840        * Substitute the template parms that got fixed up so far
3841
3842        * into the type of PARM.  */
3843
3844       tree index = DECL_INITIAL (parm);
3845
3846       /* PUSHED_DECL is the decl added to the symbol table with
3847          the name of the parameter. E,g:
3848              
3849          template<class T, T u> //#0
3850          auto my_function(T t) -> decltype(u); //#1
3851
3852          Here, when looking up u at //#1, we get the decl of u
3853          resulting from the declaration in #0. This is what
3854          PUSHED_DECL is. We need to replace the reference to the
3855          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3856          fixed-up TEMPLATE_PARM_INDEX.  */
3857       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3858
3859       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3860          fixup the type of PUSHED_DECL as well and luckily
3861          fixup_template_parm_index does it for us too.  */
3862       tree fixed_up_index =
3863         fixup_template_parm_index (index, arglist, num_parms);
3864
3865       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3866
3867       /* Add this fixed up PARM to the template parms we've fixed
3868          up so far and use that to substitute the fixed-up
3869          template parms into the type of PARM.  */
3870       TREE_VEC_ELT (fixedup_args, idx) =
3871         template_parm_to_arg (parm_desc);
3872       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3873                                  tf_none, NULL_TREE);
3874     }
3875
3876   TREE_PURPOSE (parm_desc) =
3877     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3878                          arglist, tf_none, parm);
3879
3880   pop_deferring_access_checks ();
3881 }
3882
3883 /* Walk the current template parms and properly compute the canonical
3884    types of the dependent types created during
3885    cp_parser_template_parameter_list.  */
3886
3887 void
3888 fixup_template_parms (void)
3889 {
3890   tree arglist;
3891   tree parameter_vec;
3892   tree fixedup_args;
3893   int i, num_parms;
3894
3895   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3896   if (parameter_vec == NULL_TREE)
3897     return;
3898
3899   num_parms = TREE_VEC_LENGTH (parameter_vec);
3900
3901   /* This vector contains the current innermost template parms that
3902      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3903      to be passed to tsubst* functions as their ARGS argument.  */
3904   fixedup_args = make_tree_vec (num_parms);
3905
3906   /* This vector contains the full set of template parms in a form
3907      suitable to be passed to substs functions as their ARGS
3908      argument.  */
3909   arglist = current_template_args ();
3910   arglist = add_outermost_template_args (arglist, fixedup_args);
3911
3912   /* Let's do the proper fixup now.  */
3913   for (i = 0; i < num_parms; ++i)
3914     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3915                          i, num_parms, arglist);
3916 }
3917
3918 /* end_template_decl is called after a template declaration is seen.  */
3919
3920 void
3921 end_template_decl (void)
3922 {
3923   reset_specialization ();
3924
3925   if (! processing_template_decl)
3926     return;
3927
3928   /* This matches the pushlevel in begin_template_parm_list.  */
3929   finish_scope ();
3930
3931   --processing_template_decl;
3932   current_template_parms = TREE_CHAIN (current_template_parms);
3933 }
3934
3935 /* Takes a TREE_LIST representing a template parameter and convert it
3936    into an argument suitable to be passed to the type substitution
3937    functions.  Note that If the TREE_LIST contains an error_mark
3938    node, the returned argument is error_mark_node.  */
3939
3940 static tree
3941 template_parm_to_arg (tree t)
3942 {
3943
3944   if (t == NULL_TREE
3945       || TREE_CODE (t) != TREE_LIST)
3946     return t;
3947
3948   if (error_operand_p (TREE_VALUE (t)))
3949     return error_mark_node;
3950
3951   t = TREE_VALUE (t);
3952
3953   if (TREE_CODE (t) == TYPE_DECL
3954       || TREE_CODE (t) == TEMPLATE_DECL)
3955     {
3956       t = TREE_TYPE (t);
3957
3958       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3959         {
3960           /* Turn this argument into a TYPE_ARGUMENT_PACK
3961              with a single element, which expands T.  */
3962           tree vec = make_tree_vec (1);
3963 #ifdef ENABLE_CHECKING
3964           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3965             (vec, TREE_VEC_LENGTH (vec));
3966 #endif
3967           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3968
3969           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3970           SET_ARGUMENT_PACK_ARGS (t, vec);
3971         }
3972     }
3973   else
3974     {
3975       t = DECL_INITIAL (t);
3976
3977       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3978         {
3979           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3980              with a single element, which expands T.  */
3981           tree vec = make_tree_vec (1);
3982           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3983 #ifdef ENABLE_CHECKING
3984           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3985             (vec, TREE_VEC_LENGTH (vec));
3986 #endif
3987           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3988
3989           t  = make_node (NONTYPE_ARGUMENT_PACK);
3990           SET_ARGUMENT_PACK_ARGS (t, vec);
3991           TREE_TYPE (t) = type;
3992         }
3993     }
3994   return t;
3995 }
3996
3997 /* Within the declaration of a template, return all levels of template
3998    parameters that apply.  The template parameters are represented as
3999    a TREE_VEC, in the form documented in cp-tree.h for template
4000    arguments.  */
4001
4002 static tree
4003 current_template_args (void)
4004 {
4005   tree header;
4006   tree args = NULL_TREE;
4007   int length = TMPL_PARMS_DEPTH (current_template_parms);
4008   int l = length;
4009
4010   /* If there is only one level of template parameters, we do not
4011      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4012      TREE_VEC containing the arguments.  */
4013   if (length > 1)
4014     args = make_tree_vec (length);
4015
4016   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4017     {
4018       tree a = copy_node (TREE_VALUE (header));
4019       int i;
4020
4021       TREE_TYPE (a) = NULL_TREE;
4022       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4023         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4024
4025 #ifdef ENABLE_CHECKING
4026       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4027 #endif
4028
4029       if (length > 1)
4030         TREE_VEC_ELT (args, --l) = a;
4031       else
4032         args = a;
4033     }
4034
4035     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4036       /* This can happen for template parms of a template template
4037          parameter, e.g:
4038
4039          template<template<class T, class U> class TT> struct S;
4040
4041          Consider the level of the parms of TT; T and U both have
4042          level 2; TT has no template parm of level 1. So in this case
4043          the first element of full_template_args is NULL_TREE. If we
4044          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4045          of 2. This will make tsubst wrongly consider that T and U
4046          have level 1. Instead, let's create a dummy vector as the
4047          first element of full_template_args so that TMPL_ARG_DEPTH
4048          returns the correct depth for args.  */
4049       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4050   return args;
4051 }
4052
4053 /* Update the declared TYPE by doing any lookups which were thought to be
4054    dependent, but are not now that we know the SCOPE of the declarator.  */
4055
4056 tree
4057 maybe_update_decl_type (tree orig_type, tree scope)
4058 {
4059   tree type = orig_type;
4060
4061   if (type == NULL_TREE)
4062     return type;
4063
4064   if (TREE_CODE (orig_type) == TYPE_DECL)
4065     type = TREE_TYPE (type);
4066
4067   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4068       && dependent_type_p (type)
4069       /* Don't bother building up the args in this case.  */
4070       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4071     {
4072       /* tsubst in the args corresponding to the template parameters,
4073          including auto if present.  Most things will be unchanged, but
4074          make_typename_type and tsubst_qualified_id will resolve
4075          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4076       tree args = current_template_args ();
4077       tree auto_node = type_uses_auto (type);
4078       tree pushed;
4079       if (auto_node)
4080         {
4081           tree auto_vec = make_tree_vec (1);
4082           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4083           args = add_to_template_args (args, auto_vec);
4084         }
4085       pushed = push_scope (scope);
4086       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4087       if (pushed)
4088         pop_scope (scope);
4089     }
4090
4091   if (type == error_mark_node)
4092     return orig_type;
4093
4094   if (TREE_CODE (orig_type) == TYPE_DECL)
4095     {
4096       if (same_type_p (type, TREE_TYPE (orig_type)))
4097         type = orig_type;
4098       else
4099         type = TYPE_NAME (type);
4100     }
4101   return type;
4102 }
4103
4104 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4105    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4106    a member template.  Used by push_template_decl below.  */
4107
4108 static tree
4109 build_template_decl (tree decl, tree parms, bool member_template_p)
4110 {
4111   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4112   DECL_TEMPLATE_PARMS (tmpl) = parms;
4113   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4114   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4115
4116   return tmpl;
4117 }
4118
4119 struct template_parm_data
4120 {
4121   /* The level of the template parameters we are currently
4122      processing.  */
4123   int level;
4124
4125   /* The index of the specialization argument we are currently
4126      processing.  */
4127   int current_arg;
4128
4129   /* An array whose size is the number of template parameters.  The
4130      elements are nonzero if the parameter has been used in any one
4131      of the arguments processed so far.  */
4132   int* parms;
4133
4134   /* An array whose size is the number of template arguments.  The
4135      elements are nonzero if the argument makes use of template
4136      parameters of this level.  */
4137   int* arg_uses_template_parms;
4138 };
4139
4140 /* Subroutine of push_template_decl used to see if each template
4141    parameter in a partial specialization is used in the explicit
4142    argument list.  If T is of the LEVEL given in DATA (which is
4143    treated as a template_parm_data*), then DATA->PARMS is marked
4144    appropriately.  */
4145
4146 static int
4147 mark_template_parm (tree t, void* data)
4148 {
4149   int level;
4150   int idx;
4151   struct template_parm_data* tpd = (struct template_parm_data*) data;
4152
4153   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4154     {
4155       level = TEMPLATE_PARM_LEVEL (t);
4156       idx = TEMPLATE_PARM_IDX (t);
4157     }
4158   else
4159     {
4160       level = TEMPLATE_TYPE_LEVEL (t);
4161       idx = TEMPLATE_TYPE_IDX (t);
4162     }
4163
4164   if (level == tpd->level)
4165     {
4166       tpd->parms[idx] = 1;
4167       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4168     }
4169
4170   /* Return zero so that for_each_template_parm will continue the
4171      traversal of the tree; we want to mark *every* template parm.  */
4172   return 0;
4173 }
4174
4175 /* Process the partial specialization DECL.  */
4176
4177 static tree
4178 process_partial_specialization (tree decl)
4179 {
4180   tree type = TREE_TYPE (decl);
4181   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4182   tree specargs = CLASSTYPE_TI_ARGS (type);
4183   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4184   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4185   tree inner_parms;
4186   tree inst;
4187   int nargs = TREE_VEC_LENGTH (inner_args);
4188   int ntparms;
4189   int  i;
4190   bool did_error_intro = false;
4191   struct template_parm_data tpd;
4192   struct template_parm_data tpd2;
4193
4194   gcc_assert (current_template_parms);
4195
4196   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4197   ntparms = TREE_VEC_LENGTH (inner_parms);
4198
4199   /* We check that each of the template parameters given in the
4200      partial specialization is used in the argument list to the
4201      specialization.  For example:
4202
4203        template <class T> struct S;
4204        template <class T> struct S<T*>;
4205
4206      The second declaration is OK because `T*' uses the template
4207      parameter T, whereas
4208
4209        template <class T> struct S<int>;
4210
4211      is no good.  Even trickier is:
4212
4213        template <class T>
4214        struct S1
4215        {
4216           template <class U>
4217           struct S2;
4218           template <class U>
4219           struct S2<T>;
4220        };
4221
4222      The S2<T> declaration is actually invalid; it is a
4223      full-specialization.  Of course,
4224
4225           template <class U>
4226           struct S2<T (*)(U)>;
4227
4228      or some such would have been OK.  */
4229   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4230   tpd.parms = XALLOCAVEC (int, ntparms);
4231   memset (tpd.parms, 0, sizeof (int) * ntparms);
4232
4233   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4234   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4235   for (i = 0; i < nargs; ++i)
4236     {
4237       tpd.current_arg = i;
4238       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4239                               &mark_template_parm,
4240                               &tpd,
4241                               NULL,
4242                               /*include_nondeduced_p=*/false);
4243     }
4244   for (i = 0; i < ntparms; ++i)
4245     if (tpd.parms[i] == 0)
4246       {
4247         /* One of the template parms was not used in the
4248            specialization.  */
4249         if (!did_error_intro)
4250           {
4251             error ("template parameters not used in partial specialization:");
4252             did_error_intro = true;
4253           }
4254
4255         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4256       }
4257
4258   if (did_error_intro)
4259     return error_mark_node;
4260
4261   /* [temp.class.spec]
4262
4263      The argument list of the specialization shall not be identical to
4264      the implicit argument list of the primary template.  */
4265   if (comp_template_args
4266       (inner_args,
4267        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4268                                                    (maintmpl)))))
4269     error ("partial specialization %qT does not specialize any template arguments", type);
4270
4271   /* [temp.class.spec]
4272
4273      A partially specialized non-type argument expression shall not
4274      involve template parameters of the partial specialization except
4275      when the argument expression is a simple identifier.
4276
4277      The type of a template parameter corresponding to a specialized
4278      non-type argument shall not be dependent on a parameter of the
4279      specialization. 
4280
4281      Also, we verify that pack expansions only occur at the
4282      end of the argument list.  */
4283   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4284   tpd2.parms = 0;
4285   for (i = 0; i < nargs; ++i)
4286     {
4287       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4288       tree arg = TREE_VEC_ELT (inner_args, i);
4289       tree packed_args = NULL_TREE;
4290       int j, len = 1;
4291
4292       if (ARGUMENT_PACK_P (arg))
4293         {
4294           /* Extract the arguments from the argument pack. We'll be
4295              iterating over these in the following loop.  */
4296           packed_args = ARGUMENT_PACK_ARGS (arg);
4297           len = TREE_VEC_LENGTH (packed_args);
4298         }
4299
4300       for (j = 0; j < len; j++)
4301         {
4302           if (packed_args)
4303             /* Get the Jth argument in the parameter pack.  */
4304             arg = TREE_VEC_ELT (packed_args, j);
4305
4306           if (PACK_EXPANSION_P (arg))
4307             {
4308               /* Pack expansions must come at the end of the
4309                  argument list.  */
4310               if ((packed_args && j < len - 1)
4311                   || (!packed_args && i < nargs - 1))
4312                 {
4313                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4314                     error ("parameter pack argument %qE must be at the "
4315                            "end of the template argument list", arg);
4316                   else
4317                     error ("parameter pack argument %qT must be at the "
4318                            "end of the template argument list", arg);
4319                 }
4320             }
4321
4322           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4323             /* We only care about the pattern.  */
4324             arg = PACK_EXPANSION_PATTERN (arg);
4325
4326           if (/* These first two lines are the `non-type' bit.  */
4327               !TYPE_P (arg)
4328               && TREE_CODE (arg) != TEMPLATE_DECL
4329               /* This next line is the `argument expression is not just a
4330                  simple identifier' condition and also the `specialized
4331                  non-type argument' bit.  */
4332               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4333             {
4334               if ((!packed_args && tpd.arg_uses_template_parms[i])
4335                   || (packed_args && uses_template_parms (arg)))
4336                 error ("template argument %qE involves template parameter(s)",
4337                        arg);
4338               else 
4339                 {
4340                   /* Look at the corresponding template parameter,
4341                      marking which template parameters its type depends
4342                      upon.  */
4343                   tree type = TREE_TYPE (parm);
4344
4345                   if (!tpd2.parms)
4346                     {
4347                       /* We haven't yet initialized TPD2.  Do so now.  */
4348                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4349                       /* The number of parameters here is the number in the
4350                          main template, which, as checked in the assertion
4351                          above, is NARGS.  */
4352                       tpd2.parms = XALLOCAVEC (int, nargs);
4353                       tpd2.level = 
4354                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4355                     }
4356
4357                   /* Mark the template parameters.  But this time, we're
4358                      looking for the template parameters of the main
4359                      template, not in the specialization.  */
4360                   tpd2.current_arg = i;
4361                   tpd2.arg_uses_template_parms[i] = 0;
4362                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4363                   for_each_template_parm (type,
4364                                           &mark_template_parm,
4365                                           &tpd2,
4366                                           NULL,
4367                                           /*include_nondeduced_p=*/false);
4368
4369                   if (tpd2.arg_uses_template_parms [i])
4370                     {
4371                       /* The type depended on some template parameters.
4372                          If they are fully specialized in the
4373                          specialization, that's OK.  */
4374                       int j;
4375                       int count = 0;
4376                       for (j = 0; j < nargs; ++j)
4377                         if (tpd2.parms[j] != 0
4378                             && tpd.arg_uses_template_parms [j])
4379                           ++count;
4380                       if (count != 0)
4381                         error_n (input_location, count,
4382                                  "type %qT of template argument %qE depends "
4383                                  "on a template parameter",
4384                                  "type %qT of template argument %qE depends "
4385                                  "on template parameters",
4386                                  type,
4387                                  arg);
4388                     }
4389                 }
4390             }
4391         }
4392     }
4393
4394   /* We should only get here once.  */
4395   gcc_assert (!COMPLETE_TYPE_P (type));
4396
4397   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4398     = tree_cons (specargs, inner_parms,
4399                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4400   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4401
4402   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4403        inst = TREE_CHAIN (inst))
4404     {
4405       tree inst_type = TREE_VALUE (inst);
4406       if (COMPLETE_TYPE_P (inst_type)
4407           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4408         {
4409           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4410           if (spec && TREE_TYPE (spec) == type)
4411             permerror (input_location,
4412                        "partial specialization of %qT after instantiation "
4413                        "of %qT", type, inst_type);
4414         }
4415     }
4416
4417   return decl;
4418 }
4419
4420 /* Check that a template declaration's use of default arguments and
4421    parameter packs is not invalid.  Here, PARMS are the template
4422    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4423    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4424    specialization.
4425    
4426
4427    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4428    declaration (but not a definition); 1 indicates a declaration, 2
4429    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4430    emitted for extraneous default arguments.
4431
4432    Returns TRUE if there were no errors found, FALSE otherwise. */
4433
4434 bool
4435 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4436                          int is_partial, int is_friend_decl)
4437 {
4438   const char *msg;
4439   int last_level_to_check;
4440   tree parm_level;
4441   bool no_errors = true;
4442
4443   /* [temp.param]
4444
4445      A default template-argument shall not be specified in a
4446      function template declaration or a function template definition, nor
4447      in the template-parameter-list of the definition of a member of a
4448      class template.  */
4449
4450   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4451     /* You can't have a function template declaration in a local
4452        scope, nor you can you define a member of a class template in a
4453        local scope.  */
4454     return true;
4455
4456   if (current_class_type
4457       && !TYPE_BEING_DEFINED (current_class_type)
4458       && DECL_LANG_SPECIFIC (decl)
4459       && DECL_DECLARES_FUNCTION_P (decl)
4460       /* If this is either a friend defined in the scope of the class
4461          or a member function.  */
4462       && (DECL_FUNCTION_MEMBER_P (decl)
4463           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4464           : DECL_FRIEND_CONTEXT (decl)
4465           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4466           : false)
4467       /* And, if it was a member function, it really was defined in
4468          the scope of the class.  */
4469       && (!DECL_FUNCTION_MEMBER_P (decl)
4470           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4471     /* We already checked these parameters when the template was
4472        declared, so there's no need to do it again now.  This function
4473        was defined in class scope, but we're processing it's body now
4474        that the class is complete.  */
4475     return true;
4476
4477   /* Core issue 226 (C++0x only): the following only applies to class
4478      templates.  */
4479   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4480     {
4481       /* [temp.param]
4482
4483          If a template-parameter has a default template-argument, all
4484          subsequent template-parameters shall have a default
4485          template-argument supplied.  */
4486       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4487         {
4488           tree inner_parms = TREE_VALUE (parm_level);
4489           int ntparms = TREE_VEC_LENGTH (inner_parms);
4490           int seen_def_arg_p = 0;
4491           int i;
4492
4493           for (i = 0; i < ntparms; ++i)
4494             {
4495               tree parm = TREE_VEC_ELT (inner_parms, i);
4496
4497               if (parm == error_mark_node)
4498                 continue;
4499
4500               if (TREE_PURPOSE (parm))
4501                 seen_def_arg_p = 1;
4502               else if (seen_def_arg_p
4503                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4504                 {
4505                   error ("no default argument for %qD", TREE_VALUE (parm));
4506                   /* For better subsequent error-recovery, we indicate that
4507                      there should have been a default argument.  */
4508                   TREE_PURPOSE (parm) = error_mark_node;
4509                   no_errors = false;
4510                 }
4511               else if (is_primary
4512                        && !is_partial
4513                        && !is_friend_decl
4514                        /* Don't complain about an enclosing partial
4515                           specialization.  */
4516                        && parm_level == parms
4517                        && TREE_CODE (decl) == TYPE_DECL
4518                        && i < ntparms - 1
4519                        && template_parameter_pack_p (TREE_VALUE (parm)))
4520                 {
4521                   /* A primary class template can only have one
4522                      parameter pack, at the end of the template
4523                      parameter list.  */
4524
4525                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4526                     error ("parameter pack %qE must be at the end of the"
4527                            " template parameter list", TREE_VALUE (parm));
4528                   else
4529                     error ("parameter pack %qT must be at the end of the"
4530                            " template parameter list", 
4531                            TREE_TYPE (TREE_VALUE (parm)));
4532
4533                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4534                     = error_mark_node;
4535                   no_errors = false;
4536                 }
4537             }
4538         }
4539     }
4540
4541   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4542       || is_partial 
4543       || !is_primary
4544       || is_friend_decl)
4545     /* For an ordinary class template, default template arguments are
4546        allowed at the innermost level, e.g.:
4547          template <class T = int>
4548          struct S {};
4549        but, in a partial specialization, they're not allowed even
4550        there, as we have in [temp.class.spec]:
4551
4552          The template parameter list of a specialization shall not
4553          contain default template argument values.
4554
4555        So, for a partial specialization, or for a function template
4556        (in C++98/C++03), we look at all of them.  */
4557     ;
4558   else
4559     /* But, for a primary class template that is not a partial
4560        specialization we look at all template parameters except the
4561        innermost ones.  */
4562     parms = TREE_CHAIN (parms);
4563
4564   /* Figure out what error message to issue.  */
4565   if (is_friend_decl == 2)
4566     msg = G_("default template arguments may not be used in function template "
4567              "friend re-declaration");
4568   else if (is_friend_decl)
4569     msg = G_("default template arguments may not be used in function template "
4570              "friend declarations");
4571   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4572     msg = G_("default template arguments may not be used in function templates "
4573              "without -std=c++0x or -std=gnu++0x");
4574   else if (is_partial)
4575     msg = G_("default template arguments may not be used in "
4576              "partial specializations");
4577   else
4578     msg = G_("default argument for template parameter for class enclosing %qD");
4579
4580   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4581     /* If we're inside a class definition, there's no need to
4582        examine the parameters to the class itself.  On the one
4583        hand, they will be checked when the class is defined, and,
4584        on the other, default arguments are valid in things like:
4585          template <class T = double>
4586          struct S { template <class U> void f(U); };
4587        Here the default argument for `S' has no bearing on the
4588        declaration of `f'.  */
4589     last_level_to_check = template_class_depth (current_class_type) + 1;
4590   else
4591     /* Check everything.  */
4592     last_level_to_check = 0;
4593
4594   for (parm_level = parms;
4595        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4596        parm_level = TREE_CHAIN (parm_level))
4597     {
4598       tree inner_parms = TREE_VALUE (parm_level);
4599       int i;
4600       int ntparms;
4601
4602       ntparms = TREE_VEC_LENGTH (inner_parms);
4603       for (i = 0; i < ntparms; ++i)
4604         {
4605           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4606             continue;
4607
4608           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4609             {
4610               if (msg)
4611                 {
4612                   no_errors = false;
4613                   if (is_friend_decl == 2)
4614                     return no_errors;
4615
4616                   error (msg, decl);
4617                   msg = 0;
4618                 }
4619
4620               /* Clear out the default argument so that we are not
4621                  confused later.  */
4622               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4623             }
4624         }
4625
4626       /* At this point, if we're still interested in issuing messages,
4627          they must apply to classes surrounding the object declared.  */
4628       if (msg)
4629         msg = G_("default argument for template parameter for class "
4630                  "enclosing %qD");
4631     }
4632
4633   return no_errors;
4634 }
4635
4636 /* Worker for push_template_decl_real, called via
4637    for_each_template_parm.  DATA is really an int, indicating the
4638    level of the parameters we are interested in.  If T is a template
4639    parameter of that level, return nonzero.  */
4640
4641 static int
4642 template_parm_this_level_p (tree t, void* data)
4643 {
4644   int this_level = *(int *)data;
4645   int level;
4646
4647   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4648     level = TEMPLATE_PARM_LEVEL (t);
4649   else
4650     level = TEMPLATE_TYPE_LEVEL (t);
4651   return level == this_level;
4652 }
4653
4654 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4655    parameters given by current_template_args, or reuses a
4656    previously existing one, if appropriate.  Returns the DECL, or an
4657    equivalent one, if it is replaced via a call to duplicate_decls.
4658
4659    If IS_FRIEND is true, DECL is a friend declaration.  */
4660
4661 tree
4662 push_template_decl_real (tree decl, bool is_friend)
4663 {
4664   tree tmpl;
4665   tree args;
4666   tree info;
4667   tree ctx;
4668   int primary;
4669   int is_partial;
4670   int new_template_p = 0;
4671   /* True if the template is a member template, in the sense of
4672      [temp.mem].  */
4673   bool member_template_p = false;
4674
4675   if (decl == error_mark_node || !current_template_parms)
4676     return error_mark_node;
4677
4678   /* See if this is a partial specialization.  */
4679   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4680                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4681                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4682
4683   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4684     is_friend = true;
4685
4686   if (is_friend)
4687     /* For a friend, we want the context of the friend function, not
4688        the type of which it is a friend.  */
4689     ctx = CP_DECL_CONTEXT (decl);
4690   else if (CP_DECL_CONTEXT (decl)
4691            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4692     /* In the case of a virtual function, we want the class in which
4693        it is defined.  */
4694     ctx = CP_DECL_CONTEXT (decl);
4695   else
4696     /* Otherwise, if we're currently defining some class, the DECL
4697        is assumed to be a member of the class.  */
4698     ctx = current_scope ();
4699
4700   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4701     ctx = NULL_TREE;
4702
4703   if (!DECL_CONTEXT (decl))
4704     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4705
4706   /* See if this is a primary template.  */
4707   if (is_friend && ctx)
4708     /* A friend template that specifies a class context, i.e.
4709          template <typename T> friend void A<T>::f();
4710        is not primary.  */
4711     primary = 0;
4712   else
4713     primary = template_parm_scope_p ();
4714
4715   if (primary)
4716     {
4717       if (DECL_CLASS_SCOPE_P (decl))
4718         member_template_p = true;
4719       if (TREE_CODE (decl) == TYPE_DECL
4720           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4721         {
4722           error ("template class without a name");
4723           return error_mark_node;
4724         }
4725       else if (TREE_CODE (decl) == FUNCTION_DECL)
4726         {
4727           if (DECL_DESTRUCTOR_P (decl))
4728             {
4729               /* [temp.mem]
4730
4731                  A destructor shall not be a member template.  */
4732               error ("destructor %qD declared as member template", decl);
4733               return error_mark_node;
4734             }
4735           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4736               && (!prototype_p (TREE_TYPE (decl))
4737                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4738                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4739                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4740                       == void_list_node)))
4741             {
4742               /* [basic.stc.dynamic.allocation]
4743
4744                  An allocation function can be a function
4745                  template. ... Template allocation functions shall
4746                  have two or more parameters.  */
4747               error ("invalid template declaration of %qD", decl);
4748               return error_mark_node;
4749             }
4750         }
4751       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4752                && CLASS_TYPE_P (TREE_TYPE (decl)))
4753         /* OK */;
4754       else
4755         {
4756           error ("template declaration of %q#D", decl);
4757           return error_mark_node;
4758         }
4759     }
4760
4761   /* Check to see that the rules regarding the use of default
4762      arguments are not being violated.  */
4763   check_default_tmpl_args (decl, current_template_parms,
4764                            primary, is_partial, /*is_friend_decl=*/0);
4765
4766   /* Ensure that there are no parameter packs in the type of this
4767      declaration that have not been expanded.  */
4768   if (TREE_CODE (decl) == FUNCTION_DECL)
4769     {
4770       /* Check each of the arguments individually to see if there are
4771          any bare parameter packs.  */
4772       tree type = TREE_TYPE (decl);
4773       tree arg = DECL_ARGUMENTS (decl);
4774       tree argtype = TYPE_ARG_TYPES (type);
4775
4776       while (arg && argtype)
4777         {
4778           if (!FUNCTION_PARAMETER_PACK_P (arg)
4779               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4780             {
4781             /* This is a PARM_DECL that contains unexpanded parameter
4782                packs. We have already complained about this in the
4783                check_for_bare_parameter_packs call, so just replace
4784                these types with ERROR_MARK_NODE.  */
4785               TREE_TYPE (arg) = error_mark_node;
4786               TREE_VALUE (argtype) = error_mark_node;
4787             }
4788
4789           arg = DECL_CHAIN (arg);
4790           argtype = TREE_CHAIN (argtype);
4791         }
4792
4793       /* Check for bare parameter packs in the return type and the
4794          exception specifiers.  */
4795       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4796         /* Errors were already issued, set return type to int
4797            as the frontend doesn't expect error_mark_node as
4798            the return type.  */
4799         TREE_TYPE (type) = integer_type_node;
4800       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4801         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4802     }
4803   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4804     {
4805       TREE_TYPE (decl) = error_mark_node;
4806       return error_mark_node;
4807     }
4808
4809   if (is_partial)
4810     return process_partial_specialization (decl);
4811
4812   args = current_template_args ();
4813
4814   if (!ctx
4815       || TREE_CODE (ctx) == FUNCTION_DECL
4816       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4817       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4818     {
4819       if (DECL_LANG_SPECIFIC (decl)
4820           && DECL_TEMPLATE_INFO (decl)
4821           && DECL_TI_TEMPLATE (decl))
4822         tmpl = DECL_TI_TEMPLATE (decl);
4823       /* If DECL is a TYPE_DECL for a class-template, then there won't
4824          be DECL_LANG_SPECIFIC.  The information equivalent to
4825          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4826       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4827                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4828                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4829         {
4830           /* Since a template declaration already existed for this
4831              class-type, we must be redeclaring it here.  Make sure
4832              that the redeclaration is valid.  */
4833           redeclare_class_template (TREE_TYPE (decl),
4834                                     current_template_parms);
4835           /* We don't need to create a new TEMPLATE_DECL; just use the
4836              one we already had.  */
4837           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4838         }
4839       else
4840         {
4841           tmpl = build_template_decl (decl, current_template_parms,
4842                                       member_template_p);
4843           new_template_p = 1;
4844
4845           if (DECL_LANG_SPECIFIC (decl)
4846               && DECL_TEMPLATE_SPECIALIZATION (decl))
4847             {
4848               /* A specialization of a member template of a template
4849                  class.  */
4850               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4851               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4852               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4853             }
4854         }
4855     }
4856   else
4857     {
4858       tree a, t, current, parms;
4859       int i;
4860       tree tinfo = get_template_info (decl);
4861
4862       if (!tinfo)
4863         {
4864           error ("template definition of non-template %q#D", decl);
4865           return error_mark_node;
4866         }
4867
4868       tmpl = TI_TEMPLATE (tinfo);
4869
4870       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4871           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4872           && DECL_TEMPLATE_SPECIALIZATION (decl)
4873           && DECL_MEMBER_TEMPLATE_P (tmpl))
4874         {
4875           tree new_tmpl;
4876
4877           /* The declaration is a specialization of a member
4878              template, declared outside the class.  Therefore, the
4879              innermost template arguments will be NULL, so we
4880              replace them with the arguments determined by the
4881              earlier call to check_explicit_specialization.  */
4882           args = DECL_TI_ARGS (decl);
4883
4884           new_tmpl
4885             = build_template_decl (decl, current_template_parms,
4886                                    member_template_p);
4887           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4888           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4889           DECL_TI_TEMPLATE (decl) = new_tmpl;
4890           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4891           DECL_TEMPLATE_INFO (new_tmpl)
4892             = build_template_info (tmpl, args);
4893
4894           register_specialization (new_tmpl,
4895                                    most_general_template (tmpl),
4896                                    args,
4897                                    is_friend, 0);
4898           return decl;
4899         }
4900
4901       /* Make sure the template headers we got make sense.  */
4902
4903       parms = DECL_TEMPLATE_PARMS (tmpl);
4904       i = TMPL_PARMS_DEPTH (parms);
4905       if (TMPL_ARGS_DEPTH (args) != i)
4906         {
4907           error ("expected %d levels of template parms for %q#D, got %d",
4908                  i, decl, TMPL_ARGS_DEPTH (args));
4909         }
4910       else
4911         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4912           {
4913             a = TMPL_ARGS_LEVEL (args, i);
4914             t = INNERMOST_TEMPLATE_PARMS (parms);
4915
4916             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4917               {
4918                 if (current == decl)
4919                   error ("got %d template parameters for %q#D",
4920                          TREE_VEC_LENGTH (a), decl);
4921                 else
4922                   error ("got %d template parameters for %q#T",
4923                          TREE_VEC_LENGTH (a), current);
4924                 error ("  but %d required", TREE_VEC_LENGTH (t));
4925                 return error_mark_node;
4926               }
4927
4928             if (current == decl)
4929               current = ctx;
4930             else if (current == NULL_TREE)
4931               /* Can happen in erroneous input.  */
4932               break;
4933             else
4934               current = (TYPE_P (current)
4935                          ? TYPE_CONTEXT (current)
4936                          : DECL_CONTEXT (current));
4937           }
4938
4939       /* Check that the parms are used in the appropriate qualifying scopes
4940          in the declarator.  */
4941       if (!comp_template_args
4942           (TI_ARGS (tinfo),
4943            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4944         {
4945           error ("\
4946 template arguments to %qD do not match original template %qD",
4947                  decl, DECL_TEMPLATE_RESULT (tmpl));
4948           if (!uses_template_parms (TI_ARGS (tinfo)))
4949             inform (input_location, "use template<> for an explicit specialization");
4950           /* Avoid crash in import_export_decl.  */
4951           DECL_INTERFACE_KNOWN (decl) = 1;
4952           return error_mark_node;
4953         }
4954     }
4955
4956   DECL_TEMPLATE_RESULT (tmpl) = decl;
4957   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4958
4959   /* Push template declarations for global functions and types.  Note
4960      that we do not try to push a global template friend declared in a
4961      template class; such a thing may well depend on the template
4962      parameters of the class.  */
4963   if (new_template_p && !ctx
4964       && !(is_friend && template_class_depth (current_class_type) > 0))
4965     {
4966       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4967       if (tmpl == error_mark_node)
4968         return error_mark_node;
4969
4970       /* Hide template friend classes that haven't been declared yet.  */
4971       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4972         {
4973           DECL_ANTICIPATED (tmpl) = 1;
4974           DECL_FRIEND_P (tmpl) = 1;
4975         }
4976     }
4977
4978   if (primary)
4979     {
4980       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4981       int i;
4982
4983       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4984       if (DECL_CONV_FN_P (tmpl))
4985         {
4986           int depth = TMPL_PARMS_DEPTH (parms);
4987
4988           /* It is a conversion operator. See if the type converted to
4989              depends on innermost template operands.  */
4990
4991           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4992                                          depth))
4993             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4994         }
4995
4996       /* Give template template parms a DECL_CONTEXT of the template
4997          for which they are a parameter.  */
4998       parms = INNERMOST_TEMPLATE_PARMS (parms);
4999       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5000         {
5001           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5002           if (TREE_CODE (parm) == TEMPLATE_DECL)
5003             DECL_CONTEXT (parm) = tmpl;
5004         }
5005     }
5006
5007   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5008      back to its most general template.  If TMPL is a specialization,
5009      ARGS may only have the innermost set of arguments.  Add the missing
5010      argument levels if necessary.  */
5011   if (DECL_TEMPLATE_INFO (tmpl))
5012     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5013
5014   info = build_template_info (tmpl, args);
5015
5016   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5017     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5018   else if (DECL_LANG_SPECIFIC (decl))
5019     DECL_TEMPLATE_INFO (decl) = info;
5020
5021   return DECL_TEMPLATE_RESULT (tmpl);
5022 }
5023
5024 tree
5025 push_template_decl (tree decl)
5026 {
5027   return push_template_decl_real (decl, false);
5028 }
5029
5030 /* Called when a class template TYPE is redeclared with the indicated
5031    template PARMS, e.g.:
5032
5033      template <class T> struct S;
5034      template <class T> struct S {};  */
5035
5036 bool
5037 redeclare_class_template (tree type, tree parms)
5038 {
5039   tree tmpl;
5040   tree tmpl_parms;
5041   int i;
5042
5043   if (!TYPE_TEMPLATE_INFO (type))
5044     {
5045       error ("%qT is not a template type", type);
5046       return false;
5047     }
5048
5049   tmpl = TYPE_TI_TEMPLATE (type);
5050   if (!PRIMARY_TEMPLATE_P (tmpl))
5051     /* The type is nested in some template class.  Nothing to worry
5052        about here; there are no new template parameters for the nested
5053        type.  */
5054     return true;
5055
5056   if (!parms)
5057     {
5058       error ("template specifiers not specified in declaration of %qD",
5059              tmpl);
5060       return false;
5061     }
5062
5063   parms = INNERMOST_TEMPLATE_PARMS (parms);
5064   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5065
5066   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5067     {
5068       error_n (input_location, TREE_VEC_LENGTH (parms),
5069                "redeclared with %d template parameter",
5070                "redeclared with %d template parameters",
5071                TREE_VEC_LENGTH (parms));
5072       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5073                 "previous declaration %q+D used %d template parameter",
5074                 "previous declaration %q+D used %d template parameters",
5075                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5076       return false;
5077     }
5078
5079   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5080     {
5081       tree tmpl_parm;
5082       tree parm;
5083       tree tmpl_default;
5084       tree parm_default;
5085
5086       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5087           || TREE_VEC_ELT (parms, i) == error_mark_node)
5088         continue;
5089
5090       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5091       if (tmpl_parm == error_mark_node)
5092         return false;
5093
5094       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5095       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5096       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5097
5098       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5099          TEMPLATE_DECL.  */
5100       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5101           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5102               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5103           || (TREE_CODE (tmpl_parm) != PARM_DECL
5104               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5105                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5106           || (TREE_CODE (tmpl_parm) == PARM_DECL
5107               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5108                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5109         {
5110           error ("template parameter %q+#D", tmpl_parm);
5111           error ("redeclared here as %q#D", parm);
5112           return false;
5113         }
5114
5115       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5116         {
5117           /* We have in [temp.param]:
5118
5119              A template-parameter may not be given default arguments
5120              by two different declarations in the same scope.  */
5121           error_at (input_location, "redefinition of default argument for %q#D", parm);
5122           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5123                   "original definition appeared here");
5124           return false;
5125         }
5126
5127       if (parm_default != NULL_TREE)
5128         /* Update the previous template parameters (which are the ones
5129            that will really count) with the new default value.  */
5130         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5131       else if (tmpl_default != NULL_TREE)
5132         /* Update the new parameters, too; they'll be used as the
5133            parameters for any members.  */
5134         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5135     }
5136
5137     return true;
5138 }
5139
5140 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5141    (possibly simplified) expression.  */
5142
5143 static tree
5144 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5145 {
5146   if (expr == NULL_TREE)
5147     return NULL_TREE;
5148
5149   /* If we're in a template, but EXPR isn't value dependent, simplify
5150      it.  We're supposed to treat:
5151
5152        template <typename T> void f(T[1 + 1]);
5153        template <typename T> void f(T[2]);
5154
5155      as two declarations of the same function, for example.  */
5156   if (processing_template_decl
5157       && !type_dependent_expression_p (expr)
5158       && potential_constant_expression (expr)
5159       && !value_dependent_expression_p (expr))
5160     {
5161       HOST_WIDE_INT saved_processing_template_decl;
5162
5163       saved_processing_template_decl = processing_template_decl;
5164       processing_template_decl = 0;
5165       expr = tsubst_copy_and_build (expr,
5166                                     /*args=*/NULL_TREE,
5167                                     complain,
5168                                     /*in_decl=*/NULL_TREE,
5169                                     /*function_p=*/false,
5170                                     /*integral_constant_expression_p=*/true);
5171       processing_template_decl = saved_processing_template_decl;
5172     }
5173   return expr;
5174 }
5175
5176 tree
5177 fold_non_dependent_expr (tree expr)
5178 {
5179   return fold_non_dependent_expr_sfinae (expr, tf_error);
5180 }
5181
5182 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5183    must be a function or a pointer-to-function type, as specified
5184    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5185    and check that the resulting function has external linkage.  */
5186
5187 static tree
5188 convert_nontype_argument_function (tree type, tree expr)
5189 {
5190   tree fns = expr;
5191   tree fn, fn_no_ptr;
5192
5193   fn = instantiate_type (type, fns, tf_none);
5194   if (fn == error_mark_node)
5195     return error_mark_node;
5196
5197   fn_no_ptr = fn;
5198   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5199     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5200   if (TREE_CODE (fn_no_ptr) == BASELINK)
5201     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5202  
5203   /* [temp.arg.nontype]/1
5204
5205      A template-argument for a non-type, non-template template-parameter
5206      shall be one of:
5207      [...]
5208      -- the address of an object or function with external linkage.  */
5209   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5210     {
5211       error ("%qE is not a valid template argument for type %qT "
5212              "because function %qD has not external linkage",
5213              expr, type, fn_no_ptr);
5214       return NULL_TREE;
5215     }
5216
5217   return fn;
5218 }
5219
5220 /* Subroutine of convert_nontype_argument.
5221    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5222    Emit an error otherwise.  */
5223
5224 static bool
5225 check_valid_ptrmem_cst_expr (tree type, tree expr,
5226                              tsubst_flags_t complain)
5227 {
5228   STRIP_NOPS (expr);
5229   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5230     return true;
5231   if (complain & tf_error)
5232     {
5233       error ("%qE is not a valid template argument for type %qT",
5234              expr, type);
5235       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5236     }
5237   return false;
5238 }
5239
5240 /* Returns TRUE iff the address of OP is value-dependent.
5241
5242    14.6.2.4 [temp.dep.temp]:
5243    A non-integral non-type template-argument is dependent if its type is
5244    dependent or it has either of the following forms
5245      qualified-id
5246      & qualified-id
5247    and contains a nested-name-specifier which specifies a class-name that
5248    names a dependent type.
5249
5250    We generalize this to just say that the address of a member of a
5251    dependent class is value-dependent; the above doesn't cover the
5252    address of a static data member named with an unqualified-id.  */
5253
5254 static bool
5255 has_value_dependent_address (tree op)
5256 {
5257   /* We could use get_inner_reference here, but there's no need;
5258      this is only relevant for template non-type arguments, which
5259      can only be expressed as &id-expression.  */
5260   if (DECL_P (op))
5261     {
5262       tree ctx = CP_DECL_CONTEXT (op);
5263       if (TYPE_P (ctx) && dependent_type_p (ctx))
5264         return true;
5265     }
5266
5267   return false;
5268 }
5269
5270 /* Attempt to convert the non-type template parameter EXPR to the
5271    indicated TYPE.  If the conversion is successful, return the
5272    converted value.  If the conversion is unsuccessful, return
5273    NULL_TREE if we issued an error message, or error_mark_node if we
5274    did not.  We issue error messages for out-and-out bad template
5275    parameters, but not simply because the conversion failed, since we
5276    might be just trying to do argument deduction.  Both TYPE and EXPR
5277    must be non-dependent.
5278
5279    The conversion follows the special rules described in
5280    [temp.arg.nontype], and it is much more strict than an implicit
5281    conversion.
5282
5283    This function is called twice for each template argument (see
5284    lookup_template_class for a more accurate description of this
5285    problem). This means that we need to handle expressions which
5286    are not valid in a C++ source, but can be created from the
5287    first call (for instance, casts to perform conversions). These
5288    hacks can go away after we fix the double coercion problem.  */
5289
5290 static tree
5291 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5292 {
5293   tree expr_type;
5294
5295   /* Detect immediately string literals as invalid non-type argument.
5296      This special-case is not needed for correctness (we would easily
5297      catch this later), but only to provide better diagnostic for this
5298      common user mistake. As suggested by DR 100, we do not mention
5299      linkage issues in the diagnostic as this is not the point.  */
5300   /* FIXME we're making this OK.  */
5301   if (TREE_CODE (expr) == STRING_CST)
5302     {
5303       if (complain & tf_error)
5304         error ("%qE is not a valid template argument for type %qT "
5305                "because string literals can never be used in this context",
5306                expr, type);
5307       return NULL_TREE;
5308     }
5309
5310   /* Add the ADDR_EXPR now for the benefit of
5311      value_dependent_expression_p.  */
5312   if (TYPE_PTROBV_P (type)
5313       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5314     expr = decay_conversion (expr);
5315
5316   /* If we are in a template, EXPR may be non-dependent, but still
5317      have a syntactic, rather than semantic, form.  For example, EXPR
5318      might be a SCOPE_REF, rather than the VAR_DECL to which the
5319      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5320      so that access checking can be performed when the template is
5321      instantiated -- but here we need the resolved form so that we can
5322      convert the argument.  */
5323   if (TYPE_REF_OBJ_P (type)
5324       && has_value_dependent_address (expr))
5325     /* If we want the address and it's value-dependent, don't fold.  */;
5326   else if (!type_unknown_p (expr))
5327     expr = fold_non_dependent_expr_sfinae (expr, complain);
5328   if (error_operand_p (expr))
5329     return error_mark_node;
5330   expr_type = TREE_TYPE (expr);
5331   if (TREE_CODE (type) == REFERENCE_TYPE)
5332     expr = mark_lvalue_use (expr);
5333   else
5334     expr = mark_rvalue_use (expr);
5335
5336   /* HACK: Due to double coercion, we can get a
5337      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5338      which is the tree that we built on the first call (see
5339      below when coercing to reference to object or to reference to
5340      function). We just strip everything and get to the arg.
5341      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5342      for examples.  */
5343   if (TREE_CODE (expr) == NOP_EXPR)
5344     {
5345       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5346         {
5347           /* ??? Maybe we could use convert_from_reference here, but we
5348              would need to relax its constraints because the NOP_EXPR
5349              could actually change the type to something more cv-qualified,
5350              and this is not folded by convert_from_reference.  */
5351           tree addr = TREE_OPERAND (expr, 0);
5352           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
5353           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5354           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5355           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5356                       (TREE_TYPE (expr_type),
5357                        TREE_TYPE (TREE_TYPE (addr))));
5358
5359           expr = TREE_OPERAND (addr, 0);
5360           expr_type = TREE_TYPE (expr);
5361         }
5362
5363       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5364          parameter is a pointer to object, through decay and
5365          qualification conversion. Let's strip everything.  */
5366       else if (TYPE_PTROBV_P (type))
5367         {
5368           STRIP_NOPS (expr);
5369           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5370           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5371           /* Skip the ADDR_EXPR only if it is part of the decay for
5372              an array. Otherwise, it is part of the original argument
5373              in the source code.  */
5374           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5375             expr = TREE_OPERAND (expr, 0);
5376           expr_type = TREE_TYPE (expr);
5377         }
5378     }
5379
5380   /* [temp.arg.nontype]/5, bullet 1
5381
5382      For a non-type template-parameter of integral or enumeration type,
5383      integral promotions (_conv.prom_) and integral conversions
5384      (_conv.integral_) are applied.  */
5385   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5386     {
5387       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5388       t = maybe_constant_value (t);
5389       if (t != error_mark_node)
5390         expr = t;
5391
5392       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5393         return error_mark_node;
5394
5395       /* Notice that there are constant expressions like '4 % 0' which
5396          do not fold into integer constants.  */
5397       if (TREE_CODE (expr) != INTEGER_CST)
5398         {
5399           if (complain & tf_error)
5400             {
5401               int errs = errorcount, warns = warningcount;
5402               expr = cxx_constant_value (expr);
5403               if (errorcount > errs || warningcount > warns)
5404                 inform (EXPR_LOC_OR_HERE (expr),
5405                         "in template argument for type %qT ", type);
5406               if (expr == error_mark_node)
5407                 return NULL_TREE;
5408               /* else cxx_constant_value complained but gave us
5409                  a real constant, so go ahead.  */
5410               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5411             }
5412           else
5413             return NULL_TREE;
5414         }
5415     }
5416   /* [temp.arg.nontype]/5, bullet 2
5417
5418      For a non-type template-parameter of type pointer to object,
5419      qualification conversions (_conv.qual_) and the array-to-pointer
5420      conversion (_conv.array_) are applied.  */
5421   else if (TYPE_PTROBV_P (type))
5422     {
5423       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5424
5425          A template-argument for a non-type, non-template template-parameter
5426          shall be one of: [...]
5427
5428          -- the name of a non-type template-parameter;
5429          -- the address of an object or function with external linkage, [...]
5430             expressed as "& id-expression" where the & is optional if the name
5431             refers to a function or array, or if the corresponding
5432             template-parameter is a reference.
5433
5434         Here, we do not care about functions, as they are invalid anyway
5435         for a parameter of type pointer-to-object.  */
5436
5437       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5438         /* Non-type template parameters are OK.  */
5439         ;
5440       else if (TREE_CODE (expr) != ADDR_EXPR
5441                && TREE_CODE (expr_type) != ARRAY_TYPE)
5442         {
5443           if (TREE_CODE (expr) == VAR_DECL)
5444             {
5445               error ("%qD is not a valid template argument "
5446                      "because %qD is a variable, not the address of "
5447                      "a variable",
5448                      expr, expr);
5449               return NULL_TREE;
5450             }
5451           /* Other values, like integer constants, might be valid
5452              non-type arguments of some other type.  */
5453           return error_mark_node;
5454         }
5455       else
5456         {
5457           tree decl;
5458
5459           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5460                   ? TREE_OPERAND (expr, 0) : expr);
5461           if (TREE_CODE (decl) != VAR_DECL)
5462             {
5463               error ("%qE is not a valid template argument of type %qT "
5464                      "because %qE is not a variable",
5465                      expr, type, decl);
5466               return NULL_TREE;
5467             }
5468           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5469             {
5470               error ("%qE is not a valid template argument of type %qT "
5471                      "because %qD does not have external linkage",
5472                      expr, type, decl);
5473               return NULL_TREE;
5474             }
5475         }
5476
5477       expr = decay_conversion (expr);
5478       if (expr == error_mark_node)
5479         return error_mark_node;
5480
5481       expr = perform_qualification_conversions (type, expr);
5482       if (expr == error_mark_node)
5483         return error_mark_node;
5484     }
5485   /* [temp.arg.nontype]/5, bullet 3
5486
5487      For a non-type template-parameter of type reference to object, no
5488      conversions apply. The type referred to by the reference may be more
5489      cv-qualified than the (otherwise identical) type of the
5490      template-argument. The template-parameter is bound directly to the
5491      template-argument, which must be an lvalue.  */
5492   else if (TYPE_REF_OBJ_P (type))
5493     {
5494       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5495                                                       expr_type))
5496         return error_mark_node;
5497
5498       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5499         {
5500           error ("%qE is not a valid template argument for type %qT "
5501                  "because of conflicts in cv-qualification", expr, type);
5502           return NULL_TREE;
5503         }
5504
5505       if (!real_lvalue_p (expr))
5506         {
5507           error ("%qE is not a valid template argument for type %qT "
5508                  "because it is not an lvalue", expr, type);
5509           return NULL_TREE;
5510         }
5511
5512       /* [temp.arg.nontype]/1
5513
5514          A template-argument for a non-type, non-template template-parameter
5515          shall be one of: [...]
5516
5517          -- the address of an object or function with external linkage.  */
5518       if (TREE_CODE (expr) == INDIRECT_REF
5519           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5520         {
5521           expr = TREE_OPERAND (expr, 0);
5522           if (DECL_P (expr))
5523             {
5524               error ("%q#D is not a valid template argument for type %qT "
5525                      "because a reference variable does not have a constant "
5526                      "address", expr, type);
5527               return NULL_TREE;
5528             }
5529         }
5530
5531       if (!DECL_P (expr))
5532         {
5533           error ("%qE is not a valid template argument for type %qT "
5534                  "because it is not an object with external linkage",
5535                  expr, type);
5536           return NULL_TREE;
5537         }
5538
5539       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5540         {
5541           error ("%qE is not a valid template argument for type %qT "
5542                  "because object %qD has not external linkage",
5543                  expr, type, expr);
5544           return NULL_TREE;
5545         }
5546
5547       expr = build_nop (type, build_address (expr));
5548     }
5549   /* [temp.arg.nontype]/5, bullet 4
5550
5551      For a non-type template-parameter of type pointer to function, only
5552      the function-to-pointer conversion (_conv.func_) is applied. If the
5553      template-argument represents a set of overloaded functions (or a
5554      pointer to such), the matching function is selected from the set
5555      (_over.over_).  */
5556   else if (TYPE_PTRFN_P (type))
5557     {
5558       /* If the argument is a template-id, we might not have enough
5559          context information to decay the pointer.  */
5560       if (!type_unknown_p (expr_type))
5561         {
5562           expr = decay_conversion (expr);
5563           if (expr == error_mark_node)
5564             return error_mark_node;
5565         }
5566
5567       expr = convert_nontype_argument_function (type, expr);
5568       if (!expr || expr == error_mark_node)
5569         return expr;
5570
5571       if (TREE_CODE (expr) != ADDR_EXPR)
5572         {
5573           error ("%qE is not a valid template argument for type %qT", expr, type);
5574           error ("it must be the address of a function with external linkage");
5575           return NULL_TREE;
5576         }
5577     }
5578   /* [temp.arg.nontype]/5, bullet 5
5579
5580      For a non-type template-parameter of type reference to function, no
5581      conversions apply. If the template-argument represents a set of
5582      overloaded functions, the matching function is selected from the set
5583      (_over.over_).  */
5584   else if (TYPE_REFFN_P (type))
5585     {
5586       if (TREE_CODE (expr) == ADDR_EXPR)
5587         {
5588           error ("%qE is not a valid template argument for type %qT "
5589                  "because it is a pointer", expr, type);
5590           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5591           return NULL_TREE;
5592         }
5593
5594       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5595       if (!expr || expr == error_mark_node)
5596         return expr;
5597
5598       expr = build_nop (type, build_address (expr));
5599     }
5600   /* [temp.arg.nontype]/5, bullet 6
5601
5602      For a non-type template-parameter of type pointer to member function,
5603      no conversions apply. If the template-argument represents a set of
5604      overloaded member functions, the matching member function is selected
5605      from the set (_over.over_).  */
5606   else if (TYPE_PTRMEMFUNC_P (type))
5607     {
5608       expr = instantiate_type (type, expr, tf_none);
5609       if (expr == error_mark_node)
5610         return error_mark_node;
5611
5612       /* [temp.arg.nontype] bullet 1 says the pointer to member
5613          expression must be a pointer-to-member constant.  */
5614       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5615         return error_mark_node;
5616
5617       /* There is no way to disable standard conversions in
5618          resolve_address_of_overloaded_function (called by
5619          instantiate_type). It is possible that the call succeeded by
5620          converting &B::I to &D::I (where B is a base of D), so we need
5621          to reject this conversion here.
5622
5623          Actually, even if there was a way to disable standard conversions,
5624          it would still be better to reject them here so that we can
5625          provide a superior diagnostic.  */
5626       if (!same_type_p (TREE_TYPE (expr), type))
5627         {
5628           error ("%qE is not a valid template argument for type %qT "
5629                  "because it is of type %qT", expr, type,
5630                  TREE_TYPE (expr));
5631           /* If we are just one standard conversion off, explain.  */
5632           if (can_convert (type, TREE_TYPE (expr)))
5633             inform (input_location,
5634                     "standard conversions are not allowed in this context");
5635           return NULL_TREE;
5636         }
5637     }
5638   /* [temp.arg.nontype]/5, bullet 7
5639
5640      For a non-type template-parameter of type pointer to data member,
5641      qualification conversions (_conv.qual_) are applied.  */
5642   else if (TYPE_PTRMEM_P (type))
5643     {
5644       /* [temp.arg.nontype] bullet 1 says the pointer to member
5645          expression must be a pointer-to-member constant.  */
5646       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5647         return error_mark_node;
5648
5649       expr = perform_qualification_conversions (type, expr);
5650       if (expr == error_mark_node)
5651         return expr;
5652     }
5653   /* A template non-type parameter must be one of the above.  */
5654   else
5655     gcc_unreachable ();
5656
5657   /* Sanity check: did we actually convert the argument to the
5658      right type?  */
5659   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5660               (type, TREE_TYPE (expr)));
5661   return expr;
5662 }
5663
5664 /* Subroutine of coerce_template_template_parms, which returns 1 if
5665    PARM_PARM and ARG_PARM match using the rule for the template
5666    parameters of template template parameters. Both PARM and ARG are
5667    template parameters; the rest of the arguments are the same as for
5668    coerce_template_template_parms.
5669  */
5670 static int
5671 coerce_template_template_parm (tree parm,
5672                               tree arg,
5673                               tsubst_flags_t complain,
5674                               tree in_decl,
5675                               tree outer_args)
5676 {
5677   if (arg == NULL_TREE || arg == error_mark_node
5678       || parm == NULL_TREE || parm == error_mark_node)
5679     return 0;
5680   
5681   if (TREE_CODE (arg) != TREE_CODE (parm))
5682     return 0;
5683   
5684   switch (TREE_CODE (parm))
5685     {
5686     case TEMPLATE_DECL:
5687       /* We encounter instantiations of templates like
5688          template <template <template <class> class> class TT>
5689          class C;  */
5690       {
5691         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5692         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5693         
5694         if (!coerce_template_template_parms
5695             (parmparm, argparm, complain, in_decl, outer_args))
5696           return 0;
5697       }
5698       /* Fall through.  */
5699       
5700     case TYPE_DECL:
5701       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5702           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5703         /* Argument is a parameter pack but parameter is not.  */
5704         return 0;
5705       break;
5706       
5707     case PARM_DECL:
5708       /* The tsubst call is used to handle cases such as
5709          
5710            template <int> class C {};
5711            template <class T, template <T> class TT> class D {};
5712            D<int, C> d;
5713
5714          i.e. the parameter list of TT depends on earlier parameters.  */
5715       if (!uses_template_parms (TREE_TYPE (arg))
5716           && !same_type_p
5717                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5718                  TREE_TYPE (arg)))
5719         return 0;
5720       
5721       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5722           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5723         /* Argument is a parameter pack but parameter is not.  */
5724         return 0;
5725       
5726       break;
5727
5728     default:
5729       gcc_unreachable ();
5730     }
5731
5732   return 1;
5733 }
5734
5735
5736 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5737    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5738    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5739    or PARM_DECL.
5740
5741    Consider the example:
5742      template <class T> class A;
5743      template<template <class U> class TT> class B;
5744
5745    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5746    the parameters to A, and OUTER_ARGS contains A.  */
5747
5748 static int
5749 coerce_template_template_parms (tree parm_parms,
5750                                 tree arg_parms,
5751                                 tsubst_flags_t complain,
5752                                 tree in_decl,
5753                                 tree outer_args)
5754 {
5755   int nparms, nargs, i;
5756   tree parm, arg;
5757   int variadic_p = 0;
5758
5759   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5760   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5761
5762   nparms = TREE_VEC_LENGTH (parm_parms);
5763   nargs = TREE_VEC_LENGTH (arg_parms);
5764
5765   /* Determine whether we have a parameter pack at the end of the
5766      template template parameter's template parameter list.  */
5767   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5768     {
5769       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5770       
5771       if (parm == error_mark_node)
5772         return 0;
5773
5774       switch (TREE_CODE (parm))
5775         {
5776         case TEMPLATE_DECL:
5777         case TYPE_DECL:
5778           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5779             variadic_p = 1;
5780           break;
5781           
5782         case PARM_DECL:
5783           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5784             variadic_p = 1;
5785           break;
5786           
5787         default:
5788           gcc_unreachable ();
5789         }
5790     }
5791  
5792   if (nargs != nparms
5793       && !(variadic_p && nargs >= nparms - 1))
5794     return 0;
5795
5796   /* Check all of the template parameters except the parameter pack at
5797      the end (if any).  */
5798   for (i = 0; i < nparms - variadic_p; ++i)
5799     {
5800       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5801           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5802         continue;
5803
5804       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5805       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5806
5807       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5808                                           outer_args))
5809         return 0;
5810
5811     }
5812
5813   if (variadic_p)
5814     {
5815       /* Check each of the template parameters in the template
5816          argument against the template parameter pack at the end of
5817          the template template parameter.  */
5818       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5819         return 0;
5820
5821       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5822
5823       for (; i < nargs; ++i)
5824         {
5825           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5826             continue;
5827  
5828           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5829  
5830           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5831                                               outer_args))
5832             return 0;
5833         }
5834     }
5835
5836   return 1;
5837 }
5838
5839 /* Verifies that the deduced template arguments (in TARGS) for the
5840    template template parameters (in TPARMS) represent valid bindings,
5841    by comparing the template parameter list of each template argument
5842    to the template parameter list of its corresponding template
5843    template parameter, in accordance with DR150. This
5844    routine can only be called after all template arguments have been
5845    deduced. It will return TRUE if all of the template template
5846    parameter bindings are okay, FALSE otherwise.  */
5847 bool 
5848 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5849 {
5850   int i, ntparms = TREE_VEC_LENGTH (tparms);
5851   bool ret = true;
5852
5853   /* We're dealing with template parms in this process.  */
5854   ++processing_template_decl;
5855
5856   targs = INNERMOST_TEMPLATE_ARGS (targs);
5857
5858   for (i = 0; i < ntparms; ++i)
5859     {
5860       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5861       tree targ = TREE_VEC_ELT (targs, i);
5862
5863       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5864         {
5865           tree packed_args = NULL_TREE;
5866           int idx, len = 1;
5867
5868           if (ARGUMENT_PACK_P (targ))
5869             {
5870               /* Look inside the argument pack.  */
5871               packed_args = ARGUMENT_PACK_ARGS (targ);
5872               len = TREE_VEC_LENGTH (packed_args);
5873             }
5874
5875           for (idx = 0; idx < len; ++idx)
5876             {
5877               tree targ_parms = NULL_TREE;
5878
5879               if (packed_args)
5880                 /* Extract the next argument from the argument
5881                    pack.  */
5882                 targ = TREE_VEC_ELT (packed_args, idx);
5883
5884               if (PACK_EXPANSION_P (targ))
5885                 /* Look at the pattern of the pack expansion.  */
5886                 targ = PACK_EXPANSION_PATTERN (targ);
5887
5888               /* Extract the template parameters from the template
5889                  argument.  */
5890               if (TREE_CODE (targ) == TEMPLATE_DECL)
5891                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5892               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5893                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5894
5895               /* Verify that we can coerce the template template
5896                  parameters from the template argument to the template
5897                  parameter.  This requires an exact match.  */
5898               if (targ_parms
5899                   && !coerce_template_template_parms
5900                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5901                         targ_parms,
5902                         tf_none,
5903                         tparm,
5904                         targs))
5905                 {
5906                   ret = false;
5907                   goto out;
5908                 }
5909             }
5910         }
5911     }
5912
5913  out:
5914
5915   --processing_template_decl;
5916   return ret;
5917 }
5918
5919 /* Since type attributes aren't mangled, we need to strip them from
5920    template type arguments.  */
5921
5922 static tree
5923 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
5924 {
5925   tree mv;
5926   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
5927     return arg;
5928   mv = TYPE_MAIN_VARIANT (arg);
5929   arg = strip_typedefs (arg);
5930   if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
5931       || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
5932     {
5933       if (complain & tf_warning)
5934         warning (0, "ignoring attributes on template argument %qT", arg);
5935       arg = build_aligned_type (arg, TYPE_ALIGN (mv));
5936       arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
5937     }
5938   return arg;
5939 }
5940
5941 /* Convert the indicated template ARG as necessary to match the
5942    indicated template PARM.  Returns the converted ARG, or
5943    error_mark_node if the conversion was unsuccessful.  Error and
5944    warning messages are issued under control of COMPLAIN.  This
5945    conversion is for the Ith parameter in the parameter list.  ARGS is
5946    the full set of template arguments deduced so far.  */
5947
5948 static tree
5949 convert_template_argument (tree parm,
5950                            tree arg,
5951                            tree args,
5952                            tsubst_flags_t complain,
5953                            int i,
5954                            tree in_decl)
5955 {
5956   tree orig_arg;
5957   tree val;
5958   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5959
5960   if (TREE_CODE (arg) == TREE_LIST
5961       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5962     {
5963       /* The template argument was the name of some
5964          member function.  That's usually
5965          invalid, but static members are OK.  In any
5966          case, grab the underlying fields/functions
5967          and issue an error later if required.  */
5968       orig_arg = TREE_VALUE (arg);
5969       TREE_TYPE (arg) = unknown_type_node;
5970     }
5971
5972   orig_arg = arg;
5973
5974   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5975   requires_type = (TREE_CODE (parm) == TYPE_DECL
5976                    || requires_tmpl_type);
5977
5978   /* When determining whether an argument pack expansion is a template,
5979      look at the pattern.  */
5980   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5981     arg = PACK_EXPANSION_PATTERN (arg);
5982
5983   /* Deal with an injected-class-name used as a template template arg.  */
5984   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5985     {
5986       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5987       if (TREE_CODE (t) == TEMPLATE_DECL)
5988         {
5989           if (cxx_dialect >= cxx0x)
5990             /* OK under DR 1004.  */;
5991           else if (complain & tf_warning_or_error)
5992             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5993                      " used as template template argument", TYPE_NAME (arg));
5994           else if (flag_pedantic_errors)
5995             t = arg;
5996
5997           arg = t;
5998         }
5999     }
6000
6001   is_tmpl_type = 
6002     ((TREE_CODE (arg) == TEMPLATE_DECL
6003       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
6004      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6005      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
6006
6007   if (is_tmpl_type
6008       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6009           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
6010     arg = TYPE_STUB_DECL (arg);
6011
6012   is_type = TYPE_P (arg) || is_tmpl_type;
6013
6014   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6015       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6016     {
6017       permerror (input_location, "to refer to a type member of a template parameter, "
6018                  "use %<typename %E%>", orig_arg);
6019
6020       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6021                                      TREE_OPERAND (arg, 1),
6022                                      typename_type,
6023                                      complain & tf_error);
6024       arg = orig_arg;
6025       is_type = 1;
6026     }
6027   if (is_type != requires_type)
6028     {
6029       if (in_decl)
6030         {
6031           if (complain & tf_error)
6032             {
6033               error ("type/value mismatch at argument %d in template "
6034                      "parameter list for %qD",
6035                      i + 1, in_decl);
6036               if (is_type)
6037                 error ("  expected a constant of type %qT, got %qT",
6038                        TREE_TYPE (parm),
6039                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6040               else if (requires_tmpl_type)
6041                 error ("  expected a class template, got %qE", orig_arg);
6042               else
6043                 error ("  expected a type, got %qE", orig_arg);
6044             }
6045         }
6046       return error_mark_node;
6047     }
6048   if (is_tmpl_type ^ requires_tmpl_type)
6049     {
6050       if (in_decl && (complain & tf_error))
6051         {
6052           error ("type/value mismatch at argument %d in template "
6053                  "parameter list for %qD",
6054                  i + 1, in_decl);
6055           if (is_tmpl_type)
6056             error ("  expected a type, got %qT", DECL_NAME (arg));
6057           else
6058             error ("  expected a class template, got %qT", orig_arg);
6059         }
6060       return error_mark_node;
6061     }
6062
6063   if (is_type)
6064     {
6065       if (requires_tmpl_type)
6066         {
6067           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6068             /* The number of argument required is not known yet.
6069                Just accept it for now.  */
6070             val = TREE_TYPE (arg);
6071           else
6072             {
6073               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6074               tree argparm;
6075
6076               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6077
6078               if (coerce_template_template_parms (parmparm, argparm,
6079                                                   complain, in_decl,
6080                                                   args))
6081                 {
6082                   val = arg;
6083
6084                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6085                      TEMPLATE_DECL.  */
6086                   if (val != error_mark_node)
6087                     {
6088                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6089                         val = TREE_TYPE (val);
6090                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6091                         val = make_pack_expansion (val);
6092                     }
6093                 }
6094               else
6095                 {
6096                   if (in_decl && (complain & tf_error))
6097                     {
6098                       error ("type/value mismatch at argument %d in "
6099                              "template parameter list for %qD",
6100                              i + 1, in_decl);
6101                       error ("  expected a template of type %qD, got %qT",
6102                              parm, orig_arg);
6103                     }
6104
6105                   val = error_mark_node;
6106                 }
6107             }
6108         }
6109       else
6110         val = orig_arg;
6111       /* We only form one instance of each template specialization.
6112          Therefore, if we use a non-canonical variant (i.e., a
6113          typedef), any future messages referring to the type will use
6114          the typedef, which is confusing if those future uses do not
6115          themselves also use the typedef.  */
6116       if (TYPE_P (val))
6117         val = canonicalize_type_argument (val, complain);
6118     }
6119   else
6120     {
6121       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6122
6123       if (invalid_nontype_parm_type_p (t, complain))
6124         return error_mark_node;
6125
6126       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6127         {
6128           if (same_type_p (t, TREE_TYPE (orig_arg)))
6129             val = orig_arg;
6130           else
6131             {
6132               /* Not sure if this is reachable, but it doesn't hurt
6133                  to be robust.  */
6134               error ("type mismatch in nontype parameter pack");
6135               val = error_mark_node;
6136             }
6137         }
6138       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6139         /* We used to call digest_init here.  However, digest_init
6140            will report errors, which we don't want when complain
6141            is zero.  More importantly, digest_init will try too
6142            hard to convert things: for example, `0' should not be
6143            converted to pointer type at this point according to
6144            the standard.  Accepting this is not merely an
6145            extension, since deciding whether or not these
6146            conversions can occur is part of determining which
6147            function template to call, or whether a given explicit
6148            argument specification is valid.  */
6149         val = convert_nontype_argument (t, orig_arg, complain);
6150       else
6151         val = orig_arg;
6152
6153       if (val == NULL_TREE)
6154         val = error_mark_node;
6155       else if (val == error_mark_node && (complain & tf_error))
6156         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6157
6158       if (TREE_CODE (val) == SCOPE_REF)
6159         {
6160           /* Strip typedefs from the SCOPE_REF.  */
6161           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
6162           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
6163                                                    complain);
6164           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6165                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6166         }
6167     }
6168
6169   return val;
6170 }
6171
6172 /* Coerces the remaining template arguments in INNER_ARGS (from
6173    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6174    Returns the coerced argument pack. PARM_IDX is the position of this
6175    parameter in the template parameter list. ARGS is the original
6176    template argument list.  */
6177 static tree
6178 coerce_template_parameter_pack (tree parms,
6179                                 int parm_idx,
6180                                 tree args,
6181                                 tree inner_args,
6182                                 int arg_idx,
6183                                 tree new_args,
6184                                 int* lost,
6185                                 tree in_decl,
6186                                 tsubst_flags_t complain)
6187 {
6188   tree parm = TREE_VEC_ELT (parms, parm_idx);
6189   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6190   tree packed_args;
6191   tree argument_pack;
6192   tree packed_types = NULL_TREE;
6193
6194   if (arg_idx > nargs)
6195     arg_idx = nargs;
6196
6197   packed_args = make_tree_vec (nargs - arg_idx);
6198
6199   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6200       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6201     {
6202       /* When the template parameter is a non-type template
6203          parameter pack whose type uses parameter packs, we need
6204          to look at each of the template arguments
6205          separately. Build a vector of the types for these
6206          non-type template parameters in PACKED_TYPES.  */
6207       tree expansion 
6208         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6209       packed_types = tsubst_pack_expansion (expansion, args,
6210                                             complain, in_decl);
6211
6212       if (packed_types == error_mark_node)
6213         return error_mark_node;
6214
6215       /* Check that we have the right number of arguments.  */
6216       if (arg_idx < nargs
6217           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6218           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6219         {
6220           int needed_parms 
6221             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6222           error ("wrong number of template arguments (%d, should be %d)",
6223                  nargs, needed_parms);
6224           return error_mark_node;
6225         }
6226
6227       /* If we aren't able to check the actual arguments now
6228          (because they haven't been expanded yet), we can at least
6229          verify that all of the types used for the non-type
6230          template parameter pack are, in fact, valid for non-type
6231          template parameters.  */
6232       if (arg_idx < nargs 
6233           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6234         {
6235           int j, len = TREE_VEC_LENGTH (packed_types);
6236           for (j = 0; j < len; ++j)
6237             {
6238               tree t = TREE_VEC_ELT (packed_types, j);
6239               if (invalid_nontype_parm_type_p (t, complain))
6240                 return error_mark_node;
6241             }
6242         }
6243     }
6244
6245   /* Convert the remaining arguments, which will be a part of the
6246      parameter pack "parm".  */
6247   for (; arg_idx < nargs; ++arg_idx)
6248     {
6249       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6250       tree actual_parm = TREE_VALUE (parm);
6251
6252       if (packed_types && !PACK_EXPANSION_P (arg))
6253         {
6254           /* When we have a vector of types (corresponding to the
6255              non-type template parameter pack that uses parameter
6256              packs in its type, as mention above), and the
6257              argument is not an expansion (which expands to a
6258              currently unknown number of arguments), clone the
6259              parm and give it the next type in PACKED_TYPES.  */
6260           actual_parm = copy_node (actual_parm);
6261           TREE_TYPE (actual_parm) = 
6262             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6263         }
6264
6265       if (arg != error_mark_node)
6266         arg = convert_template_argument (actual_parm, 
6267                                          arg, new_args, complain, parm_idx,
6268                                          in_decl);
6269       if (arg == error_mark_node)
6270         (*lost)++;
6271       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6272     }
6273
6274   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6275       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6276     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6277   else
6278     {
6279       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6280       TREE_TYPE (argument_pack) 
6281         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6282       TREE_CONSTANT (argument_pack) = 1;
6283     }
6284
6285   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6286 #ifdef ENABLE_CHECKING
6287   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6288                                        TREE_VEC_LENGTH (packed_args));
6289 #endif
6290   return argument_pack;
6291 }
6292
6293 /* Convert all template arguments to their appropriate types, and
6294    return a vector containing the innermost resulting template
6295    arguments.  If any error occurs, return error_mark_node. Error and
6296    warning messages are issued under control of COMPLAIN.
6297
6298    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6299    for arguments not specified in ARGS.  Otherwise, if
6300    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6301    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6302    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6303    ARGS.  */
6304
6305 static tree
6306 coerce_template_parms (tree parms,
6307                        tree args,
6308                        tree in_decl,
6309                        tsubst_flags_t complain,
6310                        bool require_all_args,
6311                        bool use_default_args)
6312 {
6313   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6314   tree inner_args;
6315   tree new_args;
6316   tree new_inner_args;
6317   int saved_unevaluated_operand;
6318   int saved_inhibit_evaluation_warnings;
6319
6320   /* When used as a boolean value, indicates whether this is a
6321      variadic template parameter list. Since it's an int, we can also
6322      subtract it from nparms to get the number of non-variadic
6323      parameters.  */
6324   int variadic_p = 0;
6325
6326   if (args == error_mark_node)
6327     return error_mark_node;
6328
6329   nparms = TREE_VEC_LENGTH (parms);
6330
6331   /* Determine if there are any parameter packs.  */
6332   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6333     {
6334       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6335       if (template_parameter_pack_p (tparm))
6336         ++variadic_p;
6337     }
6338
6339   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6340   /* If there are 0 or 1 parameter packs, we need to expand any argument
6341      packs so that we can deduce a parameter pack from some non-packed args
6342      followed by an argument pack, as in variadic85.C.  If there are more
6343      than that, we need to leave argument packs intact so the arguments are
6344      assigned to the right parameter packs.  This should only happen when
6345      dealing with a nested class inside a partial specialization of a class
6346      template, as in variadic92.C.  */
6347   if (variadic_p <= 1)
6348     inner_args = expand_template_argument_pack (inner_args);
6349
6350   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6351   if ((nargs > nparms && !variadic_p)
6352       || (nargs < nparms - variadic_p
6353           && require_all_args
6354           && (!use_default_args
6355               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6356                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6357     {
6358       if (complain & tf_error)
6359         {
6360           if (variadic_p)
6361             {
6362               --nparms;
6363               error ("wrong number of template arguments "
6364                      "(%d, should be %d or more)", nargs, nparms);
6365             }
6366           else
6367              error ("wrong number of template arguments "
6368                     "(%d, should be %d)", nargs, nparms);
6369
6370           if (in_decl)
6371             error ("provided for %q+D", in_decl);
6372         }
6373
6374       return error_mark_node;
6375     }
6376
6377   /* We need to evaluate the template arguments, even though this
6378      template-id may be nested within a "sizeof".  */
6379   saved_unevaluated_operand = cp_unevaluated_operand;
6380   cp_unevaluated_operand = 0;
6381   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6382   c_inhibit_evaluation_warnings = 0;
6383   new_inner_args = make_tree_vec (nparms);
6384   new_args = add_outermost_template_args (args, new_inner_args);
6385   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6386     {
6387       tree arg;
6388       tree parm;
6389
6390       /* Get the Ith template parameter.  */
6391       parm = TREE_VEC_ELT (parms, parm_idx);
6392  
6393       if (parm == error_mark_node)
6394       {
6395         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6396         continue;
6397       }
6398
6399       /* Calculate the next argument.  */
6400       if (arg_idx < nargs)
6401         arg = TREE_VEC_ELT (inner_args, arg_idx);
6402       else
6403         arg = NULL_TREE;
6404
6405       if (template_parameter_pack_p (TREE_VALUE (parm))
6406           && !(arg && ARGUMENT_PACK_P (arg)))
6407         {
6408           /* All remaining arguments will be placed in the
6409              template parameter pack PARM.  */
6410           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6411                                                 inner_args, arg_idx,
6412                                                 new_args, &lost,
6413                                                 in_decl, complain);
6414
6415           /* Store this argument.  */
6416           if (arg == error_mark_node)
6417             lost++;
6418           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6419
6420           /* We are done with all of the arguments.  */
6421           arg_idx = nargs;
6422           
6423           continue;
6424         }
6425       else if (arg)
6426         {
6427           if (PACK_EXPANSION_P (arg))
6428             {
6429               if (complain & tf_error)
6430                 {
6431                   /* FIXME this restriction was removed by N2555; see
6432                      bug 35722.  */
6433                   /* If ARG is a pack expansion, but PARM is not a
6434                      template parameter pack (if it were, we would have
6435                      handled it above), we're trying to expand into a
6436                      fixed-length argument list.  */
6437                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6438                     sorry ("cannot expand %<%E%> into a fixed-length "
6439                            "argument list", arg);
6440                   else
6441                     sorry ("cannot expand %<%T%> into a fixed-length "
6442                            "argument list", arg);
6443                 }
6444               ++lost;
6445             }
6446         }
6447       else if (require_all_args)
6448         {
6449           /* There must be a default arg in this case.  */
6450           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6451                                      complain, in_decl);
6452           /* The position of the first default template argument,
6453              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6454              Record that.  */
6455           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6456             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6457         }
6458       else
6459         break;
6460
6461       if (arg == error_mark_node)
6462         {
6463           if (complain & tf_error)
6464             error ("template argument %d is invalid", arg_idx + 1);
6465         }
6466       else if (!arg)
6467         /* This only occurs if there was an error in the template
6468            parameter list itself (which we would already have
6469            reported) that we are trying to recover from, e.g., a class
6470            template with a parameter list such as
6471            template<typename..., typename>.  */
6472         ++lost;
6473       else
6474         arg = convert_template_argument (TREE_VALUE (parm),
6475                                          arg, new_args, complain, 
6476                                          parm_idx, in_decl);
6477
6478       if (arg == error_mark_node)
6479         lost++;
6480       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6481     }
6482   cp_unevaluated_operand = saved_unevaluated_operand;
6483   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6484
6485   if (lost)
6486     return error_mark_node;
6487
6488 #ifdef ENABLE_CHECKING
6489   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6490     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6491                                          TREE_VEC_LENGTH (new_inner_args));
6492 #endif
6493
6494   return new_inner_args;
6495 }
6496
6497 /* Returns 1 if template args OT and NT are equivalent.  */
6498
6499 static int
6500 template_args_equal (tree ot, tree nt)
6501 {
6502   if (nt == ot)
6503     return 1;
6504   if (nt == NULL_TREE || ot == NULL_TREE)
6505     return false;
6506
6507   if (TREE_CODE (nt) == TREE_VEC)
6508     /* For member templates */
6509     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6510   else if (PACK_EXPANSION_P (ot))
6511     return PACK_EXPANSION_P (nt) 
6512       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6513                               PACK_EXPANSION_PATTERN (nt));
6514   else if (ARGUMENT_PACK_P (ot))
6515     {
6516       int i, len;
6517       tree opack, npack;
6518
6519       if (!ARGUMENT_PACK_P (nt))
6520         return 0;
6521
6522       opack = ARGUMENT_PACK_ARGS (ot);
6523       npack = ARGUMENT_PACK_ARGS (nt);
6524       len = TREE_VEC_LENGTH (opack);
6525       if (TREE_VEC_LENGTH (npack) != len)
6526         return 0;
6527       for (i = 0; i < len; ++i)
6528         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6529                                   TREE_VEC_ELT (npack, i)))
6530           return 0;
6531       return 1;
6532     }
6533   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6534     {
6535       /* We get here probably because we are in the middle of substituting
6536          into the pattern of a pack expansion. In that case the
6537          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6538          interested in. So we want to use the initial pack argument for
6539          the comparison.  */
6540       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6541       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6542         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6543       return template_args_equal (ot, nt);
6544     }
6545   else if (TYPE_P (nt))
6546     return TYPE_P (ot) && same_type_p (ot, nt);
6547   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6548     return 0;
6549   else
6550     return cp_tree_equal (ot, nt);
6551 }
6552
6553 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6554    of template arguments.  Returns 0 otherwise.  */
6555
6556 int
6557 comp_template_args (tree oldargs, tree newargs)
6558 {
6559   int i;
6560
6561   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6562     return 0;
6563
6564   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6565     {
6566       tree nt = TREE_VEC_ELT (newargs, i);
6567       tree ot = TREE_VEC_ELT (oldargs, i);
6568
6569       if (! template_args_equal (ot, nt))
6570         return 0;
6571     }
6572   return 1;
6573 }
6574
6575 static void
6576 add_pending_template (tree d)
6577 {
6578   tree ti = (TYPE_P (d)
6579              ? CLASSTYPE_TEMPLATE_INFO (d)
6580              : DECL_TEMPLATE_INFO (d));
6581   struct pending_template *pt;
6582   int level;
6583
6584   if (TI_PENDING_TEMPLATE_FLAG (ti))
6585     return;
6586
6587   /* We are called both from instantiate_decl, where we've already had a
6588      tinst_level pushed, and instantiate_template, where we haven't.
6589      Compensate.  */
6590   level = !current_tinst_level || current_tinst_level->decl != d;
6591
6592   if (level)
6593     push_tinst_level (d);
6594
6595   pt = ggc_alloc_pending_template ();
6596   pt->next = NULL;
6597   pt->tinst = current_tinst_level;
6598   if (last_pending_template)
6599     last_pending_template->next = pt;
6600   else
6601     pending_templates = pt;
6602
6603   last_pending_template = pt;
6604
6605   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6606
6607   if (level)
6608     pop_tinst_level ();
6609 }
6610
6611
6612 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6613    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6614    documentation for TEMPLATE_ID_EXPR.  */
6615
6616 tree
6617 lookup_template_function (tree fns, tree arglist)
6618 {
6619   tree type;
6620
6621   if (fns == error_mark_node || arglist == error_mark_node)
6622     return error_mark_node;
6623
6624   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6625
6626   if (!is_overloaded_fn (fns) && TREE_CODE (fns) != IDENTIFIER_NODE)
6627     {
6628       error ("%q#D is not a function template", fns);
6629       return error_mark_node;
6630     }
6631
6632   if (BASELINK_P (fns))
6633     {
6634       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6635                                          unknown_type_node,
6636                                          BASELINK_FUNCTIONS (fns),
6637                                          arglist);
6638       return fns;
6639     }
6640
6641   type = TREE_TYPE (fns);
6642   if (TREE_CODE (fns) == OVERLOAD || !type)
6643     type = unknown_type_node;
6644
6645   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6646 }
6647
6648 /* Within the scope of a template class S<T>, the name S gets bound
6649    (in build_self_reference) to a TYPE_DECL for the class, not a
6650    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6651    or one of its enclosing classes, and that type is a template,
6652    return the associated TEMPLATE_DECL.  Otherwise, the original
6653    DECL is returned.
6654
6655    Also handle the case when DECL is a TREE_LIST of ambiguous
6656    injected-class-names from different bases.  */
6657
6658 tree
6659 maybe_get_template_decl_from_type_decl (tree decl)
6660 {
6661   if (decl == NULL_TREE)
6662     return decl;
6663
6664   /* DR 176: A lookup that finds an injected-class-name (10.2
6665      [class.member.lookup]) can result in an ambiguity in certain cases
6666      (for example, if it is found in more than one base class). If all of
6667      the injected-class-names that are found refer to specializations of
6668      the same class template, and if the name is followed by a
6669      template-argument-list, the reference refers to the class template
6670      itself and not a specialization thereof, and is not ambiguous.  */
6671   if (TREE_CODE (decl) == TREE_LIST)
6672     {
6673       tree t, tmpl = NULL_TREE;
6674       for (t = decl; t; t = TREE_CHAIN (t))
6675         {
6676           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6677           if (!tmpl)
6678             tmpl = elt;
6679           else if (tmpl != elt)
6680             break;
6681         }
6682       if (tmpl && t == NULL_TREE)
6683         return tmpl;
6684       else
6685         return decl;
6686     }
6687
6688   return (decl != NULL_TREE
6689           && DECL_SELF_REFERENCE_P (decl)
6690           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6691     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6692 }
6693
6694 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6695    parameters, find the desired type.
6696
6697    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6698
6699    IN_DECL, if non-NULL, is the template declaration we are trying to
6700    instantiate.
6701
6702    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6703    the class we are looking up.
6704
6705    Issue error and warning messages under control of COMPLAIN.
6706
6707    If the template class is really a local class in a template
6708    function, then the FUNCTION_CONTEXT is the function in which it is
6709    being instantiated.
6710
6711    ??? Note that this function is currently called *twice* for each
6712    template-id: the first time from the parser, while creating the
6713    incomplete type (finish_template_type), and the second type during the
6714    real instantiation (instantiate_template_class). This is surely something
6715    that we want to avoid. It also causes some problems with argument
6716    coercion (see convert_nontype_argument for more information on this).  */
6717
6718 static tree
6719 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
6720                          int entering_scope, tsubst_flags_t complain)
6721 {
6722   tree templ = NULL_TREE, parmlist;
6723   tree t;
6724   spec_entry **slot;
6725   spec_entry *entry;
6726   spec_entry elt;
6727   hashval_t hash;
6728
6729   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6730     {
6731       tree value = innermost_non_namespace_value (d1);
6732       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6733         templ = value;
6734       else
6735         {
6736           if (context)
6737             push_decl_namespace (context);
6738           templ = lookup_name (d1);
6739           templ = maybe_get_template_decl_from_type_decl (templ);
6740           if (context)
6741             pop_decl_namespace ();
6742         }
6743       if (templ)
6744         context = DECL_CONTEXT (templ);
6745     }
6746   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6747     {
6748       tree type = TREE_TYPE (d1);
6749
6750       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6751          an implicit typename for the second A.  Deal with it.  */
6752       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6753         type = TREE_TYPE (type);
6754
6755       if (CLASSTYPE_TEMPLATE_INFO (type))
6756         {
6757           templ = CLASSTYPE_TI_TEMPLATE (type);
6758           d1 = DECL_NAME (templ);
6759         }
6760     }
6761   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6762            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6763     {
6764       templ = TYPE_TI_TEMPLATE (d1);
6765       d1 = DECL_NAME (templ);
6766     }
6767   else if (TREE_CODE (d1) == TEMPLATE_DECL
6768            && DECL_TEMPLATE_RESULT (d1)
6769            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6770     {
6771       templ = d1;
6772       d1 = DECL_NAME (templ);
6773       context = DECL_CONTEXT (templ);
6774     }
6775
6776   /* Issue an error message if we didn't find a template.  */
6777   if (! templ)
6778     {
6779       if (complain & tf_error)
6780         error ("%qT is not a template", d1);
6781       return error_mark_node;
6782     }
6783
6784   if (TREE_CODE (templ) != TEMPLATE_DECL
6785          /* Make sure it's a user visible template, if it was named by
6786             the user.  */
6787       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6788           && !PRIMARY_TEMPLATE_P (templ)))
6789     {
6790       if (complain & tf_error)
6791         {
6792           error ("non-template type %qT used as a template", d1);
6793           if (in_decl)
6794             error ("for template declaration %q+D", in_decl);
6795         }
6796       return error_mark_node;
6797     }
6798
6799   complain &= ~tf_user;
6800
6801   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6802     {
6803       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6804          template arguments */
6805
6806       tree parm;
6807       tree arglist2;
6808       tree outer;
6809
6810       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6811
6812       /* Consider an example where a template template parameter declared as
6813
6814            template <class T, class U = std::allocator<T> > class TT
6815
6816          The template parameter level of T and U are one level larger than
6817          of TT.  To proper process the default argument of U, say when an
6818          instantiation `TT<int>' is seen, we need to build the full
6819          arguments containing {int} as the innermost level.  Outer levels,
6820          available when not appearing as default template argument, can be
6821          obtained from the arguments of the enclosing template.
6822
6823          Suppose that TT is later substituted with std::vector.  The above
6824          instantiation is `TT<int, std::allocator<T> >' with TT at
6825          level 1, and T at level 2, while the template arguments at level 1
6826          becomes {std::vector} and the inner level 2 is {int}.  */
6827
6828       outer = DECL_CONTEXT (templ);
6829       if (outer)
6830         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6831       else if (current_template_parms)
6832         /* This is an argument of the current template, so we haven't set
6833            DECL_CONTEXT yet.  */
6834         outer = current_template_args ();
6835
6836       if (outer)
6837         arglist = add_to_template_args (outer, arglist);
6838
6839       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6840                                         complain,
6841                                         /*require_all_args=*/true,
6842                                         /*use_default_args=*/true);
6843       if (arglist2 == error_mark_node
6844           || (!uses_template_parms (arglist2)
6845               && check_instantiated_args (templ, arglist2, complain)))
6846         return error_mark_node;
6847
6848       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6849       return parm;
6850     }
6851   else
6852     {
6853       tree template_type = TREE_TYPE (templ);
6854       tree gen_tmpl;
6855       tree type_decl;
6856       tree found = NULL_TREE;
6857       int arg_depth;
6858       int parm_depth;
6859       int is_dependent_type;
6860       int use_partial_inst_tmpl = false;
6861
6862       gen_tmpl = most_general_template (templ);
6863       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6864       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6865       arg_depth = TMPL_ARGS_DEPTH (arglist);
6866
6867       if (arg_depth == 1 && parm_depth > 1)
6868         {
6869           /* We've been given an incomplete set of template arguments.
6870              For example, given:
6871
6872                template <class T> struct S1 {
6873                  template <class U> struct S2 {};
6874                  template <class U> struct S2<U*> {};
6875                 };
6876
6877              we will be called with an ARGLIST of `U*', but the
6878              TEMPLATE will be `template <class T> template
6879              <class U> struct S1<T>::S2'.  We must fill in the missing
6880              arguments.  */
6881           arglist
6882             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6883                                            arglist);
6884           arg_depth = TMPL_ARGS_DEPTH (arglist);
6885         }
6886
6887       /* Now we should have enough arguments.  */
6888       gcc_assert (parm_depth == arg_depth);
6889
6890       /* From here on, we're only interested in the most general
6891          template.  */
6892
6893       /* Calculate the BOUND_ARGS.  These will be the args that are
6894          actually tsubst'd into the definition to create the
6895          instantiation.  */
6896       if (parm_depth > 1)
6897         {
6898           /* We have multiple levels of arguments to coerce, at once.  */
6899           int i;
6900           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6901
6902           tree bound_args = make_tree_vec (parm_depth);
6903
6904           for (i = saved_depth,
6905                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6906                i > 0 && t != NULL_TREE;
6907                --i, t = TREE_CHAIN (t))
6908             {
6909               tree a;
6910               if (i == saved_depth)
6911                 a = coerce_template_parms (TREE_VALUE (t),
6912                                            arglist, gen_tmpl,
6913                                            complain,
6914                                            /*require_all_args=*/true,
6915                                            /*use_default_args=*/true);
6916               else
6917                 /* Outer levels should have already been coerced.  */
6918                 a = TMPL_ARGS_LEVEL (arglist, i);
6919
6920               /* Don't process further if one of the levels fails.  */
6921               if (a == error_mark_node)
6922                 {
6923                   /* Restore the ARGLIST to its full size.  */
6924                   TREE_VEC_LENGTH (arglist) = saved_depth;
6925                   return error_mark_node;
6926                 }
6927
6928               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6929
6930               /* We temporarily reduce the length of the ARGLIST so
6931                  that coerce_template_parms will see only the arguments
6932                  corresponding to the template parameters it is
6933                  examining.  */
6934               TREE_VEC_LENGTH (arglist)--;
6935             }
6936
6937           /* Restore the ARGLIST to its full size.  */
6938           TREE_VEC_LENGTH (arglist) = saved_depth;
6939
6940           arglist = bound_args;
6941         }
6942       else
6943         arglist
6944           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6945                                    INNERMOST_TEMPLATE_ARGS (arglist),
6946                                    gen_tmpl,
6947                                    complain,
6948                                    /*require_all_args=*/true,
6949                                    /*use_default_args=*/true);
6950
6951       if (arglist == error_mark_node)
6952         /* We were unable to bind the arguments.  */
6953         return error_mark_node;
6954
6955       /* In the scope of a template class, explicit references to the
6956          template class refer to the type of the template, not any
6957          instantiation of it.  For example, in:
6958
6959            template <class T> class C { void f(C<T>); }
6960
6961          the `C<T>' is just the same as `C'.  Outside of the
6962          class, however, such a reference is an instantiation.  */
6963       if ((entering_scope
6964            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6965            || currently_open_class (template_type))
6966           /* comp_template_args is expensive, check it last.  */
6967           && comp_template_args (TYPE_TI_ARGS (template_type),
6968                                  arglist))
6969         return template_type;
6970
6971       /* If we already have this specialization, return it.  */
6972       elt.tmpl = gen_tmpl;
6973       elt.args = arglist;
6974       hash = hash_specialization (&elt);
6975       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6976                                                   &elt, hash);
6977
6978       if (entry)
6979         return entry->spec;
6980
6981       is_dependent_type = uses_template_parms (arglist);
6982
6983       /* If the deduced arguments are invalid, then the binding
6984          failed.  */
6985       if (!is_dependent_type
6986           && check_instantiated_args (gen_tmpl,
6987                                       INNERMOST_TEMPLATE_ARGS (arglist),
6988                                       complain))
6989         return error_mark_node;
6990
6991       if (!is_dependent_type
6992           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6993           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6994           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6995         {
6996           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6997                                       DECL_NAME (gen_tmpl),
6998                                       /*tag_scope=*/ts_global);
6999           return found;
7000         }
7001
7002       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
7003                         complain, in_decl);
7004       if (!context)
7005         context = global_namespace;
7006
7007       /* Create the type.  */
7008       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
7009         {
7010           if (!is_dependent_type)
7011             {
7012               set_current_access_from_decl (TYPE_NAME (template_type));
7013               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
7014                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
7015                                       arglist, complain, in_decl),
7016                               SCOPED_ENUM_P (template_type), NULL);
7017             }
7018           else
7019             {
7020               /* We don't want to call start_enum for this type, since
7021                  the values for the enumeration constants may involve
7022                  template parameters.  And, no one should be interested
7023                  in the enumeration constants for such a type.  */
7024               t = cxx_make_type (ENUMERAL_TYPE);
7025               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7026             }
7027           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7028           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7029             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7030         }
7031       else
7032         {
7033           t = make_class_type (TREE_CODE (template_type));
7034           CLASSTYPE_DECLARED_CLASS (t)
7035             = CLASSTYPE_DECLARED_CLASS (template_type);
7036           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7037           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7038
7039           /* A local class.  Make sure the decl gets registered properly.  */
7040           if (context == current_function_decl)
7041             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7042
7043           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7044             /* This instantiation is another name for the primary
7045                template type. Set the TYPE_CANONICAL field
7046                appropriately. */
7047             TYPE_CANONICAL (t) = template_type;
7048           else if (any_template_arguments_need_structural_equality_p (arglist))
7049             /* Some of the template arguments require structural
7050                equality testing, so this template class requires
7051                structural equality testing. */
7052             SET_TYPE_STRUCTURAL_EQUALITY (t);
7053         }
7054
7055       /* If we called start_enum or pushtag above, this information
7056          will already be set up.  */
7057       if (!TYPE_NAME (t))
7058         {
7059           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7060
7061           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7062           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7063           DECL_SOURCE_LOCATION (type_decl)
7064             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7065         }
7066       else
7067         type_decl = TYPE_NAME (t);
7068
7069       TREE_PRIVATE (type_decl)
7070         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7071       TREE_PROTECTED (type_decl)
7072         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7073       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7074         {
7075           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7076           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7077         }
7078
7079       /* Let's consider the explicit specialization of a member
7080          of a class template specialization that is implicitely instantiated,
7081          e.g.:
7082              template<class T>
7083              struct S
7084              {
7085                template<class U> struct M {}; //#0
7086              };
7087
7088              template<>
7089              template<>
7090              struct S<int>::M<char> //#1
7091              {
7092                int i;
7093              };
7094         [temp.expl.spec]/4 says this is valid.
7095
7096         In this case, when we write:
7097         S<int>::M<char> m;
7098
7099         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7100         the one of #0.
7101
7102         When we encounter #1, we want to store the partial instantiation
7103         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7104
7105         For all cases other than this "explicit specialization of member of a
7106         class template", we just want to store the most general template into
7107         the CLASSTYPE_TI_TEMPLATE of M.
7108
7109         This case of "explicit specialization of member of a class template"
7110         only happens when:
7111         1/ the enclosing class is an instantiation of, and therefore not
7112         the same as, the context of the most general template, and
7113         2/ we aren't looking at the partial instantiation itself, i.e.
7114         the innermost arguments are not the same as the innermost parms of
7115         the most general template.
7116
7117         So it's only when 1/ and 2/ happens that we want to use the partial
7118         instantiation of the member template in lieu of its most general
7119         template.  */
7120
7121       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7122           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7123           /* the enclosing class must be an instantiation...  */
7124           && CLASS_TYPE_P (context)
7125           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7126         {
7127           tree partial_inst_args;
7128           TREE_VEC_LENGTH (arglist)--;
7129           ++processing_template_decl;
7130           partial_inst_args =
7131             tsubst (INNERMOST_TEMPLATE_ARGS
7132                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7133                     arglist, complain, NULL_TREE);
7134           --processing_template_decl;
7135           TREE_VEC_LENGTH (arglist)++;
7136           use_partial_inst_tmpl =
7137             /*...and we must not be looking at the partial instantiation
7138              itself. */
7139             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7140                                  partial_inst_args);
7141         }
7142
7143       if (!use_partial_inst_tmpl)
7144         /* This case is easy; there are no member templates involved.  */
7145         found = gen_tmpl;
7146       else
7147         {
7148           /* This is a full instantiation of a member template.  Find
7149              the partial instantiation of which this is an instance.  */
7150
7151           /* Temporarily reduce by one the number of levels in the ARGLIST
7152              so as to avoid comparing the last set of arguments.  */
7153           TREE_VEC_LENGTH (arglist)--;
7154           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7155           TREE_VEC_LENGTH (arglist)++;
7156           found = CLASSTYPE_TI_TEMPLATE (found);
7157         }
7158
7159       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7160
7161       elt.spec = t;
7162       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
7163                                                        &elt, hash, INSERT);
7164       *slot = ggc_alloc_spec_entry ();
7165       **slot = elt;
7166
7167       /* Note this use of the partial instantiation so we can check it
7168          later in maybe_process_partial_specialization.  */
7169       DECL_TEMPLATE_INSTANTIATIONS (templ)
7170         = tree_cons (arglist, t,
7171                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7172
7173       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7174         /* Now that the type has been registered on the instantiations
7175            list, we set up the enumerators.  Because the enumeration
7176            constants may involve the enumeration type itself, we make
7177            sure to register the type first, and then create the
7178            constants.  That way, doing tsubst_expr for the enumeration
7179            constants won't result in recursive calls here; we'll find
7180            the instantiation and exit above.  */
7181         tsubst_enum (template_type, t, arglist);
7182
7183       if (is_dependent_type)
7184         /* If the type makes use of template parameters, the
7185            code that generates debugging information will crash.  */
7186         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7187
7188       /* Possibly limit visibility based on template args.  */
7189       TREE_PUBLIC (type_decl) = 1;
7190       determine_visibility (type_decl);
7191
7192       return t;
7193     }
7194 }
7195
7196 /* Wrapper for lookup_template_class_1.  */
7197
7198 tree
7199 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
7200                        int entering_scope, tsubst_flags_t complain)
7201 {
7202   tree ret;
7203   timevar_push (TV_TEMPLATE_INST);
7204   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
7205                                  entering_scope, complain);
7206   timevar_pop (TV_TEMPLATE_INST);
7207   return ret;
7208 }
7209 \f
7210 struct pair_fn_data
7211 {
7212   tree_fn_t fn;
7213   void *data;
7214   /* True when we should also visit template parameters that occur in
7215      non-deduced contexts.  */
7216   bool include_nondeduced_p;
7217   struct pointer_set_t *visited;
7218 };
7219
7220 /* Called from for_each_template_parm via walk_tree.  */
7221
7222 static tree
7223 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7224 {
7225   tree t = *tp;
7226   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7227   tree_fn_t fn = pfd->fn;
7228   void *data = pfd->data;
7229
7230   if (TYPE_P (t)
7231       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7232       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7233                                  pfd->include_nondeduced_p))
7234     return error_mark_node;
7235
7236   switch (TREE_CODE (t))
7237     {
7238     case RECORD_TYPE:
7239       if (TYPE_PTRMEMFUNC_P (t))
7240         break;
7241       /* Fall through.  */
7242
7243     case UNION_TYPE:
7244     case ENUMERAL_TYPE:
7245       if (!TYPE_TEMPLATE_INFO (t))
7246         *walk_subtrees = 0;
7247       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7248                                        fn, data, pfd->visited, 
7249                                        pfd->include_nondeduced_p))
7250         return error_mark_node;
7251       break;
7252
7253     case INTEGER_TYPE:
7254       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7255                                   fn, data, pfd->visited, 
7256                                   pfd->include_nondeduced_p)
7257           || for_each_template_parm (TYPE_MAX_VALUE (t),
7258                                      fn, data, pfd->visited,
7259                                      pfd->include_nondeduced_p))
7260         return error_mark_node;
7261       break;
7262
7263     case METHOD_TYPE:
7264       /* Since we're not going to walk subtrees, we have to do this
7265          explicitly here.  */
7266       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7267                                   pfd->visited, pfd->include_nondeduced_p))
7268         return error_mark_node;
7269       /* Fall through.  */
7270
7271     case FUNCTION_TYPE:
7272       /* Check the return type.  */
7273       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7274                                   pfd->include_nondeduced_p))
7275         return error_mark_node;
7276
7277       /* Check the parameter types.  Since default arguments are not
7278          instantiated until they are needed, the TYPE_ARG_TYPES may
7279          contain expressions that involve template parameters.  But,
7280          no-one should be looking at them yet.  And, once they're
7281          instantiated, they don't contain template parameters, so
7282          there's no point in looking at them then, either.  */
7283       {
7284         tree parm;
7285
7286         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7287           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7288                                       pfd->visited, pfd->include_nondeduced_p))
7289             return error_mark_node;
7290
7291         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7292            want walk_tree walking into them itself.  */
7293         *walk_subtrees = 0;
7294       }
7295       break;
7296
7297     case TYPEOF_TYPE:
7298     case UNDERLYING_TYPE:
7299       if (pfd->include_nondeduced_p
7300           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7301                                      pfd->visited, 
7302                                      pfd->include_nondeduced_p))
7303         return error_mark_node;
7304       break;
7305
7306     case FUNCTION_DECL:
7307     case VAR_DECL:
7308       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7309           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7310                                      pfd->visited, pfd->include_nondeduced_p))
7311         return error_mark_node;
7312       /* Fall through.  */
7313
7314     case PARM_DECL:
7315     case CONST_DECL:
7316       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7317           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7318                                      pfd->visited, pfd->include_nondeduced_p))
7319         return error_mark_node;
7320       if (DECL_CONTEXT (t)
7321           && pfd->include_nondeduced_p
7322           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7323                                      pfd->visited, pfd->include_nondeduced_p))
7324         return error_mark_node;
7325       break;
7326
7327     case BOUND_TEMPLATE_TEMPLATE_PARM:
7328       /* Record template parameters such as `T' inside `TT<T>'.  */
7329       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7330                                   pfd->include_nondeduced_p))
7331         return error_mark_node;
7332       /* Fall through.  */
7333
7334     case TEMPLATE_TEMPLATE_PARM:
7335     case TEMPLATE_TYPE_PARM:
7336     case TEMPLATE_PARM_INDEX:
7337       if (fn && (*fn)(t, data))
7338         return error_mark_node;
7339       else if (!fn)
7340         return error_mark_node;
7341       break;
7342
7343     case TEMPLATE_DECL:
7344       /* A template template parameter is encountered.  */
7345       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7346           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7347                                      pfd->include_nondeduced_p))
7348         return error_mark_node;
7349
7350       /* Already substituted template template parameter */
7351       *walk_subtrees = 0;
7352       break;
7353
7354     case TYPENAME_TYPE:
7355       if (!fn
7356           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7357                                      data, pfd->visited, 
7358                                      pfd->include_nondeduced_p))
7359         return error_mark_node;
7360       break;
7361
7362     case CONSTRUCTOR:
7363       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7364           && pfd->include_nondeduced_p
7365           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7366                                      (TREE_TYPE (t)), fn, data,
7367                                      pfd->visited, pfd->include_nondeduced_p))
7368         return error_mark_node;
7369       break;
7370
7371     case INDIRECT_REF:
7372     case COMPONENT_REF:
7373       /* If there's no type, then this thing must be some expression
7374          involving template parameters.  */
7375       if (!fn && !TREE_TYPE (t))
7376         return error_mark_node;
7377       break;
7378
7379     case MODOP_EXPR:
7380     case CAST_EXPR:
7381     case REINTERPRET_CAST_EXPR:
7382     case CONST_CAST_EXPR:
7383     case STATIC_CAST_EXPR:
7384     case DYNAMIC_CAST_EXPR:
7385     case ARROW_EXPR:
7386     case DOTSTAR_EXPR:
7387     case TYPEID_EXPR:
7388     case PSEUDO_DTOR_EXPR:
7389       if (!fn)
7390         return error_mark_node;
7391       break;
7392
7393     default:
7394       break;
7395     }
7396
7397   /* We didn't find any template parameters we liked.  */
7398   return NULL_TREE;
7399 }
7400
7401 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7402    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7403    call FN with the parameter and the DATA.
7404    If FN returns nonzero, the iteration is terminated, and
7405    for_each_template_parm returns 1.  Otherwise, the iteration
7406    continues.  If FN never returns a nonzero value, the value
7407    returned by for_each_template_parm is 0.  If FN is NULL, it is
7408    considered to be the function which always returns 1.
7409
7410    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7411    parameters that occur in non-deduced contexts.  When false, only
7412    visits those template parameters that can be deduced.  */
7413
7414 static int
7415 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7416                         struct pointer_set_t *visited,
7417                         bool include_nondeduced_p)
7418 {
7419   struct pair_fn_data pfd;
7420   int result;
7421
7422   /* Set up.  */
7423   pfd.fn = fn;
7424   pfd.data = data;
7425   pfd.include_nondeduced_p = include_nondeduced_p;
7426
7427   /* Walk the tree.  (Conceptually, we would like to walk without
7428      duplicates, but for_each_template_parm_r recursively calls
7429      for_each_template_parm, so we would need to reorganize a fair
7430      bit to use walk_tree_without_duplicates, so we keep our own
7431      visited list.)  */
7432   if (visited)
7433     pfd.visited = visited;
7434   else
7435     pfd.visited = pointer_set_create ();
7436   result = cp_walk_tree (&t,
7437                          for_each_template_parm_r,
7438                          &pfd,
7439                          pfd.visited) != NULL_TREE;
7440
7441   /* Clean up.  */
7442   if (!visited)
7443     {
7444       pointer_set_destroy (pfd.visited);
7445       pfd.visited = 0;
7446     }
7447
7448   return result;
7449 }
7450
7451 /* Returns true if T depends on any template parameter.  */
7452
7453 int
7454 uses_template_parms (tree t)
7455 {
7456   bool dependent_p;
7457   int saved_processing_template_decl;
7458
7459   saved_processing_template_decl = processing_template_decl;
7460   if (!saved_processing_template_decl)
7461     processing_template_decl = 1;
7462   if (TYPE_P (t))
7463     dependent_p = dependent_type_p (t);
7464   else if (TREE_CODE (t) == TREE_VEC)
7465     dependent_p = any_dependent_template_arguments_p (t);
7466   else if (TREE_CODE (t) == TREE_LIST)
7467     dependent_p = (uses_template_parms (TREE_VALUE (t))
7468                    || uses_template_parms (TREE_CHAIN (t)));
7469   else if (TREE_CODE (t) == TYPE_DECL)
7470     dependent_p = dependent_type_p (TREE_TYPE (t));
7471   else if (DECL_P (t)
7472            || EXPR_P (t)
7473            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7474            || TREE_CODE (t) == OVERLOAD
7475            || TREE_CODE (t) == BASELINK
7476            || TREE_CODE (t) == IDENTIFIER_NODE
7477            || TREE_CODE (t) == TRAIT_EXPR
7478            || TREE_CODE (t) == CONSTRUCTOR
7479            || CONSTANT_CLASS_P (t))
7480     dependent_p = (type_dependent_expression_p (t)
7481                    || value_dependent_expression_p (t));
7482   else
7483     {
7484       gcc_assert (t == error_mark_node);
7485       dependent_p = false;
7486     }
7487
7488   processing_template_decl = saved_processing_template_decl;
7489
7490   return dependent_p;
7491 }
7492
7493 /* Returns true if T depends on any template parameter with level LEVEL.  */
7494
7495 int
7496 uses_template_parms_level (tree t, int level)
7497 {
7498   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7499                                  /*include_nondeduced_p=*/true);
7500 }
7501
7502 static int tinst_depth;
7503 extern int max_tinst_depth;
7504 #ifdef GATHER_STATISTICS
7505 int depth_reached;
7506 #endif
7507 static int tinst_level_tick;
7508 static int last_template_error_tick;
7509
7510 /* We're starting to instantiate D; record the template instantiation context
7511    for diagnostics and to restore it later.  */
7512
7513 int
7514 push_tinst_level (tree d)
7515 {
7516   struct tinst_level *new_level;
7517
7518   if (tinst_depth >= max_tinst_depth)
7519     {
7520       last_template_error_tick = tinst_level_tick;
7521       if (TREE_CODE (d) == TREE_LIST)
7522         error ("template instantiation depth exceeds maximum of %d (use "
7523                "-ftemplate-depth= to increase the maximum) substituting %qS",
7524                max_tinst_depth, d);
7525       else
7526         error ("template instantiation depth exceeds maximum of %d (use "
7527                "-ftemplate-depth= to increase the maximum) instantiating %qD",
7528                max_tinst_depth, d);
7529
7530       print_instantiation_context ();
7531
7532       return 0;
7533     }
7534
7535   new_level = ggc_alloc_tinst_level ();
7536   new_level->decl = d;
7537   new_level->locus = input_location;
7538   new_level->in_system_header_p = in_system_header;
7539   new_level->next = current_tinst_level;
7540   current_tinst_level = new_level;
7541
7542   ++tinst_depth;
7543 #ifdef GATHER_STATISTICS
7544   if (tinst_depth > depth_reached)
7545     depth_reached = tinst_depth;
7546 #endif
7547
7548   ++tinst_level_tick;
7549   return 1;
7550 }
7551
7552 /* We're done instantiating this template; return to the instantiation
7553    context.  */
7554
7555 void
7556 pop_tinst_level (void)
7557 {
7558   /* Restore the filename and line number stashed away when we started
7559      this instantiation.  */
7560   input_location = current_tinst_level->locus;
7561   current_tinst_level = current_tinst_level->next;
7562   --tinst_depth;
7563   ++tinst_level_tick;
7564 }
7565
7566 /* We're instantiating a deferred template; restore the template
7567    instantiation context in which the instantiation was requested, which
7568    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7569
7570 static tree
7571 reopen_tinst_level (struct tinst_level *level)
7572 {
7573   struct tinst_level *t;
7574
7575   tinst_depth = 0;
7576   for (t = level; t; t = t->next)
7577     ++tinst_depth;
7578
7579   current_tinst_level = level;
7580   pop_tinst_level ();
7581   return level->decl;
7582 }
7583
7584 /* Returns the TINST_LEVEL which gives the original instantiation
7585    context.  */
7586
7587 struct tinst_level *
7588 outermost_tinst_level (void)
7589 {
7590   struct tinst_level *level = current_tinst_level;
7591   if (level)
7592     while (level->next)
7593       level = level->next;
7594   return level;
7595 }
7596
7597 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7598
7599 bool
7600 parameter_of_template_p (tree parm, tree templ)
7601 {
7602   tree parms;
7603   int i;
7604
7605   if (!parm || !templ)
7606     return false;
7607
7608   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7609   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7610
7611   parms = DECL_TEMPLATE_PARMS (templ);
7612   parms = INNERMOST_TEMPLATE_PARMS (parms);
7613
7614   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7615     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7616       return true;
7617
7618   return false;
7619 }
7620
7621 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7622    vector of template arguments, as for tsubst.
7623
7624    Returns an appropriate tsubst'd friend declaration.  */
7625
7626 static tree
7627 tsubst_friend_function (tree decl, tree args)
7628 {
7629   tree new_friend;
7630
7631   if (TREE_CODE (decl) == FUNCTION_DECL
7632       && DECL_TEMPLATE_INSTANTIATION (decl)
7633       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7634     /* This was a friend declared with an explicit template
7635        argument list, e.g.:
7636
7637        friend void f<>(T);
7638
7639        to indicate that f was a template instantiation, not a new
7640        function declaration.  Now, we have to figure out what
7641        instantiation of what template.  */
7642     {
7643       tree template_id, arglist, fns;
7644       tree new_args;
7645       tree tmpl;
7646       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7647
7648       /* Friend functions are looked up in the containing namespace scope.
7649          We must enter that scope, to avoid finding member functions of the
7650          current class with same name.  */
7651       push_nested_namespace (ns);
7652       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7653                          tf_warning_or_error, NULL_TREE,
7654                          /*integral_constant_expression_p=*/false);
7655       pop_nested_namespace (ns);
7656       arglist = tsubst (DECL_TI_ARGS (decl), args,
7657                         tf_warning_or_error, NULL_TREE);
7658       template_id = lookup_template_function (fns, arglist);
7659
7660       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7661       tmpl = determine_specialization (template_id, new_friend,
7662                                        &new_args,
7663                                        /*need_member_template=*/0,
7664                                        TREE_VEC_LENGTH (args),
7665                                        tsk_none);
7666       return instantiate_template (tmpl, new_args, tf_error);
7667     }
7668
7669   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7670
7671   /* The NEW_FRIEND will look like an instantiation, to the
7672      compiler, but is not an instantiation from the point of view of
7673      the language.  For example, we might have had:
7674
7675      template <class T> struct S {
7676        template <class U> friend void f(T, U);
7677      };
7678
7679      Then, in S<int>, template <class U> void f(int, U) is not an
7680      instantiation of anything.  */
7681   if (new_friend == error_mark_node)
7682     return error_mark_node;
7683
7684   DECL_USE_TEMPLATE (new_friend) = 0;
7685   if (TREE_CODE (decl) == TEMPLATE_DECL)
7686     {
7687       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7688       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7689         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7690     }
7691
7692   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7693      is not a template instantiation and should not be mangled like
7694      one.  Therefore, we forget the mangling here; we'll recompute it
7695      later if we need it.  */
7696   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7697     {
7698       SET_DECL_RTL (new_friend, NULL);
7699       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7700     }
7701
7702   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7703     {
7704       tree old_decl;
7705       tree new_friend_template_info;
7706       tree new_friend_result_template_info;
7707       tree ns;
7708       int  new_friend_is_defn;
7709
7710       /* We must save some information from NEW_FRIEND before calling
7711          duplicate decls since that function will free NEW_FRIEND if
7712          possible.  */
7713       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7714       new_friend_is_defn =
7715             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7716                            (template_for_substitution (new_friend)))
7717              != NULL_TREE);
7718       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7719         {
7720           /* This declaration is a `primary' template.  */
7721           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7722
7723           new_friend_result_template_info
7724             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7725         }
7726       else
7727         new_friend_result_template_info = NULL_TREE;
7728
7729       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7730       if (new_friend_is_defn)
7731         DECL_INITIAL (new_friend) = error_mark_node;
7732
7733       /* Inside pushdecl_namespace_level, we will push into the
7734          current namespace. However, the friend function should go
7735          into the namespace of the template.  */
7736       ns = decl_namespace_context (new_friend);
7737       push_nested_namespace (ns);
7738       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7739       pop_nested_namespace (ns);
7740
7741       if (old_decl == error_mark_node)
7742         return error_mark_node;
7743
7744       if (old_decl != new_friend)
7745         {
7746           /* This new friend declaration matched an existing
7747              declaration.  For example, given:
7748
7749                template <class T> void f(T);
7750                template <class U> class C {
7751                  template <class T> friend void f(T) {}
7752                };
7753
7754              the friend declaration actually provides the definition
7755              of `f', once C has been instantiated for some type.  So,
7756              old_decl will be the out-of-class template declaration,
7757              while new_friend is the in-class definition.
7758
7759              But, if `f' was called before this point, the
7760              instantiation of `f' will have DECL_TI_ARGS corresponding
7761              to `T' but not to `U', references to which might appear
7762              in the definition of `f'.  Previously, the most general
7763              template for an instantiation of `f' was the out-of-class
7764              version; now it is the in-class version.  Therefore, we
7765              run through all specialization of `f', adding to their
7766              DECL_TI_ARGS appropriately.  In particular, they need a
7767              new set of outer arguments, corresponding to the
7768              arguments for this class instantiation.
7769
7770              The same situation can arise with something like this:
7771
7772                friend void f(int);
7773                template <class T> class C {
7774                  friend void f(T) {}
7775                };
7776
7777              when `C<int>' is instantiated.  Now, `f(int)' is defined
7778              in the class.  */
7779
7780           if (!new_friend_is_defn)
7781             /* On the other hand, if the in-class declaration does
7782                *not* provide a definition, then we don't want to alter
7783                existing definitions.  We can just leave everything
7784                alone.  */
7785             ;
7786           else
7787             {
7788               tree new_template = TI_TEMPLATE (new_friend_template_info);
7789               tree new_args = TI_ARGS (new_friend_template_info);
7790
7791               /* Overwrite whatever template info was there before, if
7792                  any, with the new template information pertaining to
7793                  the declaration.  */
7794               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7795
7796               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7797                 {
7798                   /* We should have called reregister_specialization in
7799                      duplicate_decls.  */
7800                   gcc_assert (retrieve_specialization (new_template,
7801                                                        new_args, 0)
7802                               == old_decl);
7803
7804                   /* Instantiate it if the global has already been used.  */
7805                   if (DECL_ODR_USED (old_decl))
7806                     instantiate_decl (old_decl, /*defer_ok=*/true,
7807                                       /*expl_inst_class_mem_p=*/false);
7808                 }
7809               else
7810                 {
7811                   tree t;
7812
7813                   /* Indicate that the old function template is a partial
7814                      instantiation.  */
7815                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7816                     = new_friend_result_template_info;
7817
7818                   gcc_assert (new_template
7819                               == most_general_template (new_template));
7820                   gcc_assert (new_template != old_decl);
7821
7822                   /* Reassign any specializations already in the hash table
7823                      to the new more general template, and add the
7824                      additional template args.  */
7825                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7826                        t != NULL_TREE;
7827                        t = TREE_CHAIN (t))
7828                     {
7829                       tree spec = TREE_VALUE (t);
7830                       spec_entry elt;
7831
7832                       elt.tmpl = old_decl;
7833                       elt.args = DECL_TI_ARGS (spec);
7834                       elt.spec = NULL_TREE;
7835
7836                       htab_remove_elt (decl_specializations, &elt);
7837
7838                       DECL_TI_ARGS (spec)
7839                         = add_outermost_template_args (new_args,
7840                                                        DECL_TI_ARGS (spec));
7841
7842                       register_specialization
7843                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7844
7845                     }
7846                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7847                 }
7848             }
7849
7850           /* The information from NEW_FRIEND has been merged into OLD_DECL
7851              by duplicate_decls.  */
7852           new_friend = old_decl;
7853         }
7854     }
7855   else
7856     {
7857       tree context = DECL_CONTEXT (new_friend);
7858       bool dependent_p;
7859
7860       /* In the code
7861            template <class T> class C {
7862              template <class U> friend void C1<U>::f (); // case 1
7863              friend void C2<T>::f ();                    // case 2
7864            };
7865          we only need to make sure CONTEXT is a complete type for
7866          case 2.  To distinguish between the two cases, we note that
7867          CONTEXT of case 1 remains dependent type after tsubst while
7868          this isn't true for case 2.  */
7869       ++processing_template_decl;
7870       dependent_p = dependent_type_p (context);
7871       --processing_template_decl;
7872
7873       if (!dependent_p
7874           && !complete_type_or_else (context, NULL_TREE))
7875         return error_mark_node;
7876
7877       if (COMPLETE_TYPE_P (context))
7878         {
7879           /* Check to see that the declaration is really present, and,
7880              possibly obtain an improved declaration.  */
7881           tree fn = check_classfn (context,
7882                                    new_friend, NULL_TREE);
7883
7884           if (fn)
7885             new_friend = fn;
7886         }
7887     }
7888
7889   return new_friend;
7890 }
7891
7892 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7893    template arguments, as for tsubst.
7894
7895    Returns an appropriate tsubst'd friend type or error_mark_node on
7896    failure.  */
7897
7898 static tree
7899 tsubst_friend_class (tree friend_tmpl, tree args)
7900 {
7901   tree friend_type;
7902   tree tmpl;
7903   tree context;
7904
7905   context = CP_DECL_CONTEXT (friend_tmpl);
7906
7907   if (context != global_namespace)
7908     {
7909       if (TREE_CODE (context) == NAMESPACE_DECL)
7910         push_nested_namespace (context);
7911       else
7912         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7913     }
7914
7915   /* Look for a class template declaration.  We look for hidden names
7916      because two friend declarations of the same template are the
7917      same.  For example, in:
7918
7919        struct A { 
7920          template <typename> friend class F;
7921        };
7922        template <typename> struct B { 
7923          template <typename> friend class F;
7924        };
7925
7926      both F templates are the same.  */
7927   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7928                            /*block_p=*/true, 0, 
7929                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7930
7931   /* But, if we don't find one, it might be because we're in a
7932      situation like this:
7933
7934        template <class T>
7935        struct S {
7936          template <class U>
7937          friend struct S;
7938        };
7939
7940      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7941      for `S<int>', not the TEMPLATE_DECL.  */
7942   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7943     {
7944       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7945       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7946     }
7947
7948   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7949     {
7950       /* The friend template has already been declared.  Just
7951          check to see that the declarations match, and install any new
7952          default parameters.  We must tsubst the default parameters,
7953          of course.  We only need the innermost template parameters
7954          because that is all that redeclare_class_template will look
7955          at.  */
7956       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7957           > TMPL_ARGS_DEPTH (args))
7958         {
7959           tree parms;
7960           location_t saved_input_location;
7961           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7962                                          args, tf_warning_or_error);
7963
7964           saved_input_location = input_location;
7965           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7966           redeclare_class_template (TREE_TYPE (tmpl), parms);
7967           input_location = saved_input_location;
7968           
7969         }
7970
7971       friend_type = TREE_TYPE (tmpl);
7972     }
7973   else
7974     {
7975       /* The friend template has not already been declared.  In this
7976          case, the instantiation of the template class will cause the
7977          injection of this template into the global scope.  */
7978       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7979       if (tmpl == error_mark_node)
7980         return error_mark_node;
7981
7982       /* The new TMPL is not an instantiation of anything, so we
7983          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7984          the new type because that is supposed to be the corresponding
7985          template decl, i.e., TMPL.  */
7986       DECL_USE_TEMPLATE (tmpl) = 0;
7987       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7988       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7989       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7990         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7991
7992       /* Inject this template into the global scope.  */
7993       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7994     }
7995
7996   if (context != global_namespace)
7997     {
7998       if (TREE_CODE (context) == NAMESPACE_DECL)
7999         pop_nested_namespace (context);
8000       else
8001         pop_nested_class ();
8002     }
8003
8004   return friend_type;
8005 }
8006
8007 /* Returns zero if TYPE cannot be completed later due to circularity.
8008    Otherwise returns one.  */
8009
8010 static int
8011 can_complete_type_without_circularity (tree type)
8012 {
8013   if (type == NULL_TREE || type == error_mark_node)
8014     return 0;
8015   else if (COMPLETE_TYPE_P (type))
8016     return 1;
8017   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
8018     return can_complete_type_without_circularity (TREE_TYPE (type));
8019   else if (CLASS_TYPE_P (type)
8020            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
8021     return 0;
8022   else
8023     return 1;
8024 }
8025
8026 /* Apply any attributes which had to be deferred until instantiation
8027    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
8028    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8029
8030 static void
8031 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8032                                 tree args, tsubst_flags_t complain, tree in_decl)
8033 {
8034   tree last_dep = NULL_TREE;
8035   tree t;
8036   tree *p;
8037
8038   for (t = attributes; t; t = TREE_CHAIN (t))
8039     if (ATTR_IS_DEPENDENT (t))
8040       {
8041         last_dep = t;
8042         attributes = copy_list (attributes);
8043         break;
8044       }
8045
8046   if (DECL_P (*decl_p))
8047     {
8048       if (TREE_TYPE (*decl_p) == error_mark_node)
8049         return;
8050       p = &DECL_ATTRIBUTES (*decl_p);
8051     }
8052   else
8053     p = &TYPE_ATTRIBUTES (*decl_p);
8054
8055   if (last_dep)
8056     {
8057       tree late_attrs = NULL_TREE;
8058       tree *q = &late_attrs;
8059
8060       for (*p = attributes; *p; )
8061         {
8062           t = *p;
8063           if (ATTR_IS_DEPENDENT (t))
8064             {
8065               *p = TREE_CHAIN (t);
8066               TREE_CHAIN (t) = NULL_TREE;
8067               /* If the first attribute argument is an identifier, don't
8068                  pass it through tsubst.  Attributes like mode, format,
8069                  cleanup and several target specific attributes expect it
8070                  unmodified.  */
8071               if (TREE_VALUE (t)
8072                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8073                   && TREE_VALUE (TREE_VALUE (t))
8074                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8075                       == IDENTIFIER_NODE))
8076                 {
8077                   tree chain
8078                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8079                                    in_decl,
8080                                    /*integral_constant_expression_p=*/false);
8081                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8082                     TREE_VALUE (t)
8083                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8084                                    chain);
8085                 }
8086               else
8087                 TREE_VALUE (t)
8088                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8089                                  /*integral_constant_expression_p=*/false);
8090               *q = t;
8091               q = &TREE_CHAIN (t);
8092             }
8093           else
8094             p = &TREE_CHAIN (t);
8095         }
8096
8097       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8098     }
8099 }
8100
8101 /* Perform (or defer) access check for typedefs that were referenced
8102    from within the template TMPL code.
8103    This is a subroutine of instantiate_template and instantiate_class_template.
8104    TMPL is the template to consider and TARGS is the list of arguments of
8105    that template.  */
8106
8107 static void
8108 perform_typedefs_access_check (tree tmpl, tree targs)
8109 {
8110   location_t saved_location;
8111   int i;
8112   qualified_typedef_usage_t *iter;
8113
8114   if (!tmpl
8115       || (!CLASS_TYPE_P (tmpl)
8116           && TREE_CODE (tmpl) != FUNCTION_DECL))
8117     return;
8118
8119   saved_location = input_location;
8120   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8121                     get_types_needing_access_check (tmpl),
8122                     i, iter)
8123     {
8124       tree type_decl = iter->typedef_decl;
8125       tree type_scope = iter->context;
8126
8127       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8128         continue;
8129
8130       if (uses_template_parms (type_decl))
8131         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8132       if (uses_template_parms (type_scope))
8133         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8134
8135       /* Make access check error messages point to the location
8136          of the use of the typedef.  */
8137       input_location = iter->locus;
8138       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8139                                      type_decl, type_decl);
8140     }
8141     input_location = saved_location;
8142 }
8143
8144 static tree
8145 instantiate_class_template_1 (tree type)
8146 {
8147   tree templ, args, pattern, t, member;
8148   tree typedecl;
8149   tree pbinfo;
8150   tree base_list;
8151   unsigned int saved_maximum_field_alignment;
8152
8153   if (type == error_mark_node)
8154     return error_mark_node;
8155
8156   if (COMPLETE_OR_OPEN_TYPE_P (type)
8157       || uses_template_parms (type))
8158     return type;
8159
8160   /* Figure out which template is being instantiated.  */
8161   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8162   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8163
8164   /* Determine what specialization of the original template to
8165      instantiate.  */
8166   t = most_specialized_class (type, templ, tf_warning_or_error);
8167   if (t == error_mark_node)
8168     {
8169       TYPE_BEING_DEFINED (type) = 1;
8170       return error_mark_node;
8171     }
8172   else if (t)
8173     {
8174       /* This TYPE is actually an instantiation of a partial
8175          specialization.  We replace the innermost set of ARGS with
8176          the arguments appropriate for substitution.  For example,
8177          given:
8178
8179            template <class T> struct S {};
8180            template <class T> struct S<T*> {};
8181
8182          and supposing that we are instantiating S<int*>, ARGS will
8183          presently be {int*} -- but we need {int}.  */
8184       pattern = TREE_TYPE (t);
8185       args = TREE_PURPOSE (t);
8186     }
8187   else
8188     {
8189       pattern = TREE_TYPE (templ);
8190       args = CLASSTYPE_TI_ARGS (type);
8191     }
8192
8193   /* If the template we're instantiating is incomplete, then clearly
8194      there's nothing we can do.  */
8195   if (!COMPLETE_TYPE_P (pattern))
8196     return type;
8197
8198   /* If we've recursively instantiated too many templates, stop.  */
8199   if (! push_tinst_level (type))
8200     return type;
8201
8202   /* Now we're really doing the instantiation.  Mark the type as in
8203      the process of being defined.  */
8204   TYPE_BEING_DEFINED (type) = 1;
8205
8206   /* We may be in the middle of deferred access check.  Disable
8207      it now.  */
8208   push_deferring_access_checks (dk_no_deferred);
8209
8210   push_to_top_level ();
8211   /* Use #pragma pack from the template context.  */
8212   saved_maximum_field_alignment = maximum_field_alignment;
8213   maximum_field_alignment = TYPE_PRECISION (pattern);
8214
8215   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8216
8217   /* Set the input location to the most specialized template definition.
8218      This is needed if tsubsting causes an error.  */
8219   typedecl = TYPE_MAIN_DECL (pattern);
8220   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8221     DECL_SOURCE_LOCATION (typedecl);
8222
8223   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
8224   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
8225   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
8226   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
8227   TYPE_HAS_COPY_ASSIGN (type) = TYPE_HAS_COPY_ASSIGN (pattern);
8228   TYPE_HAS_CONST_COPY_ASSIGN (type) = TYPE_HAS_CONST_COPY_ASSIGN (pattern);
8229   TYPE_HAS_COPY_CTOR (type) = TYPE_HAS_COPY_CTOR (pattern);
8230   TYPE_HAS_CONST_COPY_CTOR (type) = TYPE_HAS_CONST_COPY_CTOR (pattern);
8231   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
8232   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
8233   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8234   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8235   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8236   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8237   if (ANON_AGGR_TYPE_P (pattern))
8238     SET_ANON_AGGR_TYPE_P (type);
8239   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8240     {
8241       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8242       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8243     }
8244   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8245
8246   pbinfo = TYPE_BINFO (pattern);
8247
8248   /* We should never instantiate a nested class before its enclosing
8249      class; we need to look up the nested class by name before we can
8250      instantiate it, and that lookup should instantiate the enclosing
8251      class.  */
8252   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8253               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8254
8255   base_list = NULL_TREE;
8256   if (BINFO_N_BASE_BINFOS (pbinfo))
8257     {
8258       tree pbase_binfo;
8259       tree pushed_scope;
8260       int i;
8261
8262       /* We must enter the scope containing the type, as that is where
8263          the accessibility of types named in dependent bases are
8264          looked up from.  */
8265       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8266
8267       /* Substitute into each of the bases to determine the actual
8268          basetypes.  */
8269       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8270         {
8271           tree base;
8272           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8273           tree expanded_bases = NULL_TREE;
8274           int idx, len = 1;
8275
8276           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8277             {
8278               expanded_bases = 
8279                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8280                                        args, tf_error, NULL_TREE);
8281               if (expanded_bases == error_mark_node)
8282                 continue;
8283
8284               len = TREE_VEC_LENGTH (expanded_bases);
8285             }
8286
8287           for (idx = 0; idx < len; idx++)
8288             {
8289               if (expanded_bases)
8290                 /* Extract the already-expanded base class.  */
8291                 base = TREE_VEC_ELT (expanded_bases, idx);
8292               else
8293                 /* Substitute to figure out the base class.  */
8294                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8295                                NULL_TREE);
8296
8297               if (base == error_mark_node)
8298                 continue;
8299
8300               base_list = tree_cons (access, base, base_list);
8301               if (BINFO_VIRTUAL_P (pbase_binfo))
8302                 TREE_TYPE (base_list) = integer_type_node;
8303             }
8304         }
8305
8306       /* The list is now in reverse order; correct that.  */
8307       base_list = nreverse (base_list);
8308
8309       if (pushed_scope)
8310         pop_scope (pushed_scope);
8311     }
8312   /* Now call xref_basetypes to set up all the base-class
8313      information.  */
8314   xref_basetypes (type, base_list);
8315
8316   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8317                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8318                                   args, tf_error, NULL_TREE);
8319   fixup_attribute_variants (type);
8320
8321   /* Now that our base classes are set up, enter the scope of the
8322      class, so that name lookups into base classes, etc. will work
8323      correctly.  This is precisely analogous to what we do in
8324      begin_class_definition when defining an ordinary non-template
8325      class, except we also need to push the enclosing classes.  */
8326   push_nested_class (type);
8327
8328   /* Now members are processed in the order of declaration.  */
8329   for (member = CLASSTYPE_DECL_LIST (pattern);
8330        member; member = TREE_CHAIN (member))
8331     {
8332       tree t = TREE_VALUE (member);
8333
8334       if (TREE_PURPOSE (member))
8335         {
8336           if (TYPE_P (t))
8337             {
8338               /* Build new CLASSTYPE_NESTED_UTDS.  */
8339
8340               tree newtag;
8341               bool class_template_p;
8342
8343               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8344                                   && TYPE_LANG_SPECIFIC (t)
8345                                   && CLASSTYPE_IS_TEMPLATE (t));
8346               /* If the member is a class template, then -- even after
8347                  substitution -- there may be dependent types in the
8348                  template argument list for the class.  We increment
8349                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8350                  that function will assume that no types are dependent
8351                  when outside of a template.  */
8352               if (class_template_p)
8353                 ++processing_template_decl;
8354               newtag = tsubst (t, args, tf_error, NULL_TREE);
8355               if (class_template_p)
8356                 --processing_template_decl;
8357               if (newtag == error_mark_node)
8358                 continue;
8359
8360               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8361                 {
8362                   tree name = TYPE_IDENTIFIER (t);
8363
8364                   if (class_template_p)
8365                     /* Unfortunately, lookup_template_class sets
8366                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8367                        instantiation (i.e., for the type of a member
8368                        template class nested within a template class.)
8369                        This behavior is required for
8370                        maybe_process_partial_specialization to work
8371                        correctly, but is not accurate in this case;
8372                        the TAG is not an instantiation of anything.
8373                        (The corresponding TEMPLATE_DECL is an
8374                        instantiation, but the TYPE is not.) */
8375                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8376
8377                   /* Now, we call pushtag to put this NEWTAG into the scope of
8378                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8379                      pushtag calling push_template_decl.  We don't have to do
8380                      this for enums because it will already have been done in
8381                      tsubst_enum.  */
8382                   if (name)
8383                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8384                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8385                 }
8386             }
8387           else if (TREE_CODE (t) == FUNCTION_DECL
8388                    || DECL_FUNCTION_TEMPLATE_P (t))
8389             {
8390               /* Build new TYPE_METHODS.  */
8391               tree r;
8392
8393               if (TREE_CODE (t) == TEMPLATE_DECL)
8394                 ++processing_template_decl;
8395               r = tsubst (t, args, tf_error, NULL_TREE);
8396               if (TREE_CODE (t) == TEMPLATE_DECL)
8397                 --processing_template_decl;
8398               set_current_access_from_decl (r);
8399               finish_member_declaration (r);
8400             }
8401           else
8402             {
8403               /* Build new TYPE_FIELDS.  */
8404               if (TREE_CODE (t) == STATIC_ASSERT)
8405                 {
8406                   tree condition = 
8407                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8408                                  tf_warning_or_error, NULL_TREE,
8409                                  /*integral_constant_expression_p=*/true);
8410                   finish_static_assert (condition,
8411                                         STATIC_ASSERT_MESSAGE (t), 
8412                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8413                                         /*member_p=*/true);
8414                 }
8415               else if (TREE_CODE (t) != CONST_DECL)
8416                 {
8417                   tree r;
8418
8419                   /* The file and line for this declaration, to
8420                      assist in error message reporting.  Since we
8421                      called push_tinst_level above, we don't need to
8422                      restore these.  */
8423                   input_location = DECL_SOURCE_LOCATION (t);
8424
8425                   if (TREE_CODE (t) == TEMPLATE_DECL)
8426                     ++processing_template_decl;
8427                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8428                   if (TREE_CODE (t) == TEMPLATE_DECL)
8429                     --processing_template_decl;
8430                   if (TREE_CODE (r) == VAR_DECL)
8431                     {
8432                       /* In [temp.inst]:
8433
8434                            [t]he initialization (and any associated
8435                            side-effects) of a static data member does
8436                            not occur unless the static data member is
8437                            itself used in a way that requires the
8438                            definition of the static data member to
8439                            exist.
8440
8441                          Therefore, we do not substitute into the
8442                          initialized for the static data member here.  */
8443                       finish_static_data_member_decl
8444                         (r,
8445                          /*init=*/NULL_TREE,
8446                          /*init_const_expr_p=*/false,
8447                          /*asmspec_tree=*/NULL_TREE,
8448                          /*flags=*/0);
8449                     }
8450                   else if (TREE_CODE (r) == FIELD_DECL)
8451                     {
8452                       /* Determine whether R has a valid type and can be
8453                          completed later.  If R is invalid, then it is
8454                          replaced by error_mark_node so that it will not be
8455                          added to TYPE_FIELDS.  */
8456                       tree rtype = TREE_TYPE (r);
8457                       if (can_complete_type_without_circularity (rtype))
8458                         complete_type (rtype);
8459
8460                       if (!COMPLETE_TYPE_P (rtype))
8461                         {
8462                           cxx_incomplete_type_error (r, rtype);
8463                           r = error_mark_node;
8464                         }
8465                     }
8466
8467                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8468                      such a thing will already have been added to the field
8469                      list by tsubst_enum in finish_member_declaration in the
8470                      CLASSTYPE_NESTED_UTDS case above.  */
8471                   if (!(TREE_CODE (r) == TYPE_DECL
8472                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8473                         && DECL_ARTIFICIAL (r)))
8474                     {
8475                       set_current_access_from_decl (r);
8476                       finish_member_declaration (r);
8477                     }
8478                 }
8479             }
8480         }
8481       else
8482         {
8483           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8484             {
8485               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8486
8487               tree friend_type = t;
8488               bool adjust_processing_template_decl = false;
8489
8490               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8491                 {
8492                   /* template <class T> friend class C;  */
8493                   friend_type = tsubst_friend_class (friend_type, args);
8494                   adjust_processing_template_decl = true;
8495                 }
8496               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8497                 {
8498                   /* template <class T> friend class C::D;  */
8499                   friend_type = tsubst (friend_type, args,
8500                                         tf_warning_or_error, NULL_TREE);
8501                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8502                     friend_type = TREE_TYPE (friend_type);
8503                   adjust_processing_template_decl = true;
8504                 }
8505               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
8506                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
8507                 {
8508                   /* This could be either
8509
8510                        friend class T::C;
8511
8512                      when dependent_type_p is false or
8513
8514                        template <class U> friend class T::C;
8515
8516                      otherwise.  */
8517                   friend_type = tsubst (friend_type, args,
8518                                         tf_warning_or_error, NULL_TREE);
8519                   /* Bump processing_template_decl for correct
8520                      dependent_type_p calculation.  */
8521                   ++processing_template_decl;
8522                   if (dependent_type_p (friend_type))
8523                     adjust_processing_template_decl = true;
8524                   --processing_template_decl;
8525                 }
8526               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8527                        && hidden_name_p (TYPE_NAME (friend_type)))
8528                 {
8529                   /* friend class C;
8530
8531                      where C hasn't been declared yet.  Let's lookup name
8532                      from namespace scope directly, bypassing any name that
8533                      come from dependent base class.  */
8534                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8535
8536                   /* The call to xref_tag_from_type does injection for friend
8537                      classes.  */
8538                   push_nested_namespace (ns);
8539                   friend_type =
8540                     xref_tag_from_type (friend_type, NULL_TREE,
8541                                         /*tag_scope=*/ts_current);
8542                   pop_nested_namespace (ns);
8543                 }
8544               else if (uses_template_parms (friend_type))
8545                 /* friend class C<T>;  */
8546                 friend_type = tsubst (friend_type, args,
8547                                       tf_warning_or_error, NULL_TREE);
8548               /* Otherwise it's
8549
8550                    friend class C;
8551
8552                  where C is already declared or
8553
8554                    friend class C<int>;
8555
8556                  We don't have to do anything in these cases.  */
8557
8558               if (adjust_processing_template_decl)
8559                 /* Trick make_friend_class into realizing that the friend
8560                    we're adding is a template, not an ordinary class.  It's
8561                    important that we use make_friend_class since it will
8562                    perform some error-checking and output cross-reference
8563                    information.  */
8564                 ++processing_template_decl;
8565
8566               if (friend_type != error_mark_node)
8567                 make_friend_class (type, friend_type, /*complain=*/false);
8568
8569               if (adjust_processing_template_decl)
8570                 --processing_template_decl;
8571             }
8572           else
8573             {
8574               /* Build new DECL_FRIENDLIST.  */
8575               tree r;
8576
8577               /* The file and line for this declaration, to
8578                  assist in error message reporting.  Since we
8579                  called push_tinst_level above, we don't need to
8580                  restore these.  */
8581               input_location = DECL_SOURCE_LOCATION (t);
8582
8583               if (TREE_CODE (t) == TEMPLATE_DECL)
8584                 {
8585                   ++processing_template_decl;
8586                   push_deferring_access_checks (dk_no_check);
8587                 }
8588
8589               r = tsubst_friend_function (t, args);
8590               add_friend (type, r, /*complain=*/false);
8591               if (TREE_CODE (t) == TEMPLATE_DECL)
8592                 {
8593                   pop_deferring_access_checks ();
8594                   --processing_template_decl;
8595                 }
8596             }
8597         }
8598     }
8599
8600   if (CLASSTYPE_LAMBDA_EXPR (type))
8601     maybe_add_lambda_conv_op (type);
8602
8603   /* Set the file and line number information to whatever is given for
8604      the class itself.  This puts error messages involving generated
8605      implicit functions at a predictable point, and the same point
8606      that would be used for non-template classes.  */
8607   input_location = DECL_SOURCE_LOCATION (typedecl);
8608
8609   unreverse_member_declarations (type);
8610   finish_struct_1 (type);
8611   TYPE_BEING_DEFINED (type) = 0;
8612
8613   /* We don't instantiate default arguments for member functions.  14.7.1:
8614
8615      The implicit instantiation of a class template specialization causes
8616      the implicit instantiation of the declarations, but not of the
8617      definitions or default arguments, of the class member functions,
8618      member classes, static data members and member templates....  */
8619
8620   /* Some typedefs referenced from within the template code need to be access
8621      checked at template instantiation time, i.e now. These types were
8622      added to the template at parsing time. Let's get those and perform
8623      the access checks then.  */
8624   perform_typedefs_access_check (pattern, args);
8625   perform_deferred_access_checks ();
8626   pop_nested_class ();
8627   maximum_field_alignment = saved_maximum_field_alignment;
8628   pop_from_top_level ();
8629   pop_deferring_access_checks ();
8630   pop_tinst_level ();
8631
8632   /* The vtable for a template class can be emitted in any translation
8633      unit in which the class is instantiated.  When there is no key
8634      method, however, finish_struct_1 will already have added TYPE to
8635      the keyed_classes list.  */
8636   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8637     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8638
8639   return type;
8640 }
8641
8642 /* Wrapper for instantiate_class_template_1.  */
8643
8644 tree
8645 instantiate_class_template (tree type)
8646 {
8647   tree ret;
8648   timevar_push (TV_TEMPLATE_INST);
8649   ret = instantiate_class_template_1 (type);
8650   timevar_pop (TV_TEMPLATE_INST);
8651   return ret;
8652 }
8653
8654 static tree
8655 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8656 {
8657   tree r;
8658
8659   if (!t)
8660     r = t;
8661   else if (TYPE_P (t))
8662     r = tsubst (t, args, complain, in_decl);
8663   else
8664     {
8665       if (!(complain & tf_warning))
8666         ++c_inhibit_evaluation_warnings;
8667       r = tsubst_expr (t, args, complain, in_decl,
8668                        /*integral_constant_expression_p=*/true);
8669       if (!(complain & tf_warning))
8670         --c_inhibit_evaluation_warnings;
8671     }
8672   return r;
8673 }
8674
8675 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8676    NONTYPE_ARGUMENT_PACK.  */
8677
8678 static tree
8679 make_fnparm_pack (tree spec_parm)
8680 {
8681   /* Collect all of the extra "packed" parameters into an
8682      argument pack.  */
8683   tree parmvec;
8684   tree parmtypevec;
8685   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8686   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8687   int i, len = list_length (spec_parm);
8688
8689   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8690   parmvec = make_tree_vec (len);
8691   parmtypevec = make_tree_vec (len);
8692   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
8693     {
8694       TREE_VEC_ELT (parmvec, i) = spec_parm;
8695       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8696     }
8697
8698   /* Build the argument packs.  */
8699   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8700   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8701   TREE_TYPE (argpack) = argtypepack;
8702
8703   return argpack;
8704 }        
8705
8706 /* Substitute ARGS into T, which is an pack expansion
8707    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8708    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8709    (if only a partial substitution could be performed) or
8710    ERROR_MARK_NODE if there was an error.  */
8711 tree
8712 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8713                        tree in_decl)
8714 {
8715   tree pattern;
8716   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8717   int i, len = -1;
8718   tree result;
8719   int incomplete = 0;
8720   htab_t saved_local_specializations = NULL;
8721
8722   gcc_assert (PACK_EXPANSION_P (t));
8723   pattern = PACK_EXPANSION_PATTERN (t);
8724
8725   /* Determine the argument packs that will instantiate the parameter
8726      packs used in the expansion expression. While we're at it,
8727      compute the number of arguments to be expanded and make sure it
8728      is consistent.  */
8729   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8730        pack = TREE_CHAIN (pack))
8731     {
8732       tree parm_pack = TREE_VALUE (pack);
8733       tree arg_pack = NULL_TREE;
8734       tree orig_arg = NULL_TREE;
8735
8736       if (TREE_CODE (parm_pack) == PARM_DECL)
8737         {
8738           if (!cp_unevaluated_operand)
8739             arg_pack = retrieve_local_specialization (parm_pack);
8740           else
8741             {
8742               /* We can't rely on local_specializations for a parameter
8743                  name used later in a function declaration (such as in a
8744                  late-specified return type).  Even if it exists, it might
8745                  have the wrong value for a recursive call.  Just make a
8746                  dummy decl, since it's only used for its type.  */
8747               arg_pack = tsubst_decl (parm_pack, args, complain);
8748               if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
8749                 /* Partial instantiation of the parm_pack, we can't build
8750                    up an argument pack yet.  */
8751                 arg_pack = NULL_TREE;
8752               else
8753                 arg_pack = make_fnparm_pack (arg_pack);
8754             }
8755         }
8756       else
8757         {
8758           int level, idx, levels;
8759           template_parm_level_and_index (parm_pack, &level, &idx);
8760
8761           levels = TMPL_ARGS_DEPTH (args);
8762           if (level <= levels)
8763             arg_pack = TMPL_ARG (args, level, idx);
8764         }
8765
8766       orig_arg = arg_pack;
8767       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8768         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8769       
8770       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8771         /* This can only happen if we forget to expand an argument
8772            pack somewhere else. Just return an error, silently.  */
8773         {
8774           result = make_tree_vec (1);
8775           TREE_VEC_ELT (result, 0) = error_mark_node;
8776           return result;
8777         }
8778
8779       /* For clarity in the comments below let's use the
8780          representation 'argument_pack<elements>' to denote an
8781          argument pack and its elements.
8782
8783          In the 'if' block below, we want to detect cases where
8784          ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
8785          check if ARG_PACK is an argument pack which sole element is
8786          the expansion of PARM_PACK.  That argument pack is typically
8787          created by template_parm_to_arg when passed a parameter
8788          pack.  */
8789       if (arg_pack
8790           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8791           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8792         {
8793           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8794           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8795           /* So we have an argument_pack<P...>.  We want to test if P
8796              is actually PARM_PACK.  We will not use cp_tree_equal to
8797              test P and PARM_PACK because during type fixup (by
8798              fixup_template_parm) P can be a pre-fixup version of a
8799              type and PARM_PACK be its post-fixup version.
8800              cp_tree_equal would consider them as different even
8801              though we would want to consider them compatible for our
8802              precise purpose here.
8803
8804              Thus we are going to consider that P and PARM_PACK are
8805              compatible if they have the same DECL.  */
8806           if ((/* If ARG_PACK is a type parameter pack named by the
8807                   same DECL as parm_pack ...  */
8808                (TYPE_P (pattern)
8809                 && TYPE_P (parm_pack)
8810                 && TYPE_NAME (pattern) == TYPE_NAME (parm_pack))
8811                /* ... or if ARG_PACK is a non-type parameter
8812                   named by the same DECL as parm_pack ...  */
8813                || (TREE_CODE (pattern) == TEMPLATE_PARM_INDEX
8814                    && TREE_CODE (parm_pack) == PARM_DECL
8815                    && TEMPLATE_PARM_DECL (pattern)
8816                    == TEMPLATE_PARM_DECL (DECL_INITIAL (parm_pack))))
8817               && template_parameter_pack_p (pattern))
8818             /* ... then the argument pack that the parameter maps to
8819                is just an expansion of the parameter itself, such as
8820                one would find in the implicit typedef of a class
8821                inside the class itself.  Consider this parameter
8822                "unsubstituted", so that we will maintain the outer
8823                pack expansion.  */
8824             arg_pack = NULL_TREE;
8825         }
8826           
8827       if (arg_pack)
8828         {
8829           int my_len = 
8830             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8831
8832           /* It's all-or-nothing with incomplete argument packs.  */
8833           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8834             return error_mark_node;
8835           
8836           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8837             incomplete = 1;
8838
8839           if (len < 0)
8840             len = my_len;
8841           else if (len != my_len)
8842             {
8843               if (incomplete)
8844                 /* We got explicit args for some packs but not others;
8845                    do nothing now and try again after deduction.  */
8846                 return t;
8847               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8848                 error ("mismatched argument pack lengths while expanding "
8849                        "%<%T%>",
8850                        pattern);
8851               else
8852                 error ("mismatched argument pack lengths while expanding "
8853                        "%<%E%>",
8854                        pattern);
8855               return error_mark_node;
8856             }
8857
8858           /* Keep track of the parameter packs and their corresponding
8859              argument packs.  */
8860           packs = tree_cons (parm_pack, arg_pack, packs);
8861           TREE_TYPE (packs) = orig_arg;
8862         }
8863       else
8864         /* We can't substitute for this parameter pack.  */
8865         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8866                                          TREE_VALUE (pack),
8867                                          unsubstituted_packs);
8868     }
8869
8870   /* We cannot expand this expansion expression, because we don't have
8871      all of the argument packs we need. Substitute into the pattern
8872      and return a PACK_EXPANSION_*. The caller will need to deal with
8873      that.  */
8874   if (unsubstituted_packs)
8875     {
8876       tree new_pat;
8877       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8878         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8879                                /*integral_constant_expression_p=*/false);
8880       else
8881         new_pat = tsubst (pattern, args, complain, in_decl);
8882       return make_pack_expansion (new_pat);
8883     }
8884
8885   /* We could not find any argument packs that work.  */
8886   if (len < 0)
8887     return error_mark_node;
8888
8889   if (cp_unevaluated_operand)
8890     {
8891       /* We're in a late-specified return type, so create our own local
8892          specializations table; the current table is either NULL or (in the
8893          case of recursive unification) might have bindings that we don't
8894          want to use or alter.  */
8895       saved_local_specializations = local_specializations;
8896       local_specializations = htab_create (37,
8897                                            hash_local_specialization,
8898                                            eq_local_specializations,
8899                                            NULL);
8900     }
8901
8902   /* For each argument in each argument pack, substitute into the
8903      pattern.  */
8904   result = make_tree_vec (len + incomplete);
8905   for (i = 0; i < len + incomplete; ++i)
8906     {
8907       /* For parameter pack, change the substitution of the parameter
8908          pack to the ith argument in its argument pack, then expand
8909          the pattern.  */
8910       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8911         {
8912           tree parm = TREE_PURPOSE (pack);
8913
8914           if (TREE_CODE (parm) == PARM_DECL)
8915             {
8916               /* Select the Ith argument from the pack.  */
8917               tree arg = make_node (ARGUMENT_PACK_SELECT);
8918               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8919               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8920               mark_used (parm);
8921               register_local_specialization (arg, parm);
8922             }
8923           else
8924             {
8925               tree value = parm;
8926               int idx, level;
8927               template_parm_level_and_index (parm, &level, &idx);
8928               
8929               if (i < len) 
8930                 {
8931                   /* Select the Ith argument from the pack. */
8932                   value = make_node (ARGUMENT_PACK_SELECT);
8933                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8934                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8935                 }
8936
8937               /* Update the corresponding argument.  */
8938               TMPL_ARG (args, level, idx) = value;
8939             }
8940         }
8941
8942       /* Substitute into the PATTERN with the altered arguments.  */
8943       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8944         TREE_VEC_ELT (result, i) = 
8945           tsubst_expr (pattern, args, complain, in_decl,
8946                        /*integral_constant_expression_p=*/false);
8947       else
8948         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8949
8950       if (i == len)
8951         /* When we have incomplete argument packs, the last "expanded"
8952            result is itself a pack expansion, which allows us
8953            to deduce more arguments.  */
8954         TREE_VEC_ELT (result, i) = 
8955           make_pack_expansion (TREE_VEC_ELT (result, i));
8956
8957       if (TREE_VEC_ELT (result, i) == error_mark_node)
8958         {
8959           result = error_mark_node;
8960           break;
8961         }
8962     }
8963
8964   /* Update ARGS to restore the substitution from parameter packs to
8965      their argument packs.  */
8966   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8967     {
8968       tree parm = TREE_PURPOSE (pack);
8969
8970       if (TREE_CODE (parm) == PARM_DECL)
8971         register_local_specialization (TREE_TYPE (pack), parm);
8972       else
8973         {
8974           int idx, level;
8975           template_parm_level_and_index (parm, &level, &idx);
8976           
8977           /* Update the corresponding argument.  */
8978           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8979             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8980               TREE_TYPE (pack);
8981           else
8982             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8983         }
8984     }
8985
8986   if (saved_local_specializations)
8987     {
8988       htab_delete (local_specializations);
8989       local_specializations = saved_local_specializations;
8990     }
8991   
8992   return result;
8993 }
8994
8995 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8996    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8997    parameter packs; all parms generated from a function parameter pack will
8998    have the same DECL_PARM_INDEX.  */
8999
9000 tree
9001 get_pattern_parm (tree parm, tree tmpl)
9002 {
9003   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
9004   tree patparm;
9005
9006   if (DECL_ARTIFICIAL (parm))
9007     {
9008       for (patparm = DECL_ARGUMENTS (pattern);
9009            patparm; patparm = DECL_CHAIN (patparm))
9010         if (DECL_ARTIFICIAL (patparm)
9011             && DECL_NAME (parm) == DECL_NAME (patparm))
9012           break;
9013     }
9014   else
9015     {
9016       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
9017       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
9018       gcc_assert (DECL_PARM_INDEX (patparm)
9019                   == DECL_PARM_INDEX (parm));
9020     }
9021
9022   return patparm;
9023 }
9024
9025 /* Substitute ARGS into the vector or list of template arguments T.  */
9026
9027 static tree
9028 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9029 {
9030   tree orig_t = t;
9031   int len, need_new = 0, i, expanded_len_adjust = 0, out;
9032   tree *elts;
9033
9034   if (t == error_mark_node)
9035     return error_mark_node;
9036
9037   len = TREE_VEC_LENGTH (t);
9038   elts = XALLOCAVEC (tree, len);
9039
9040   for (i = 0; i < len; i++)
9041     {
9042       tree orig_arg = TREE_VEC_ELT (t, i);
9043       tree new_arg;
9044
9045       if (TREE_CODE (orig_arg) == TREE_VEC)
9046         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9047       else if (PACK_EXPANSION_P (orig_arg))
9048         {
9049           /* Substitute into an expansion expression.  */
9050           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9051
9052           if (TREE_CODE (new_arg) == TREE_VEC)
9053             /* Add to the expanded length adjustment the number of
9054                expanded arguments. We subtract one from this
9055                measurement, because the argument pack expression
9056                itself is already counted as 1 in
9057                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9058                the argument pack is empty.  */
9059             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9060         }
9061       else if (ARGUMENT_PACK_P (orig_arg))
9062         {
9063           /* Substitute into each of the arguments.  */
9064           new_arg = TYPE_P (orig_arg)
9065             ? cxx_make_type (TREE_CODE (orig_arg))
9066             : make_node (TREE_CODE (orig_arg));
9067           
9068           SET_ARGUMENT_PACK_ARGS (
9069             new_arg,
9070             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9071                                   args, complain, in_decl));
9072
9073           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9074             new_arg = error_mark_node;
9075
9076           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9077             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9078                                           complain, in_decl);
9079             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9080
9081             if (TREE_TYPE (new_arg) == error_mark_node)
9082               new_arg = error_mark_node;
9083           }
9084         }
9085       else
9086         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9087
9088       if (new_arg == error_mark_node)
9089         return error_mark_node;
9090
9091       elts[i] = new_arg;
9092       if (new_arg != orig_arg)
9093         need_new = 1;
9094     }
9095
9096   if (!need_new)
9097     return t;
9098
9099   /* Make space for the expanded arguments coming from template
9100      argument packs.  */
9101   t = make_tree_vec (len + expanded_len_adjust);
9102   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9103      arguments for a member template.
9104      In that case each TREE_VEC in ORIG_T represents a level of template
9105      arguments, and ORIG_T won't carry any non defaulted argument count.
9106      It will rather be the nested TREE_VECs that will carry one.
9107      In other words, ORIG_T carries a non defaulted argument count only
9108      if it doesn't contain any nested TREE_VEC.  */
9109   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9110     {
9111       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9112       count += expanded_len_adjust;
9113       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9114     }
9115   for (i = 0, out = 0; i < len; i++)
9116     {
9117       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9118            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9119           && TREE_CODE (elts[i]) == TREE_VEC)
9120         {
9121           int idx;
9122
9123           /* Now expand the template argument pack "in place".  */
9124           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9125             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9126         }
9127       else
9128         {
9129           TREE_VEC_ELT (t, out) = elts[i];
9130           out++;
9131         }
9132     }
9133
9134   return t;
9135 }
9136
9137 /* Return the result of substituting ARGS into the template parameters
9138    given by PARMS.  If there are m levels of ARGS and m + n levels of
9139    PARMS, then the result will contain n levels of PARMS.  For
9140    example, if PARMS is `template <class T> template <class U>
9141    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9142    result will be `template <int*, double, class V>'.  */
9143
9144 static tree
9145 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9146 {
9147   tree r = NULL_TREE;
9148   tree* new_parms;
9149
9150   /* When substituting into a template, we must set
9151      PROCESSING_TEMPLATE_DECL as the template parameters may be
9152      dependent if they are based on one-another, and the dependency
9153      predicates are short-circuit outside of templates.  */
9154   ++processing_template_decl;
9155
9156   for (new_parms = &r;
9157        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9158        new_parms = &(TREE_CHAIN (*new_parms)),
9159          parms = TREE_CHAIN (parms))
9160     {
9161       tree new_vec =
9162         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9163       int i;
9164
9165       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9166         {
9167           tree tuple;
9168
9169           if (parms == error_mark_node)
9170             continue;
9171
9172           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9173
9174           if (tuple == error_mark_node)
9175             continue;
9176
9177           TREE_VEC_ELT (new_vec, i) =
9178             tsubst_template_parm (tuple, args, complain);
9179         }
9180
9181       *new_parms =
9182         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9183                              - TMPL_ARGS_DEPTH (args)),
9184                    new_vec, NULL_TREE);
9185     }
9186
9187   --processing_template_decl;
9188
9189   return r;
9190 }
9191
9192 /* Return the result of substituting ARGS into one template parameter
9193    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9194    parameter and which TREE_PURPOSE is the default argument of the
9195    template parameter.  */
9196
9197 static tree
9198 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9199 {
9200   tree default_value, parm_decl;
9201
9202   if (args == NULL_TREE
9203       || t == NULL_TREE
9204       || t == error_mark_node)
9205     return t;
9206
9207   gcc_assert (TREE_CODE (t) == TREE_LIST);
9208
9209   default_value = TREE_PURPOSE (t);
9210   parm_decl = TREE_VALUE (t);
9211
9212   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9213   if (TREE_CODE (parm_decl) == PARM_DECL
9214       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9215     parm_decl = error_mark_node;
9216   default_value = tsubst_template_arg (default_value, args,
9217                                        complain, NULL_TREE);
9218
9219   return build_tree_list (default_value, parm_decl);
9220 }
9221
9222 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9223    type T.  If T is not an aggregate or enumeration type, it is
9224    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9225    ENTERING_SCOPE is nonzero, T is the context for a template which
9226    we are presently tsubst'ing.  Return the substituted value.  */
9227
9228 static tree
9229 tsubst_aggr_type (tree t,
9230                   tree args,
9231                   tsubst_flags_t complain,
9232                   tree in_decl,
9233                   int entering_scope)
9234 {
9235   if (t == NULL_TREE)
9236     return NULL_TREE;
9237
9238   switch (TREE_CODE (t))
9239     {
9240     case RECORD_TYPE:
9241       if (TYPE_PTRMEMFUNC_P (t))
9242         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9243
9244       /* Else fall through.  */
9245     case ENUMERAL_TYPE:
9246     case UNION_TYPE:
9247       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9248         {
9249           tree argvec;
9250           tree context;
9251           tree r;
9252           int saved_unevaluated_operand;
9253           int saved_inhibit_evaluation_warnings;
9254
9255           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9256           saved_unevaluated_operand = cp_unevaluated_operand;
9257           cp_unevaluated_operand = 0;
9258           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9259           c_inhibit_evaluation_warnings = 0;
9260
9261           /* First, determine the context for the type we are looking
9262              up.  */
9263           context = TYPE_CONTEXT (t);
9264           if (context)
9265             {
9266               context = tsubst_aggr_type (context, args, complain,
9267                                           in_decl, /*entering_scope=*/1);
9268               /* If context is a nested class inside a class template,
9269                  it may still need to be instantiated (c++/33959).  */
9270               if (TYPE_P (context))
9271                 context = complete_type (context);
9272             }
9273
9274           /* Then, figure out what arguments are appropriate for the
9275              type we are trying to find.  For example, given:
9276
9277                template <class T> struct S;
9278                template <class T, class U> void f(T, U) { S<U> su; }
9279
9280              and supposing that we are instantiating f<int, double>,
9281              then our ARGS will be {int, double}, but, when looking up
9282              S we only want {double}.  */
9283           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9284                                          complain, in_decl);
9285           if (argvec == error_mark_node)
9286             r = error_mark_node;
9287           else
9288             {
9289               r = lookup_template_class (t, argvec, in_decl, context,
9290                                          entering_scope, complain);
9291               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9292             }
9293
9294           cp_unevaluated_operand = saved_unevaluated_operand;
9295           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9296
9297           return r;
9298         }
9299       else
9300         /* This is not a template type, so there's nothing to do.  */
9301         return t;
9302
9303     default:
9304       return tsubst (t, args, complain, in_decl);
9305     }
9306 }
9307
9308 /* Substitute into the default argument ARG (a default argument for
9309    FN), which has the indicated TYPE.  */
9310
9311 tree
9312 tsubst_default_argument (tree fn, tree type, tree arg)
9313 {
9314   tree saved_class_ptr = NULL_TREE;
9315   tree saved_class_ref = NULL_TREE;
9316
9317   /* This can happen in invalid code.  */
9318   if (TREE_CODE (arg) == DEFAULT_ARG)
9319     return arg;
9320
9321   /* This default argument came from a template.  Instantiate the
9322      default argument here, not in tsubst.  In the case of
9323      something like:
9324
9325        template <class T>
9326        struct S {
9327          static T t();
9328          void f(T = t());
9329        };
9330
9331      we must be careful to do name lookup in the scope of S<T>,
9332      rather than in the current class.  */
9333   push_access_scope (fn);
9334   /* The "this" pointer is not valid in a default argument.  */
9335   if (cfun)
9336     {
9337       saved_class_ptr = current_class_ptr;
9338       cp_function_chain->x_current_class_ptr = NULL_TREE;
9339       saved_class_ref = current_class_ref;
9340       cp_function_chain->x_current_class_ref = NULL_TREE;
9341     }
9342
9343   push_deferring_access_checks(dk_no_deferred);
9344   /* The default argument expression may cause implicitly defined
9345      member functions to be synthesized, which will result in garbage
9346      collection.  We must treat this situation as if we were within
9347      the body of function so as to avoid collecting live data on the
9348      stack.  */
9349   ++function_depth;
9350   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9351                      tf_warning_or_error, NULL_TREE,
9352                      /*integral_constant_expression_p=*/false);
9353   --function_depth;
9354   pop_deferring_access_checks();
9355
9356   /* Restore the "this" pointer.  */
9357   if (cfun)
9358     {
9359       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9360       cp_function_chain->x_current_class_ref = saved_class_ref;
9361     }
9362
9363   /* Make sure the default argument is reasonable.  */
9364   arg = check_default_argument (type, arg);
9365
9366   pop_access_scope (fn);
9367
9368   return arg;
9369 }
9370
9371 /* Substitute into all the default arguments for FN.  */
9372
9373 static void
9374 tsubst_default_arguments (tree fn)
9375 {
9376   tree arg;
9377   tree tmpl_args;
9378
9379   tmpl_args = DECL_TI_ARGS (fn);
9380
9381   /* If this function is not yet instantiated, we certainly don't need
9382      its default arguments.  */
9383   if (uses_template_parms (tmpl_args))
9384     return;
9385   /* Don't do this again for clones.  */
9386   if (DECL_CLONED_FUNCTION_P (fn))
9387     return;
9388
9389   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9390        arg;
9391        arg = TREE_CHAIN (arg))
9392     if (TREE_PURPOSE (arg))
9393       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9394                                                     TREE_VALUE (arg),
9395                                                     TREE_PURPOSE (arg));
9396 }
9397
9398 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9399    result of the substitution.  Issue error and warning messages under
9400    control of COMPLAIN.  */
9401
9402 static tree
9403 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9404 {
9405 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9406   location_t saved_loc;
9407   tree r = NULL_TREE;
9408   tree in_decl = t;
9409   hashval_t hash = 0;
9410
9411   /* Set the filename and linenumber to improve error-reporting.  */
9412   saved_loc = input_location;
9413   input_location = DECL_SOURCE_LOCATION (t);
9414
9415   switch (TREE_CODE (t))
9416     {
9417     case TEMPLATE_DECL:
9418       {
9419         /* We can get here when processing a member function template,
9420            member class template, or template template parameter.  */
9421         tree decl = DECL_TEMPLATE_RESULT (t);
9422         tree spec;
9423         tree tmpl_args;
9424         tree full_args;
9425
9426         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9427           {
9428             /* Template template parameter is treated here.  */
9429             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9430             if (new_type == error_mark_node)
9431               RETURN (error_mark_node);
9432
9433             r = copy_decl (t);
9434             DECL_CHAIN (r) = NULL_TREE;
9435             TREE_TYPE (r) = new_type;
9436             DECL_TEMPLATE_RESULT (r)
9437               = build_decl (DECL_SOURCE_LOCATION (decl),
9438                             TYPE_DECL, DECL_NAME (decl), new_type);
9439             DECL_TEMPLATE_PARMS (r)
9440               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9441                                        complain);
9442             TYPE_NAME (new_type) = r;
9443             break;
9444           }
9445
9446         /* We might already have an instance of this template.
9447            The ARGS are for the surrounding class type, so the
9448            full args contain the tsubst'd args for the context,
9449            plus the innermost args from the template decl.  */
9450         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9451           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9452           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9453         /* Because this is a template, the arguments will still be
9454            dependent, even after substitution.  If
9455            PROCESSING_TEMPLATE_DECL is not set, the dependency
9456            predicates will short-circuit.  */
9457         ++processing_template_decl;
9458         full_args = tsubst_template_args (tmpl_args, args,
9459                                           complain, in_decl);
9460         --processing_template_decl;
9461         if (full_args == error_mark_node)
9462           RETURN (error_mark_node);
9463
9464         /* If this is a default template template argument,
9465            tsubst might not have changed anything.  */
9466         if (full_args == tmpl_args)
9467           RETURN (t);
9468
9469         hash = hash_tmpl_and_args (t, full_args);
9470         spec = retrieve_specialization (t, full_args, hash);
9471         if (spec != NULL_TREE)
9472           {
9473             r = spec;
9474             break;
9475           }
9476
9477         /* Make a new template decl.  It will be similar to the
9478            original, but will record the current template arguments.
9479            We also create a new function declaration, which is just
9480            like the old one, but points to this new template, rather
9481            than the old one.  */
9482         r = copy_decl (t);
9483         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9484         DECL_CHAIN (r) = NULL_TREE;
9485
9486         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9487
9488         if (TREE_CODE (decl) == TYPE_DECL)
9489           {
9490             tree new_type;
9491             ++processing_template_decl;
9492             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9493             --processing_template_decl;
9494             if (new_type == error_mark_node)
9495               RETURN (error_mark_node);
9496
9497             TREE_TYPE (r) = new_type;
9498             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9499             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9500             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9501             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9502           }
9503         else
9504           {
9505             tree new_decl;
9506             ++processing_template_decl;
9507             new_decl = tsubst (decl, args, complain, in_decl);
9508             --processing_template_decl;
9509             if (new_decl == error_mark_node)
9510               RETURN (error_mark_node);
9511
9512             DECL_TEMPLATE_RESULT (r) = new_decl;
9513             DECL_TI_TEMPLATE (new_decl) = r;
9514             TREE_TYPE (r) = TREE_TYPE (new_decl);
9515             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9516             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9517           }
9518
9519         SET_DECL_IMPLICIT_INSTANTIATION (r);
9520         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9521         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9522
9523         /* The template parameters for this new template are all the
9524            template parameters for the old template, except the
9525            outermost level of parameters.  */
9526         DECL_TEMPLATE_PARMS (r)
9527           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9528                                    complain);
9529
9530         if (PRIMARY_TEMPLATE_P (t))
9531           DECL_PRIMARY_TEMPLATE (r) = r;
9532
9533         if (TREE_CODE (decl) != TYPE_DECL)
9534           /* Record this non-type partial instantiation.  */
9535           register_specialization (r, t,
9536                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9537                                    false, hash);
9538       }
9539       break;
9540
9541     case FUNCTION_DECL:
9542       {
9543         tree ctx;
9544         tree argvec = NULL_TREE;
9545         tree *friends;
9546         tree gen_tmpl;
9547         tree type;
9548         int member;
9549         int args_depth;
9550         int parms_depth;
9551
9552         /* Nobody should be tsubst'ing into non-template functions.  */
9553         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9554
9555         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9556           {
9557             tree spec;
9558             bool dependent_p;
9559
9560             /* If T is not dependent, just return it.  We have to
9561                increment PROCESSING_TEMPLATE_DECL because
9562                value_dependent_expression_p assumes that nothing is
9563                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9564             ++processing_template_decl;
9565             dependent_p = value_dependent_expression_p (t);
9566             --processing_template_decl;
9567             if (!dependent_p)
9568               RETURN (t);
9569
9570             /* Calculate the most general template of which R is a
9571                specialization, and the complete set of arguments used to
9572                specialize R.  */
9573             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9574             argvec = tsubst_template_args (DECL_TI_ARGS
9575                                           (DECL_TEMPLATE_RESULT
9576                                                  (DECL_TI_TEMPLATE (t))),
9577                                            args, complain, in_decl);
9578             if (argvec == error_mark_node)
9579               RETURN (error_mark_node);
9580
9581             /* Check to see if we already have this specialization.  */
9582             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9583             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9584
9585             if (spec)
9586               {
9587                 r = spec;
9588                 break;
9589               }
9590
9591             /* We can see more levels of arguments than parameters if
9592                there was a specialization of a member template, like
9593                this:
9594
9595                  template <class T> struct S { template <class U> void f(); }
9596                  template <> template <class U> void S<int>::f(U);
9597
9598                Here, we'll be substituting into the specialization,
9599                because that's where we can find the code we actually
9600                want to generate, but we'll have enough arguments for
9601                the most general template.
9602
9603                We also deal with the peculiar case:
9604
9605                  template <class T> struct S {
9606                    template <class U> friend void f();
9607                  };
9608                  template <class U> void f() {}
9609                  template S<int>;
9610                  template void f<double>();
9611
9612                Here, the ARGS for the instantiation of will be {int,
9613                double}.  But, we only need as many ARGS as there are
9614                levels of template parameters in CODE_PATTERN.  We are
9615                careful not to get fooled into reducing the ARGS in
9616                situations like:
9617
9618                  template <class T> struct S { template <class U> void f(U); }
9619                  template <class T> template <> void S<T>::f(int) {}
9620
9621                which we can spot because the pattern will be a
9622                specialization in this case.  */
9623             args_depth = TMPL_ARGS_DEPTH (args);
9624             parms_depth =
9625               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9626             if (args_depth > parms_depth
9627                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9628               args = get_innermost_template_args (args, parms_depth);
9629           }
9630         else
9631           {
9632             /* This special case arises when we have something like this:
9633
9634                  template <class T> struct S {
9635                    friend void f<int>(int, double);
9636                  };
9637
9638                Here, the DECL_TI_TEMPLATE for the friend declaration
9639                will be an IDENTIFIER_NODE.  We are being called from
9640                tsubst_friend_function, and we want only to create a
9641                new decl (R) with appropriate types so that we can call
9642                determine_specialization.  */
9643             gen_tmpl = NULL_TREE;
9644           }
9645
9646         if (DECL_CLASS_SCOPE_P (t))
9647           {
9648             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9649               member = 2;
9650             else
9651               member = 1;
9652             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9653                                     complain, t, /*entering_scope=*/1);
9654           }
9655         else
9656           {
9657             member = 0;
9658             ctx = DECL_CONTEXT (t);
9659           }
9660         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9661         if (type == error_mark_node)
9662           RETURN (error_mark_node);
9663
9664         /* We do NOT check for matching decls pushed separately at this
9665            point, as they may not represent instantiations of this
9666            template, and in any case are considered separate under the
9667            discrete model.  */
9668         r = copy_decl (t);
9669         DECL_USE_TEMPLATE (r) = 0;
9670         TREE_TYPE (r) = type;
9671         /* Clear out the mangled name and RTL for the instantiation.  */
9672         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9673         SET_DECL_RTL (r, NULL);
9674         /* Leave DECL_INITIAL set on deleted instantiations.  */
9675         if (!DECL_DELETED_FN (r))
9676           DECL_INITIAL (r) = NULL_TREE;
9677         DECL_CONTEXT (r) = ctx;
9678
9679         if (member && DECL_CONV_FN_P (r))
9680           /* Type-conversion operator.  Reconstruct the name, in
9681              case it's the name of one of the template's parameters.  */
9682           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9683
9684         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9685                                      complain, t);
9686         DECL_RESULT (r) = NULL_TREE;
9687
9688         TREE_STATIC (r) = 0;
9689         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9690         DECL_EXTERNAL (r) = 1;
9691         /* If this is an instantiation of a function with internal
9692            linkage, we already know what object file linkage will be
9693            assigned to the instantiation.  */
9694         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9695         DECL_DEFER_OUTPUT (r) = 0;
9696         DECL_CHAIN (r) = NULL_TREE;
9697         DECL_PENDING_INLINE_INFO (r) = 0;
9698         DECL_PENDING_INLINE_P (r) = 0;
9699         DECL_SAVED_TREE (r) = NULL_TREE;
9700         DECL_STRUCT_FUNCTION (r) = NULL;
9701         TREE_USED (r) = 0;
9702         /* We'll re-clone as appropriate in instantiate_template.  */
9703         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9704
9705         /* If we aren't complaining now, return on error before we register
9706            the specialization so that we'll complain eventually.  */
9707         if ((complain & tf_error) == 0
9708             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9709             && !grok_op_properties (r, /*complain=*/false))
9710           RETURN (error_mark_node);
9711
9712         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9713            this in the special friend case mentioned above where
9714            GEN_TMPL is NULL.  */
9715         if (gen_tmpl)
9716           {
9717             DECL_TEMPLATE_INFO (r)
9718               = build_template_info (gen_tmpl, argvec);
9719             SET_DECL_IMPLICIT_INSTANTIATION (r);
9720             register_specialization (r, gen_tmpl, argvec, false, hash);
9721
9722             /* We're not supposed to instantiate default arguments
9723                until they are called, for a template.  But, for a
9724                declaration like:
9725
9726                  template <class T> void f ()
9727                  { extern void g(int i = T()); }
9728
9729                we should do the substitution when the template is
9730                instantiated.  We handle the member function case in
9731                instantiate_class_template since the default arguments
9732                might refer to other members of the class.  */
9733             if (!member
9734                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9735                 && !uses_template_parms (argvec))
9736               tsubst_default_arguments (r);
9737           }
9738         else
9739           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9740
9741         /* Copy the list of befriending classes.  */
9742         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9743              *friends;
9744              friends = &TREE_CHAIN (*friends))
9745           {
9746             *friends = copy_node (*friends);
9747             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9748                                             args, complain,
9749                                             in_decl);
9750           }
9751
9752         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9753           {
9754             maybe_retrofit_in_chrg (r);
9755             if (DECL_CONSTRUCTOR_P (r))
9756               grok_ctor_properties (ctx, r);
9757             /* If this is an instantiation of a member template, clone it.
9758                If it isn't, that'll be handled by
9759                clone_constructors_and_destructors.  */
9760             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9761               clone_function_decl (r, /*update_method_vec_p=*/0);
9762           }
9763         else if ((complain & tf_error) != 0
9764                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9765                  && !grok_op_properties (r, /*complain=*/true))
9766           RETURN (error_mark_node);
9767
9768         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9769           SET_DECL_FRIEND_CONTEXT (r,
9770                                    tsubst (DECL_FRIEND_CONTEXT (t),
9771                                             args, complain, in_decl));
9772
9773         /* Possibly limit visibility based on template args.  */
9774         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9775         if (DECL_VISIBILITY_SPECIFIED (t))
9776           {
9777             DECL_VISIBILITY_SPECIFIED (r) = 0;
9778             DECL_ATTRIBUTES (r)
9779               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9780           }
9781         determine_visibility (r);
9782         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9783             && !processing_template_decl)
9784           defaulted_late_check (r);
9785
9786         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9787                                         args, complain, in_decl);
9788       }
9789       break;
9790
9791     case PARM_DECL:
9792       {
9793         tree type = NULL_TREE;
9794         int i, len = 1;
9795         tree expanded_types = NULL_TREE;
9796         tree prev_r = NULL_TREE;
9797         tree first_r = NULL_TREE;
9798
9799         if (FUNCTION_PARAMETER_PACK_P (t))
9800           {
9801             /* If there is a local specialization that isn't a
9802                parameter pack, it means that we're doing a "simple"
9803                substitution from inside tsubst_pack_expansion. Just
9804                return the local specialization (which will be a single
9805                parm).  */
9806             tree spec = retrieve_local_specialization (t);
9807             if (spec 
9808                 && TREE_CODE (spec) == PARM_DECL
9809                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9810               RETURN (spec);
9811
9812             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9813                the parameters in this function parameter pack.  */
9814             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9815                                                     complain, in_decl);
9816             if (TREE_CODE (expanded_types) == TREE_VEC)
9817               {
9818                 len = TREE_VEC_LENGTH (expanded_types);
9819
9820                 /* Zero-length parameter packs are boring. Just substitute
9821                    into the chain.  */
9822                 if (len == 0)
9823                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9824                                   TREE_CHAIN (t)));
9825               }
9826             else
9827               {
9828                 /* All we did was update the type. Make a note of that.  */
9829                 type = expanded_types;
9830                 expanded_types = NULL_TREE;
9831               }
9832           }
9833
9834         /* Loop through all of the parameter's we'll build. When T is
9835            a function parameter pack, LEN is the number of expanded
9836            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9837         r = NULL_TREE;
9838         for (i = 0; i < len; ++i)
9839           {
9840             prev_r = r;
9841             r = copy_node (t);
9842             if (DECL_TEMPLATE_PARM_P (t))
9843               SET_DECL_TEMPLATE_PARM_P (r);
9844
9845             if (expanded_types)
9846               /* We're on the Ith parameter of the function parameter
9847                  pack.  */
9848               {
9849                 /* An argument of a function parameter pack is not a parameter
9850                    pack.  */
9851                 FUNCTION_PARAMETER_PACK_P (r) = false;
9852
9853                 /* Get the Ith type.  */
9854                 type = TREE_VEC_ELT (expanded_types, i);
9855
9856                 if (DECL_NAME (r))
9857                   /* Rename the parameter to include the index.  */
9858                   DECL_NAME (r) =
9859                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9860               }
9861             else if (!type)
9862               /* We're dealing with a normal parameter.  */
9863               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9864
9865             type = type_decays_to (type);
9866             TREE_TYPE (r) = type;
9867             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9868
9869             if (DECL_INITIAL (r))
9870               {
9871                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9872                   DECL_INITIAL (r) = TREE_TYPE (r);
9873                 else
9874                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9875                                              complain, in_decl);
9876               }
9877
9878             DECL_CONTEXT (r) = NULL_TREE;
9879
9880             if (!DECL_TEMPLATE_PARM_P (r))
9881               DECL_ARG_TYPE (r) = type_passed_as (type);
9882
9883             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9884                                             args, complain, in_decl);
9885
9886             /* Keep track of the first new parameter we
9887                generate. That's what will be returned to the
9888                caller.  */
9889             if (!first_r)
9890               first_r = r;
9891
9892             /* Build a proper chain of parameters when substituting
9893                into a function parameter pack.  */
9894             if (prev_r)
9895               DECL_CHAIN (prev_r) = r;
9896           }
9897
9898         if (DECL_CHAIN (t))
9899           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
9900                                    complain, DECL_CHAIN (t));
9901
9902         /* FIRST_R contains the start of the chain we've built.  */
9903         r = first_r;
9904       }
9905       break;
9906
9907     case FIELD_DECL:
9908       {
9909         tree type;
9910
9911         r = copy_decl (t);
9912         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9913         if (type == error_mark_node)
9914           RETURN (error_mark_node);
9915         TREE_TYPE (r) = type;
9916         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9917
9918         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9919         DECL_INITIAL (r)
9920           = tsubst_expr (DECL_INITIAL (t), args,
9921                          complain, in_decl,
9922                          /*integral_constant_expression_p=*/true);
9923         /* We don't have to set DECL_CONTEXT here; it is set by
9924            finish_member_declaration.  */
9925         DECL_CHAIN (r) = NULL_TREE;
9926         if (VOID_TYPE_P (type))
9927           error ("instantiation of %q+D as type %qT", r, type);
9928
9929         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9930                                         args, complain, in_decl);
9931       }
9932       break;
9933
9934     case USING_DECL:
9935       /* We reach here only for member using decls.  */
9936       if (DECL_DEPENDENT_P (t))
9937         {
9938           r = do_class_using_decl
9939             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9940              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9941           if (!r)
9942             r = error_mark_node;
9943           else
9944             {
9945               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9946               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9947             }
9948         }
9949       else
9950         {
9951           r = copy_node (t);
9952           DECL_CHAIN (r) = NULL_TREE;
9953         }
9954       break;
9955
9956     case TYPE_DECL:
9957     case VAR_DECL:
9958       {
9959         tree argvec = NULL_TREE;
9960         tree gen_tmpl = NULL_TREE;
9961         tree spec;
9962         tree tmpl = NULL_TREE;
9963         tree ctx;
9964         tree type = NULL_TREE;
9965         bool local_p;
9966
9967         if (TREE_CODE (t) == TYPE_DECL
9968             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9969           {
9970             /* If this is the canonical decl, we don't have to
9971                mess with instantiations, and often we can't (for
9972                typename, template type parms and such).  Note that
9973                TYPE_NAME is not correct for the above test if
9974                we've copied the type for a typedef.  */
9975             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9976             if (type == error_mark_node)
9977               RETURN (error_mark_node);
9978             r = TYPE_NAME (type);
9979             break;
9980           }
9981
9982         /* Check to see if we already have the specialization we
9983            need.  */
9984         spec = NULL_TREE;
9985         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9986           {
9987             /* T is a static data member or namespace-scope entity.
9988                We have to substitute into namespace-scope variables
9989                (even though such entities are never templates) because
9990                of cases like:
9991                
9992                  template <class T> void f() { extern T t; }
9993
9994                where the entity referenced is not known until
9995                instantiation time.  */
9996             local_p = false;
9997             ctx = DECL_CONTEXT (t);
9998             if (DECL_CLASS_SCOPE_P (t))
9999               {
10000                 ctx = tsubst_aggr_type (ctx, args,
10001                                         complain,
10002                                         in_decl, /*entering_scope=*/1);
10003                 /* If CTX is unchanged, then T is in fact the
10004                    specialization we want.  That situation occurs when
10005                    referencing a static data member within in its own
10006                    class.  We can use pointer equality, rather than
10007                    same_type_p, because DECL_CONTEXT is always
10008                    canonical.  */
10009                 if (ctx == DECL_CONTEXT (t))
10010                   spec = t;
10011               }
10012
10013             if (!spec)
10014               {
10015                 tmpl = DECL_TI_TEMPLATE (t);
10016                 gen_tmpl = most_general_template (tmpl);
10017                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
10018                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
10019                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
10020               }
10021           }
10022         else
10023           {
10024             /* A local variable.  */
10025             local_p = true;
10026             /* Subsequent calls to pushdecl will fill this in.  */
10027             ctx = NULL_TREE;
10028             spec = retrieve_local_specialization (t);
10029           }
10030         /* If we already have the specialization we need, there is
10031            nothing more to do.  */ 
10032         if (spec)
10033           {
10034             r = spec;
10035             break;
10036           }
10037
10038         /* Create a new node for the specialization we need.  */
10039         r = copy_decl (t);
10040         if (type == NULL_TREE)
10041           {
10042             if (is_typedef_decl (t))
10043               type = DECL_ORIGINAL_TYPE (t);
10044             else
10045               type = TREE_TYPE (t);
10046             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
10047               type = strip_array_domain (type);
10048             type = tsubst (type, args, complain, in_decl);
10049           }
10050         if (TREE_CODE (r) == VAR_DECL)
10051           {
10052             /* Even if the original location is out of scope, the
10053                newly substituted one is not.  */
10054             DECL_DEAD_FOR_LOCAL (r) = 0;
10055             DECL_INITIALIZED_P (r) = 0;
10056             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10057             if (type == error_mark_node)
10058               RETURN (error_mark_node);
10059             if (TREE_CODE (type) == FUNCTION_TYPE)
10060               {
10061                 /* It may seem that this case cannot occur, since:
10062
10063                      typedef void f();
10064                      void g() { f x; }
10065
10066                    declares a function, not a variable.  However:
10067       
10068                      typedef void f();
10069                      template <typename T> void g() { T t; }
10070                      template void g<f>();
10071
10072                    is an attempt to declare a variable with function
10073                    type.  */
10074                 error ("variable %qD has function type",
10075                        /* R is not yet sufficiently initialized, so we
10076                           just use its name.  */
10077                        DECL_NAME (r));
10078                 RETURN (error_mark_node);
10079               }
10080             type = complete_type (type);
10081             /* Wait until cp_finish_decl to set this again, to handle
10082                circular dependency (template/instantiate6.C). */
10083             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10084             type = check_var_type (DECL_NAME (r), type);
10085
10086             if (DECL_HAS_VALUE_EXPR_P (t))
10087               {
10088                 tree ve = DECL_VALUE_EXPR (t);
10089                 ve = tsubst_expr (ve, args, complain, in_decl,
10090                                   /*constant_expression_p=*/false);
10091                 if (REFERENCE_REF_P (ve))
10092                   {
10093                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
10094                     ve = TREE_OPERAND (ve, 0);
10095                   }
10096                 SET_DECL_VALUE_EXPR (r, ve);
10097               }
10098           }
10099         else if (DECL_SELF_REFERENCE_P (t))
10100           SET_DECL_SELF_REFERENCE_P (r);
10101         TREE_TYPE (r) = type;
10102         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10103         DECL_CONTEXT (r) = ctx;
10104         /* Clear out the mangled name and RTL for the instantiation.  */
10105         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10106         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10107           SET_DECL_RTL (r, NULL);
10108         /* The initializer must not be expanded until it is required;
10109            see [temp.inst].  */
10110         DECL_INITIAL (r) = NULL_TREE;
10111         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10112           SET_DECL_RTL (r, NULL);
10113         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10114         if (TREE_CODE (r) == VAR_DECL)
10115           {
10116             /* Possibly limit visibility based on template args.  */
10117             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10118             if (DECL_VISIBILITY_SPECIFIED (t))
10119               {
10120                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10121                 DECL_ATTRIBUTES (r)
10122                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10123               }
10124             determine_visibility (r);
10125           }
10126
10127         if (!local_p)
10128           {
10129             /* A static data member declaration is always marked
10130                external when it is declared in-class, even if an
10131                initializer is present.  We mimic the non-template
10132                processing here.  */
10133             DECL_EXTERNAL (r) = 1;
10134
10135             register_specialization (r, gen_tmpl, argvec, false, hash);
10136             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10137             SET_DECL_IMPLICIT_INSTANTIATION (r);
10138           }
10139         else if (cp_unevaluated_operand)
10140           {
10141             /* We're substituting this var in a decltype outside of its
10142                scope, such as for a lambda return type.  Don't add it to
10143                local_specializations, do perform auto deduction.  */
10144             tree auto_node = type_uses_auto (type);
10145             if (auto_node)
10146               {
10147                 tree init
10148                   = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10149                                  /*constant_expression_p=*/false);
10150                 init = resolve_nondeduced_context (init);
10151                 TREE_TYPE (r) = type
10152                   = do_auto_deduction (type, init, auto_node);
10153               }
10154           }
10155         else
10156           register_local_specialization (r, t);
10157
10158         DECL_CHAIN (r) = NULL_TREE;
10159
10160         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10161                                         /*flags=*/0,
10162                                         args, complain, in_decl);
10163
10164         /* Preserve a typedef that names a type.  */
10165         if (is_typedef_decl (r))
10166           {
10167             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10168             set_underlying_type (r);
10169           }
10170
10171         layout_decl (r, 0);
10172       }
10173       break;
10174
10175     default:
10176       gcc_unreachable ();
10177     }
10178 #undef RETURN
10179
10180  out:
10181   /* Restore the file and line information.  */
10182   input_location = saved_loc;
10183
10184   return r;
10185 }
10186
10187 /* Substitute into the ARG_TYPES of a function type.  */
10188
10189 static tree
10190 tsubst_arg_types (tree arg_types,
10191                   tree args,
10192                   tsubst_flags_t complain,
10193                   tree in_decl)
10194 {
10195   tree remaining_arg_types;
10196   tree type = NULL_TREE;
10197   int i = 1;
10198   tree expanded_args = NULL_TREE;
10199   tree default_arg;
10200
10201   if (!arg_types || arg_types == void_list_node)
10202     return arg_types;
10203
10204   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10205                                           args, complain, in_decl);
10206   if (remaining_arg_types == error_mark_node)
10207     return error_mark_node;
10208
10209   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10210     {
10211       /* For a pack expansion, perform substitution on the
10212          entire expression. Later on, we'll handle the arguments
10213          one-by-one.  */
10214       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10215                                             args, complain, in_decl);
10216
10217       if (TREE_CODE (expanded_args) == TREE_VEC)
10218         /* So that we'll spin through the parameters, one by one.  */
10219         i = TREE_VEC_LENGTH (expanded_args);
10220       else
10221         {
10222           /* We only partially substituted into the parameter
10223              pack. Our type is TYPE_PACK_EXPANSION.  */
10224           type = expanded_args;
10225           expanded_args = NULL_TREE;
10226         }
10227     }
10228
10229   while (i > 0) {
10230     --i;
10231     
10232     if (expanded_args)
10233       type = TREE_VEC_ELT (expanded_args, i);
10234     else if (!type)
10235       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10236
10237     if (type == error_mark_node)
10238       return error_mark_node;
10239     if (VOID_TYPE_P (type))
10240       {
10241         if (complain & tf_error)
10242           {
10243             error ("invalid parameter type %qT", type);
10244             if (in_decl)
10245               error ("in declaration %q+D", in_decl);
10246           }
10247         return error_mark_node;
10248     }
10249     
10250     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10251        top-level qualifiers as required.  */
10252     type = cv_unqualified (type_decays_to (type));
10253
10254     /* We do not substitute into default arguments here.  The standard
10255        mandates that they be instantiated only when needed, which is
10256        done in build_over_call.  */
10257     default_arg = TREE_PURPOSE (arg_types);
10258
10259     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10260       {
10261         /* We've instantiated a template before its default arguments
10262            have been parsed.  This can happen for a nested template
10263            class, and is not an error unless we require the default
10264            argument in a call of this function.  */
10265         remaining_arg_types = 
10266           tree_cons (default_arg, type, remaining_arg_types);
10267         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10268                        remaining_arg_types);
10269       }
10270     else
10271       remaining_arg_types = 
10272         hash_tree_cons (default_arg, type, remaining_arg_types);
10273   }
10274         
10275   return remaining_arg_types;
10276 }
10277
10278 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10279    *not* handle the exception-specification for FNTYPE, because the
10280    initial substitution of explicitly provided template parameters
10281    during argument deduction forbids substitution into the
10282    exception-specification:
10283
10284      [temp.deduct]
10285
10286      All references in the function type of the function template to  the
10287      corresponding template parameters are replaced by the specified tem-
10288      plate argument values.  If a substitution in a template parameter or
10289      in  the function type of the function template results in an invalid
10290      type, type deduction fails.  [Note: The equivalent  substitution  in
10291      exception specifications is done only when the function is instanti-
10292      ated, at which point a program is  ill-formed  if  the  substitution
10293      results in an invalid type.]  */
10294
10295 static tree
10296 tsubst_function_type (tree t,
10297                       tree args,
10298                       tsubst_flags_t complain,
10299                       tree in_decl)
10300 {
10301   tree return_type;
10302   tree arg_types;
10303   tree fntype;
10304
10305   /* The TYPE_CONTEXT is not used for function/method types.  */
10306   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10307
10308   /* Substitute the return type.  */
10309   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10310   if (return_type == error_mark_node)
10311     return error_mark_node;
10312   /* The standard does not presently indicate that creation of a
10313      function type with an invalid return type is a deduction failure.
10314      However, that is clearly analogous to creating an array of "void"
10315      or a reference to a reference.  This is core issue #486.  */
10316   if (TREE_CODE (return_type) == ARRAY_TYPE
10317       || TREE_CODE (return_type) == FUNCTION_TYPE)
10318     {
10319       if (complain & tf_error)
10320         {
10321           if (TREE_CODE (return_type) == ARRAY_TYPE)
10322             error ("function returning an array");
10323           else
10324             error ("function returning a function");
10325         }
10326       return error_mark_node;
10327     }
10328
10329   /* Substitute the argument types.  */
10330   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10331                                 complain, in_decl);
10332   if (arg_types == error_mark_node)
10333     return error_mark_node;
10334
10335   /* Construct a new type node and return it.  */
10336   if (TREE_CODE (t) == FUNCTION_TYPE)
10337     {
10338       fntype = build_function_type (return_type, arg_types);
10339       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10340     }
10341   else
10342     {
10343       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10344       if (! MAYBE_CLASS_TYPE_P (r))
10345         {
10346           /* [temp.deduct]
10347
10348              Type deduction may fail for any of the following
10349              reasons:
10350
10351              -- Attempting to create "pointer to member of T" when T
10352              is not a class type.  */
10353           if (complain & tf_error)
10354             error ("creating pointer to member function of non-class type %qT",
10355                       r);
10356           return error_mark_node;
10357         }
10358
10359       fntype = build_method_type_directly (r, return_type,
10360                                            TREE_CHAIN (arg_types));
10361     }
10362   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10363
10364   return fntype;
10365 }
10366
10367 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10368    ARGS into that specification, and return the substituted
10369    specification.  If there is no specification, return NULL_TREE.  */
10370
10371 static tree
10372 tsubst_exception_specification (tree fntype,
10373                                 tree args,
10374                                 tsubst_flags_t complain,
10375                                 tree in_decl,
10376                                 bool defer_ok)
10377 {
10378   tree specs;
10379   tree new_specs;
10380
10381   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10382   new_specs = NULL_TREE;
10383   if (specs && TREE_PURPOSE (specs))
10384     {
10385       /* A noexcept-specifier.  */
10386       tree expr = TREE_PURPOSE (specs);
10387       if (expr == boolean_true_node || expr == boolean_false_node)
10388         new_specs = expr;
10389       else if (defer_ok)
10390         {
10391           /* Defer instantiation of noexcept-specifiers to avoid
10392              excessive instantiations (c++/49107).  */
10393           new_specs = make_node (DEFERRED_NOEXCEPT);
10394           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
10395             {
10396               /* We already partially instantiated this member template,
10397                  so combine the new args with the old.  */
10398               DEFERRED_NOEXCEPT_PATTERN (new_specs)
10399                 = DEFERRED_NOEXCEPT_PATTERN (expr);
10400               DEFERRED_NOEXCEPT_ARGS (new_specs)
10401                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
10402             }
10403           else
10404             {
10405               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
10406               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
10407             }
10408         }
10409       else
10410         new_specs = tsubst_copy_and_build
10411           (expr, args, complain, in_decl, /*function_p=*/false,
10412            /*integral_constant_expression_p=*/true);
10413       new_specs = build_noexcept_spec (new_specs, complain);
10414     }
10415   else if (specs)
10416     {
10417       if (! TREE_VALUE (specs))
10418         new_specs = specs;
10419       else
10420         while (specs)
10421           {
10422             tree spec;
10423             int i, len = 1;
10424             tree expanded_specs = NULL_TREE;
10425
10426             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10427               {
10428                 /* Expand the pack expansion type.  */
10429                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10430                                                        args, complain,
10431                                                        in_decl);
10432
10433                 if (expanded_specs == error_mark_node)
10434                   return error_mark_node;
10435                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10436                   len = TREE_VEC_LENGTH (expanded_specs);
10437                 else
10438                   {
10439                     /* We're substituting into a member template, so
10440                        we got a TYPE_PACK_EXPANSION back.  Add that
10441                        expansion and move on.  */
10442                     gcc_assert (TREE_CODE (expanded_specs) 
10443                                 == TYPE_PACK_EXPANSION);
10444                     new_specs = add_exception_specifier (new_specs,
10445                                                          expanded_specs,
10446                                                          complain);
10447                     specs = TREE_CHAIN (specs);
10448                     continue;
10449                   }
10450               }
10451
10452             for (i = 0; i < len; ++i)
10453               {
10454                 if (expanded_specs)
10455                   spec = TREE_VEC_ELT (expanded_specs, i);
10456                 else
10457                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10458                 if (spec == error_mark_node)
10459                   return spec;
10460                 new_specs = add_exception_specifier (new_specs, spec, 
10461                                                      complain);
10462               }
10463
10464             specs = TREE_CHAIN (specs);
10465           }
10466     }
10467   return new_specs;
10468 }
10469
10470 /* Take the tree structure T and replace template parameters used
10471    therein with the argument vector ARGS.  IN_DECL is an associated
10472    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10473    Issue error and warning messages under control of COMPLAIN.  Note
10474    that we must be relatively non-tolerant of extensions here, in
10475    order to preserve conformance; if we allow substitutions that
10476    should not be allowed, we may allow argument deductions that should
10477    not succeed, and therefore report ambiguous overload situations
10478    where there are none.  In theory, we could allow the substitution,
10479    but indicate that it should have failed, and allow our caller to
10480    make sure that the right thing happens, but we don't try to do this
10481    yet.
10482
10483    This function is used for dealing with types, decls and the like;
10484    for expressions, use tsubst_expr or tsubst_copy.  */
10485
10486 tree
10487 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10488 {
10489   enum tree_code code;
10490   tree type, r;
10491
10492   if (t == NULL_TREE || t == error_mark_node
10493       || t == integer_type_node
10494       || t == void_type_node
10495       || t == char_type_node
10496       || t == unknown_type_node
10497       || TREE_CODE (t) == NAMESPACE_DECL
10498       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10499     return t;
10500
10501   if (DECL_P (t))
10502     return tsubst_decl (t, args, complain);
10503
10504   if (args == NULL_TREE)
10505     return t;
10506
10507   code = TREE_CODE (t);
10508
10509   if (code == IDENTIFIER_NODE)
10510     type = IDENTIFIER_TYPE_VALUE (t);
10511   else
10512     type = TREE_TYPE (t);
10513
10514   gcc_assert (type != unknown_type_node);
10515
10516   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10517      such as attribute aligned.  */
10518   if (TYPE_P (t)
10519       && typedef_variant_p (t))
10520     {
10521       tree decl = TYPE_NAME (t);
10522       
10523       if (DECL_CLASS_SCOPE_P (decl)
10524           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10525           && uses_template_parms (DECL_CONTEXT (decl)))
10526         {
10527           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10528           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10529           r = retrieve_specialization (tmpl, gen_args, 0);
10530         }
10531       else if (DECL_FUNCTION_SCOPE_P (decl)
10532                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10533                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10534         r = retrieve_local_specialization (decl);
10535       else
10536         /* The typedef is from a non-template context.  */
10537         return t;
10538
10539       if (r)
10540         {
10541           r = TREE_TYPE (r);
10542           r = cp_build_qualified_type_real
10543             (r, cp_type_quals (t) | cp_type_quals (r),
10544              complain | tf_ignore_bad_quals);
10545           return r;
10546         }
10547       /* Else we must be instantiating the typedef, so fall through.  */
10548     }
10549
10550   if (type
10551       && code != TYPENAME_TYPE
10552       && code != TEMPLATE_TYPE_PARM
10553       && code != IDENTIFIER_NODE
10554       && code != FUNCTION_TYPE
10555       && code != METHOD_TYPE)
10556     type = tsubst (type, args, complain, in_decl);
10557   if (type == error_mark_node)
10558     return error_mark_node;
10559
10560   switch (code)
10561     {
10562     case RECORD_TYPE:
10563     case UNION_TYPE:
10564     case ENUMERAL_TYPE:
10565       return tsubst_aggr_type (t, args, complain, in_decl,
10566                                /*entering_scope=*/0);
10567
10568     case ERROR_MARK:
10569     case IDENTIFIER_NODE:
10570     case VOID_TYPE:
10571     case REAL_TYPE:
10572     case COMPLEX_TYPE:
10573     case VECTOR_TYPE:
10574     case BOOLEAN_TYPE:
10575     case NULLPTR_TYPE:
10576     case LANG_TYPE:
10577       return t;
10578
10579     case INTEGER_TYPE:
10580       if (t == integer_type_node)
10581         return t;
10582
10583       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10584           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10585         return t;
10586
10587       {
10588         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10589
10590         max = tsubst_expr (omax, args, complain, in_decl,
10591                            /*integral_constant_expression_p=*/false);
10592
10593         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10594            needed.  */
10595         if (TREE_CODE (max) == NOP_EXPR
10596             && TREE_SIDE_EFFECTS (omax)
10597             && !TREE_TYPE (max))
10598           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10599
10600         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10601            with TREE_SIDE_EFFECTS that indicates this is not an integral
10602            constant expression.  */
10603         if (processing_template_decl
10604             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10605           {
10606             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10607             TREE_SIDE_EFFECTS (max) = 1;
10608           }
10609
10610         return compute_array_index_type (NULL_TREE, max, complain);
10611       }
10612
10613     case TEMPLATE_TYPE_PARM:
10614     case TEMPLATE_TEMPLATE_PARM:
10615     case BOUND_TEMPLATE_TEMPLATE_PARM:
10616     case TEMPLATE_PARM_INDEX:
10617       {
10618         int idx;
10619         int level;
10620         int levels;
10621         tree arg = NULL_TREE;
10622
10623         r = NULL_TREE;
10624
10625         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10626         template_parm_level_and_index (t, &level, &idx); 
10627
10628         levels = TMPL_ARGS_DEPTH (args);
10629         if (level <= levels)
10630           {
10631             arg = TMPL_ARG (args, level, idx);
10632
10633             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10634               /* See through ARGUMENT_PACK_SELECT arguments. */
10635               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10636           }
10637
10638         if (arg == error_mark_node)
10639           return error_mark_node;
10640         else if (arg != NULL_TREE)
10641           {
10642             if (ARGUMENT_PACK_P (arg))
10643               /* If ARG is an argument pack, we don't actually want to
10644                  perform a substitution here, because substitutions
10645                  for argument packs are only done
10646                  element-by-element. We can get to this point when
10647                  substituting the type of a non-type template
10648                  parameter pack, when that type actually contains
10649                  template parameter packs from an outer template, e.g.,
10650
10651                  template<typename... Types> struct A {
10652                    template<Types... Values> struct B { };
10653                  };  */
10654               return t;
10655
10656             if (code == TEMPLATE_TYPE_PARM)
10657               {
10658                 int quals;
10659                 gcc_assert (TYPE_P (arg));
10660
10661                 quals = cp_type_quals (arg) | cp_type_quals (t);
10662                   
10663                 return cp_build_qualified_type_real
10664                   (arg, quals, complain | tf_ignore_bad_quals);
10665               }
10666             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10667               {
10668                 /* We are processing a type constructed from a
10669                    template template parameter.  */
10670                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10671                                       args, complain, in_decl);
10672                 if (argvec == error_mark_node)
10673                   return error_mark_node;
10674
10675                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10676                    are resolving nested-types in the signature of a
10677                    member function templates.  Otherwise ARG is a
10678                    TEMPLATE_DECL and is the real template to be
10679                    instantiated.  */
10680                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10681                   arg = TYPE_NAME (arg);
10682
10683                 r = lookup_template_class (arg,
10684                                            argvec, in_decl,
10685                                            DECL_CONTEXT (arg),
10686                                             /*entering_scope=*/0,
10687                                            complain);
10688                 return cp_build_qualified_type_real
10689                   (r, cp_type_quals (t), complain);
10690               }
10691             else
10692               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10693               return unshare_expr (arg);
10694           }
10695
10696         if (level == 1)
10697           /* This can happen during the attempted tsubst'ing in
10698              unify.  This means that we don't yet have any information
10699              about the template parameter in question.  */
10700           return t;
10701
10702         /* If we get here, we must have been looking at a parm for a
10703            more deeply nested template.  Make a new version of this
10704            template parameter, but with a lower level.  */
10705         switch (code)
10706           {
10707           case TEMPLATE_TYPE_PARM:
10708           case TEMPLATE_TEMPLATE_PARM:
10709           case BOUND_TEMPLATE_TEMPLATE_PARM:
10710             if (cp_type_quals (t))
10711               {
10712                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10713                 r = cp_build_qualified_type_real
10714                   (r, cp_type_quals (t),
10715                    complain | (code == TEMPLATE_TYPE_PARM
10716                                ? tf_ignore_bad_quals : 0));
10717               }
10718             else
10719               {
10720                 r = copy_type (t);
10721                 TEMPLATE_TYPE_PARM_INDEX (r)
10722                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10723                                                 r, levels, args, complain);
10724                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10725                 TYPE_MAIN_VARIANT (r) = r;
10726                 TYPE_POINTER_TO (r) = NULL_TREE;
10727                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10728
10729                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10730                   /* We have reduced the level of the template
10731                      template parameter, but not the levels of its
10732                      template parameters, so canonical_type_parameter
10733                      will not be able to find the canonical template
10734                      template parameter for this level. Thus, we
10735                      require structural equality checking to compare
10736                      TEMPLATE_TEMPLATE_PARMs. */
10737                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10738                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10739                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10740                 else
10741                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10742
10743                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10744                   {
10745                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10746                                           complain, in_decl);
10747                     if (argvec == error_mark_node)
10748                       return error_mark_node;
10749
10750                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10751                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10752                   }
10753               }
10754             break;
10755
10756           case TEMPLATE_PARM_INDEX:
10757             r = reduce_template_parm_level (t, type, levels, args, complain);
10758             break;
10759
10760           default:
10761             gcc_unreachable ();
10762           }
10763
10764         return r;
10765       }
10766
10767     case TREE_LIST:
10768       {
10769         tree purpose, value, chain;
10770
10771         if (t == void_list_node)
10772           return t;
10773
10774         purpose = TREE_PURPOSE (t);
10775         if (purpose)
10776           {
10777             purpose = tsubst (purpose, args, complain, in_decl);
10778             if (purpose == error_mark_node)
10779               return error_mark_node;
10780           }
10781         value = TREE_VALUE (t);
10782         if (value)
10783           {
10784             value = tsubst (value, args, complain, in_decl);
10785             if (value == error_mark_node)
10786               return error_mark_node;
10787           }
10788         chain = TREE_CHAIN (t);
10789         if (chain && chain != void_type_node)
10790           {
10791             chain = tsubst (chain, args, complain, in_decl);
10792             if (chain == error_mark_node)
10793               return error_mark_node;
10794           }
10795         if (purpose == TREE_PURPOSE (t)
10796             && value == TREE_VALUE (t)
10797             && chain == TREE_CHAIN (t))
10798           return t;
10799         return hash_tree_cons (purpose, value, chain);
10800       }
10801
10802     case TREE_BINFO:
10803       /* We should never be tsubsting a binfo.  */
10804       gcc_unreachable ();
10805
10806     case TREE_VEC:
10807       /* A vector of template arguments.  */
10808       gcc_assert (!type);
10809       return tsubst_template_args (t, args, complain, in_decl);
10810
10811     case POINTER_TYPE:
10812     case REFERENCE_TYPE:
10813       {
10814         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10815           return t;
10816
10817         /* [temp.deduct]
10818
10819            Type deduction may fail for any of the following
10820            reasons:
10821
10822            -- Attempting to create a pointer to reference type.
10823            -- Attempting to create a reference to a reference type or
10824               a reference to void.
10825
10826           Core issue 106 says that creating a reference to a reference
10827           during instantiation is no longer a cause for failure. We
10828           only enforce this check in strict C++98 mode.  */
10829         if ((TREE_CODE (type) == REFERENCE_TYPE
10830              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10831             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10832           {
10833             static location_t last_loc;
10834
10835             /* We keep track of the last time we issued this error
10836                message to avoid spewing a ton of messages during a
10837                single bad template instantiation.  */
10838             if (complain & tf_error
10839                 && last_loc != input_location)
10840               {
10841                 if (TREE_CODE (type) == VOID_TYPE)
10842                   error ("forming reference to void");
10843                else if (code == POINTER_TYPE)
10844                  error ("forming pointer to reference type %qT", type);
10845                else
10846                   error ("forming reference to reference type %qT", type);
10847                 last_loc = input_location;
10848               }
10849
10850             return error_mark_node;
10851           }
10852         else if (code == POINTER_TYPE)
10853           {
10854             r = build_pointer_type (type);
10855             if (TREE_CODE (type) == METHOD_TYPE)
10856               r = build_ptrmemfunc_type (r);
10857           }
10858         else if (TREE_CODE (type) == REFERENCE_TYPE)
10859           /* In C++0x, during template argument substitution, when there is an
10860              attempt to create a reference to a reference type, reference
10861              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10862
10863              "If a template-argument for a template-parameter T names a type
10864              that is a reference to a type A, an attempt to create the type
10865              'lvalue reference to cv T' creates the type 'lvalue reference to
10866              A,' while an attempt to create the type type rvalue reference to
10867              cv T' creates the type T"
10868           */
10869           r = cp_build_reference_type
10870               (TREE_TYPE (type),
10871                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10872         else
10873           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10874         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
10875
10876         if (r != error_mark_node)
10877           /* Will this ever be needed for TYPE_..._TO values?  */
10878           layout_type (r);
10879
10880         return r;
10881       }
10882     case OFFSET_TYPE:
10883       {
10884         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10885         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10886           {
10887             /* [temp.deduct]
10888
10889                Type deduction may fail for any of the following
10890                reasons:
10891
10892                -- Attempting to create "pointer to member of T" when T
10893                   is not a class type.  */
10894             if (complain & tf_error)
10895               error ("creating pointer to member of non-class type %qT", r);
10896             return error_mark_node;
10897           }
10898         if (TREE_CODE (type) == REFERENCE_TYPE)
10899           {
10900             if (complain & tf_error)
10901               error ("creating pointer to member reference type %qT", type);
10902             return error_mark_node;
10903           }
10904         if (TREE_CODE (type) == VOID_TYPE)
10905           {
10906             if (complain & tf_error)
10907               error ("creating pointer to member of type void");
10908             return error_mark_node;
10909           }
10910         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10911         if (TREE_CODE (type) == FUNCTION_TYPE)
10912           {
10913             /* The type of the implicit object parameter gets its
10914                cv-qualifiers from the FUNCTION_TYPE. */
10915             tree memptr;
10916             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
10917             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10918             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10919                                                  complain);
10920           }
10921         else
10922           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10923                                                cp_type_quals (t),
10924                                                complain);
10925       }
10926     case FUNCTION_TYPE:
10927     case METHOD_TYPE:
10928       {
10929         tree fntype;
10930         tree specs;
10931         fntype = tsubst_function_type (t, args, complain, in_decl);
10932         if (fntype == error_mark_node)
10933           return error_mark_node;
10934
10935         /* Substitute the exception specification.  */
10936         specs = tsubst_exception_specification (t, args, complain,
10937                                                 in_decl, /*defer_ok*/true);
10938         if (specs == error_mark_node)
10939           return error_mark_node;
10940         if (specs)
10941           fntype = build_exception_variant (fntype, specs);
10942         return fntype;
10943       }
10944     case ARRAY_TYPE:
10945       {
10946         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10947         if (domain == error_mark_node)
10948           return error_mark_node;
10949
10950         /* As an optimization, we avoid regenerating the array type if
10951            it will obviously be the same as T.  */
10952         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10953           return t;
10954
10955         /* These checks should match the ones in grokdeclarator.
10956
10957            [temp.deduct]
10958
10959            The deduction may fail for any of the following reasons:
10960
10961            -- Attempting to create an array with an element type that
10962               is void, a function type, or a reference type, or [DR337]
10963               an abstract class type.  */
10964         if (TREE_CODE (type) == VOID_TYPE
10965             || TREE_CODE (type) == FUNCTION_TYPE
10966             || TREE_CODE (type) == REFERENCE_TYPE)
10967           {
10968             if (complain & tf_error)
10969               error ("creating array of %qT", type);
10970             return error_mark_node;
10971           }
10972         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10973           {
10974             if (complain & tf_error)
10975               error ("creating array of %qT, which is an abstract class type",
10976                      type);
10977             return error_mark_node;
10978           }
10979
10980         r = build_cplus_array_type (type, domain);
10981
10982         if (TYPE_USER_ALIGN (t))
10983           {
10984             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10985             TYPE_USER_ALIGN (r) = 1;
10986           }
10987
10988         return r;
10989       }
10990
10991     case TYPENAME_TYPE:
10992       {
10993         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10994                                      in_decl, /*entering_scope=*/1);
10995         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10996                               complain, in_decl);
10997
10998         if (ctx == error_mark_node || f == error_mark_node)
10999           return error_mark_node;
11000
11001         if (!MAYBE_CLASS_TYPE_P (ctx))
11002           {
11003             if (complain & tf_error)
11004               error ("%qT is not a class, struct, or union type", ctx);
11005             return error_mark_node;
11006           }
11007         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
11008           {
11009             /* Normally, make_typename_type does not require that the CTX
11010                have complete type in order to allow things like:
11011
11012                  template <class T> struct S { typename S<T>::X Y; };
11013
11014                But, such constructs have already been resolved by this
11015                point, so here CTX really should have complete type, unless
11016                it's a partial instantiation.  */
11017             ctx = complete_type (ctx);
11018             if (!COMPLETE_TYPE_P (ctx))
11019               {
11020                 if (complain & tf_error)
11021                   cxx_incomplete_type_error (NULL_TREE, ctx);
11022                 return error_mark_node;
11023               }
11024           }
11025
11026         f = make_typename_type (ctx, f, typename_type,
11027                                 (complain & tf_error) | tf_keep_type_decl);
11028         if (f == error_mark_node)
11029           return f;
11030         if (TREE_CODE (f) == TYPE_DECL)
11031           {
11032             complain |= tf_ignore_bad_quals;
11033             f = TREE_TYPE (f);
11034           }
11035
11036         if (TREE_CODE (f) != TYPENAME_TYPE)
11037           {
11038             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
11039               {
11040                 if (complain & tf_error)
11041                   error ("%qT resolves to %qT, which is not an enumeration type",
11042                          t, f);
11043                 else
11044                   return error_mark_node;
11045               }
11046             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
11047               {
11048                 if (complain & tf_error)
11049                   error ("%qT resolves to %qT, which is is not a class type",
11050                          t, f);
11051                 else
11052                   return error_mark_node;
11053               }
11054           }
11055
11056         return cp_build_qualified_type_real
11057           (f, cp_type_quals (f) | cp_type_quals (t), complain);
11058       }
11059
11060     case UNBOUND_CLASS_TEMPLATE:
11061       {
11062         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11063                                      in_decl, /*entering_scope=*/1);
11064         tree name = TYPE_IDENTIFIER (t);
11065         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11066
11067         if (ctx == error_mark_node || name == error_mark_node)
11068           return error_mark_node;
11069
11070         if (parm_list)
11071           parm_list = tsubst_template_parms (parm_list, args, complain);
11072         return make_unbound_class_template (ctx, name, parm_list, complain);
11073       }
11074
11075     case TYPEOF_TYPE:
11076       {
11077         tree type;
11078
11079         ++cp_unevaluated_operand;
11080         ++c_inhibit_evaluation_warnings;
11081
11082         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11083                             complain, in_decl,
11084                             /*integral_constant_expression_p=*/false);
11085
11086         --cp_unevaluated_operand;
11087         --c_inhibit_evaluation_warnings;
11088
11089         type = finish_typeof (type);
11090         return cp_build_qualified_type_real (type,
11091                                              cp_type_quals (t)
11092                                              | cp_type_quals (type),
11093                                              complain);
11094       }
11095
11096     case DECLTYPE_TYPE:
11097       {
11098         tree type;
11099
11100         ++cp_unevaluated_operand;
11101         ++c_inhibit_evaluation_warnings;
11102
11103         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11104                             complain, in_decl,
11105                             /*integral_constant_expression_p=*/false);
11106
11107         --cp_unevaluated_operand;
11108         --c_inhibit_evaluation_warnings;
11109
11110         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11111           type = lambda_capture_field_type (type);
11112         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
11113           type = lambda_return_type (type);
11114         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
11115           type = lambda_proxy_type (type);
11116         else
11117           type = finish_decltype_type
11118             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
11119         return cp_build_qualified_type_real (type,
11120                                              cp_type_quals (t)
11121                                              | cp_type_quals (type),
11122                                              complain);
11123       }
11124
11125     case UNDERLYING_TYPE:
11126       {
11127         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11128                             complain, in_decl);
11129         return finish_underlying_type (type);
11130       }
11131
11132     case TYPE_ARGUMENT_PACK:
11133     case NONTYPE_ARGUMENT_PACK:
11134       {
11135         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11136         tree packed_out = 
11137           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11138                                 args,
11139                                 complain,
11140                                 in_decl);
11141         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11142
11143         /* For template nontype argument packs, also substitute into
11144            the type.  */
11145         if (code == NONTYPE_ARGUMENT_PACK)
11146           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11147
11148         return r;
11149       }
11150       break;
11151
11152     case INTEGER_CST:
11153     case REAL_CST:
11154     case STRING_CST:
11155     case PLUS_EXPR:
11156     case MINUS_EXPR:
11157     case NEGATE_EXPR:
11158     case NOP_EXPR:
11159     case INDIRECT_REF:
11160     case ADDR_EXPR:
11161     case CALL_EXPR:
11162     case ARRAY_REF:
11163     case SCOPE_REF:
11164       /* We should use one of the expression tsubsts for these codes.  */
11165       gcc_unreachable ();
11166
11167     default:
11168       sorry ("use of %qs in template", tree_code_name [(int) code]);
11169       return error_mark_node;
11170     }
11171 }
11172
11173 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11174    type of the expression on the left-hand side of the "." or "->"
11175    operator.  */
11176
11177 static tree
11178 tsubst_baselink (tree baselink, tree object_type,
11179                  tree args, tsubst_flags_t complain, tree in_decl)
11180 {
11181     tree name;
11182     tree qualifying_scope;
11183     tree fns;
11184     tree optype;
11185     tree template_args = 0;
11186     bool template_id_p = false;
11187
11188     /* A baselink indicates a function from a base class.  Both the
11189        BASELINK_ACCESS_BINFO and the base class referenced may
11190        indicate bases of the template class, rather than the
11191        instantiated class.  In addition, lookups that were not
11192        ambiguous before may be ambiguous now.  Therefore, we perform
11193        the lookup again.  */
11194     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11195     qualifying_scope = tsubst (qualifying_scope, args,
11196                                complain, in_decl);
11197     fns = BASELINK_FUNCTIONS (baselink);
11198     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11199     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11200       {
11201         template_id_p = true;
11202         template_args = TREE_OPERAND (fns, 1);
11203         fns = TREE_OPERAND (fns, 0);
11204         if (template_args)
11205           template_args = tsubst_template_args (template_args, args,
11206                                                 complain, in_decl);
11207       }
11208     name = DECL_NAME (get_first_fn (fns));
11209     if (IDENTIFIER_TYPENAME_P (name))
11210       name = mangle_conv_op_name_for_type (optype);
11211     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11212     if (!baselink)
11213       return error_mark_node;
11214
11215     /* If lookup found a single function, mark it as used at this
11216        point.  (If it lookup found multiple functions the one selected
11217        later by overload resolution will be marked as used at that
11218        point.)  */
11219     if (BASELINK_P (baselink))
11220       fns = BASELINK_FUNCTIONS (baselink);
11221     if (!template_id_p && !really_overloaded_fn (fns))
11222       mark_used (OVL_CURRENT (fns));
11223
11224     /* Add back the template arguments, if present.  */
11225     if (BASELINK_P (baselink) && template_id_p)
11226       BASELINK_FUNCTIONS (baselink)
11227         = build_nt (TEMPLATE_ID_EXPR,
11228                     BASELINK_FUNCTIONS (baselink),
11229                     template_args);
11230     /* Update the conversion operator type.  */
11231     BASELINK_OPTYPE (baselink) = optype;
11232
11233     if (!object_type)
11234       object_type = current_class_type;
11235     return adjust_result_of_qualified_name_lookup (baselink,
11236                                                    qualifying_scope,
11237                                                    object_type);
11238 }
11239
11240 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11241    true if the qualified-id will be a postfix-expression in-and-of
11242    itself; false if more of the postfix-expression follows the
11243    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11244    of "&".  */
11245
11246 static tree
11247 tsubst_qualified_id (tree qualified_id, tree args,
11248                      tsubst_flags_t complain, tree in_decl,
11249                      bool done, bool address_p)
11250 {
11251   tree expr;
11252   tree scope;
11253   tree name;
11254   bool is_template;
11255   tree template_args;
11256
11257   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11258
11259   /* Figure out what name to look up.  */
11260   name = TREE_OPERAND (qualified_id, 1);
11261   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11262     {
11263       is_template = true;
11264       template_args = TREE_OPERAND (name, 1);
11265       if (template_args)
11266         template_args = tsubst_template_args (template_args, args,
11267                                               complain, in_decl);
11268       name = TREE_OPERAND (name, 0);
11269     }
11270   else
11271     {
11272       is_template = false;
11273       template_args = NULL_TREE;
11274     }
11275
11276   /* Substitute into the qualifying scope.  When there are no ARGS, we
11277      are just trying to simplify a non-dependent expression.  In that
11278      case the qualifying scope may be dependent, and, in any case,
11279      substituting will not help.  */
11280   scope = TREE_OPERAND (qualified_id, 0);
11281   if (args)
11282     {
11283       scope = tsubst (scope, args, complain, in_decl);
11284       expr = tsubst_copy (name, args, complain, in_decl);
11285     }
11286   else
11287     expr = name;
11288
11289   if (dependent_scope_p (scope))
11290     {
11291       if (is_template)
11292         expr = build_min_nt (TEMPLATE_ID_EXPR, expr, template_args);
11293       return build_qualified_name (NULL_TREE, scope, expr,
11294                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11295     }
11296
11297   if (!BASELINK_P (name) && !DECL_P (expr))
11298     {
11299       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11300         {
11301           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11302           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11303             {
11304               error ("qualifying type %qT does not match destructor name ~%qT",
11305                      scope, TREE_OPERAND (expr, 0));
11306               expr = error_mark_node;
11307             }
11308           else
11309             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11310                                           /*is_type_p=*/0, false);
11311         }
11312       else
11313         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11314       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11315                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11316         {
11317           if (complain & tf_error)
11318             {
11319               error ("dependent-name %qE is parsed as a non-type, but "
11320                      "instantiation yields a type", qualified_id);
11321               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11322             }
11323           return error_mark_node;
11324         }
11325     }
11326
11327   if (DECL_P (expr))
11328     {
11329       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11330                                            scope);
11331       /* Remember that there was a reference to this entity.  */
11332       mark_used (expr);
11333     }
11334
11335   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11336     {
11337       if (complain & tf_error)
11338         qualified_name_lookup_error (scope,
11339                                      TREE_OPERAND (qualified_id, 1),
11340                                      expr, input_location);
11341       return error_mark_node;
11342     }
11343
11344   if (is_template)
11345     expr = lookup_template_function (expr, template_args);
11346
11347   if (expr == error_mark_node && complain & tf_error)
11348     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11349                                  expr, input_location);
11350   else if (TYPE_P (scope))
11351     {
11352       expr = (adjust_result_of_qualified_name_lookup
11353               (expr, scope, current_class_type));
11354       expr = (finish_qualified_id_expr
11355               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
11356                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11357                /*template_arg_p=*/false));
11358     }
11359
11360   /* Expressions do not generally have reference type.  */
11361   if (TREE_CODE (expr) != SCOPE_REF
11362       /* However, if we're about to form a pointer-to-member, we just
11363          want the referenced member referenced.  */
11364       && TREE_CODE (expr) != OFFSET_REF)
11365     expr = convert_from_reference (expr);
11366
11367   return expr;
11368 }
11369
11370 /* Like tsubst, but deals with expressions.  This function just replaces
11371    template parms; to finish processing the resultant expression, use
11372    tsubst_expr.  */
11373
11374 static tree
11375 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11376 {
11377   enum tree_code code;
11378   tree r;
11379
11380   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11381     return t;
11382
11383   code = TREE_CODE (t);
11384
11385   switch (code)
11386     {
11387     case PARM_DECL:
11388       r = retrieve_local_specialization (t);
11389
11390       if (r == NULL)
11391         {
11392           tree c;
11393           /* This can happen for a parameter name used later in a function
11394              declaration (such as in a late-specified return type).  Just
11395              make a dummy decl, since it's only used for its type.  */
11396           gcc_assert (cp_unevaluated_operand != 0);
11397           /* We copy T because want to tsubst the PARM_DECL only,
11398              not the following PARM_DECLs that are chained to T.  */
11399           c = copy_node (t);
11400           r = tsubst_decl (c, args, complain);
11401           /* Give it the template pattern as its context; its true context
11402              hasn't been instantiated yet and this is good enough for
11403              mangling.  */
11404           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11405         }
11406       
11407       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11408         r = ARGUMENT_PACK_SELECT_ARG (r);
11409       mark_used (r);
11410       return r;
11411
11412     case CONST_DECL:
11413       {
11414         tree enum_type;
11415         tree v;
11416
11417         if (DECL_TEMPLATE_PARM_P (t))
11418           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11419         /* There is no need to substitute into namespace-scope
11420            enumerators.  */
11421         if (DECL_NAMESPACE_SCOPE_P (t))
11422           return t;
11423         /* If ARGS is NULL, then T is known to be non-dependent.  */
11424         if (args == NULL_TREE)
11425           return integral_constant_value (t);
11426
11427         /* Unfortunately, we cannot just call lookup_name here.
11428            Consider:
11429
11430              template <int I> int f() {
11431              enum E { a = I };
11432              struct S { void g() { E e = a; } };
11433              };
11434
11435            When we instantiate f<7>::S::g(), say, lookup_name is not
11436            clever enough to find f<7>::a.  */
11437         enum_type
11438           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11439                               /*entering_scope=*/0);
11440
11441         for (v = TYPE_VALUES (enum_type);
11442              v != NULL_TREE;
11443              v = TREE_CHAIN (v))
11444           if (TREE_PURPOSE (v) == DECL_NAME (t))
11445             return TREE_VALUE (v);
11446
11447           /* We didn't find the name.  That should never happen; if
11448              name-lookup found it during preliminary parsing, we
11449              should find it again here during instantiation.  */
11450         gcc_unreachable ();
11451       }
11452       return t;
11453
11454     case FIELD_DECL:
11455       if (DECL_CONTEXT (t))
11456         {
11457           tree ctx;
11458
11459           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11460                                   /*entering_scope=*/1);
11461           if (ctx != DECL_CONTEXT (t))
11462             {
11463               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11464               if (!r)
11465                 {
11466                   if (complain & tf_error)
11467                     error ("using invalid field %qD", t);
11468                   return error_mark_node;
11469                 }
11470               return r;
11471             }
11472         }
11473
11474       return t;
11475
11476     case VAR_DECL:
11477     case FUNCTION_DECL:
11478       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11479           || local_variable_p (t))
11480         t = tsubst (t, args, complain, in_decl);
11481       mark_used (t);
11482       return t;
11483
11484     case OVERLOAD:
11485       /* An OVERLOAD will always be a non-dependent overload set; an
11486          overload set from function scope will just be represented with an
11487          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11488       gcc_assert (!uses_template_parms (t));
11489       return t;
11490
11491     case BASELINK:
11492       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11493
11494     case TEMPLATE_DECL:
11495       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11496         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11497                        args, complain, in_decl);
11498       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11499         return tsubst (t, args, complain, in_decl);
11500       else if (DECL_CLASS_SCOPE_P (t)
11501                && uses_template_parms (DECL_CONTEXT (t)))
11502         {
11503           /* Template template argument like the following example need
11504              special treatment:
11505
11506                template <template <class> class TT> struct C {};
11507                template <class T> struct D {
11508                  template <class U> struct E {};
11509                  C<E> c;                                // #1
11510                };
11511                D<int> d;                                // #2
11512
11513              We are processing the template argument `E' in #1 for
11514              the template instantiation #2.  Originally, `E' is a
11515              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11516              have to substitute this with one having context `D<int>'.  */
11517
11518           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11519           return lookup_field (context, DECL_NAME(t), 0, false);
11520         }
11521       else
11522         /* Ordinary template template argument.  */
11523         return t;
11524
11525     case CAST_EXPR:
11526     case REINTERPRET_CAST_EXPR:
11527     case CONST_CAST_EXPR:
11528     case STATIC_CAST_EXPR:
11529     case DYNAMIC_CAST_EXPR:
11530     case NOP_EXPR:
11531       return build1
11532         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11533          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11534
11535     case SIZEOF_EXPR:
11536       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11537         {
11538
11539           tree expanded;
11540           int len = 0;
11541
11542           ++cp_unevaluated_operand;
11543           ++c_inhibit_evaluation_warnings;
11544           /* We only want to compute the number of arguments.  */
11545           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11546                                             complain, in_decl);
11547           --cp_unevaluated_operand;
11548           --c_inhibit_evaluation_warnings;
11549
11550           if (TREE_CODE (expanded) == TREE_VEC)
11551             len = TREE_VEC_LENGTH (expanded);
11552
11553           if (expanded == error_mark_node)
11554             return error_mark_node;
11555           else if (PACK_EXPANSION_P (expanded)
11556                    || (TREE_CODE (expanded) == TREE_VEC
11557                        && len > 0
11558                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11559             {
11560               if (TREE_CODE (expanded) == TREE_VEC)
11561                 expanded = TREE_VEC_ELT (expanded, len - 1);
11562
11563               if (TYPE_P (expanded))
11564                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11565                                                    complain & tf_error);
11566               else
11567                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11568                                                    complain & tf_error);
11569             }
11570           else
11571             return build_int_cst (size_type_node, len);
11572         }
11573       /* Fall through */
11574
11575     case INDIRECT_REF:
11576     case NEGATE_EXPR:
11577     case TRUTH_NOT_EXPR:
11578     case BIT_NOT_EXPR:
11579     case ADDR_EXPR:
11580     case UNARY_PLUS_EXPR:      /* Unary + */
11581     case ALIGNOF_EXPR:
11582     case AT_ENCODE_EXPR:
11583     case ARROW_EXPR:
11584     case THROW_EXPR:
11585     case TYPEID_EXPR:
11586     case REALPART_EXPR:
11587     case IMAGPART_EXPR:
11588       return build1
11589         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11590          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11591
11592     case COMPONENT_REF:
11593       {
11594         tree object;
11595         tree name;
11596
11597         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11598         name = TREE_OPERAND (t, 1);
11599         if (TREE_CODE (name) == BIT_NOT_EXPR)
11600           {
11601             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11602                                 complain, in_decl);
11603             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11604           }
11605         else if (TREE_CODE (name) == SCOPE_REF
11606                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11607           {
11608             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11609                                      complain, in_decl);
11610             name = TREE_OPERAND (name, 1);
11611             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11612                                 complain, in_decl);
11613             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11614             name = build_qualified_name (/*type=*/NULL_TREE,
11615                                          base, name,
11616                                          /*template_p=*/false);
11617           }
11618         else if (TREE_CODE (name) == BASELINK)
11619           name = tsubst_baselink (name,
11620                                   non_reference (TREE_TYPE (object)),
11621                                   args, complain,
11622                                   in_decl);
11623         else
11624           name = tsubst_copy (name, args, complain, in_decl);
11625         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11626       }
11627
11628     case PLUS_EXPR:
11629     case MINUS_EXPR:
11630     case MULT_EXPR:
11631     case TRUNC_DIV_EXPR:
11632     case CEIL_DIV_EXPR:
11633     case FLOOR_DIV_EXPR:
11634     case ROUND_DIV_EXPR:
11635     case EXACT_DIV_EXPR:
11636     case BIT_AND_EXPR:
11637     case BIT_IOR_EXPR:
11638     case BIT_XOR_EXPR:
11639     case TRUNC_MOD_EXPR:
11640     case FLOOR_MOD_EXPR:
11641     case TRUTH_ANDIF_EXPR:
11642     case TRUTH_ORIF_EXPR:
11643     case TRUTH_AND_EXPR:
11644     case TRUTH_OR_EXPR:
11645     case RSHIFT_EXPR:
11646     case LSHIFT_EXPR:
11647     case RROTATE_EXPR:
11648     case LROTATE_EXPR:
11649     case EQ_EXPR:
11650     case NE_EXPR:
11651     case MAX_EXPR:
11652     case MIN_EXPR:
11653     case LE_EXPR:
11654     case GE_EXPR:
11655     case LT_EXPR:
11656     case GT_EXPR:
11657     case COMPOUND_EXPR:
11658     case DOTSTAR_EXPR:
11659     case MEMBER_REF:
11660     case PREDECREMENT_EXPR:
11661     case PREINCREMENT_EXPR:
11662     case POSTDECREMENT_EXPR:
11663     case POSTINCREMENT_EXPR:
11664       return build_nt
11665         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11666          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11667
11668     case SCOPE_REF:
11669       return build_qualified_name (/*type=*/NULL_TREE,
11670                                    tsubst_copy (TREE_OPERAND (t, 0),
11671                                                 args, complain, in_decl),
11672                                    tsubst_copy (TREE_OPERAND (t, 1),
11673                                                 args, complain, in_decl),
11674                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11675
11676     case ARRAY_REF:
11677       return build_nt
11678         (ARRAY_REF,
11679          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11680          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11681          NULL_TREE, NULL_TREE);
11682
11683     case CALL_EXPR:
11684       {
11685         int n = VL_EXP_OPERAND_LENGTH (t);
11686         tree result = build_vl_exp (CALL_EXPR, n);
11687         int i;
11688         for (i = 0; i < n; i++)
11689           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11690                                              complain, in_decl);
11691         return result;
11692       }
11693
11694     case COND_EXPR:
11695     case MODOP_EXPR:
11696     case PSEUDO_DTOR_EXPR:
11697       {
11698         r = build_nt
11699           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11700            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11701            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11702         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11703         return r;
11704       }
11705
11706     case NEW_EXPR:
11707       {
11708         r = build_nt
11709         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11710          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11711          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11712         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11713         return r;
11714       }
11715
11716     case DELETE_EXPR:
11717       {
11718         r = build_nt
11719         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11720          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11721         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11722         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11723         return r;
11724       }
11725
11726     case TEMPLATE_ID_EXPR:
11727       {
11728         /* Substituted template arguments */
11729         tree fn = TREE_OPERAND (t, 0);
11730         tree targs = TREE_OPERAND (t, 1);
11731
11732         fn = tsubst_copy (fn, args, complain, in_decl);
11733         if (targs)
11734           targs = tsubst_template_args (targs, args, complain, in_decl);
11735
11736         return lookup_template_function (fn, targs);
11737       }
11738
11739     case TREE_LIST:
11740       {
11741         tree purpose, value, chain;
11742
11743         if (t == void_list_node)
11744           return t;
11745
11746         purpose = TREE_PURPOSE (t);
11747         if (purpose)
11748           purpose = tsubst_copy (purpose, args, complain, in_decl);
11749         value = TREE_VALUE (t);
11750         if (value)
11751           value = tsubst_copy (value, args, complain, in_decl);
11752         chain = TREE_CHAIN (t);
11753         if (chain && chain != void_type_node)
11754           chain = tsubst_copy (chain, args, complain, in_decl);
11755         if (purpose == TREE_PURPOSE (t)
11756             && value == TREE_VALUE (t)
11757             && chain == TREE_CHAIN (t))
11758           return t;
11759         return tree_cons (purpose, value, chain);
11760       }
11761
11762     case RECORD_TYPE:
11763     case UNION_TYPE:
11764     case ENUMERAL_TYPE:
11765     case INTEGER_TYPE:
11766     case TEMPLATE_TYPE_PARM:
11767     case TEMPLATE_TEMPLATE_PARM:
11768     case BOUND_TEMPLATE_TEMPLATE_PARM:
11769     case TEMPLATE_PARM_INDEX:
11770     case POINTER_TYPE:
11771     case REFERENCE_TYPE:
11772     case OFFSET_TYPE:
11773     case FUNCTION_TYPE:
11774     case METHOD_TYPE:
11775     case ARRAY_TYPE:
11776     case TYPENAME_TYPE:
11777     case UNBOUND_CLASS_TEMPLATE:
11778     case TYPEOF_TYPE:
11779     case DECLTYPE_TYPE:
11780     case TYPE_DECL:
11781       return tsubst (t, args, complain, in_decl);
11782
11783     case IDENTIFIER_NODE:
11784       if (IDENTIFIER_TYPENAME_P (t))
11785         {
11786           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11787           return mangle_conv_op_name_for_type (new_type);
11788         }
11789       else
11790         return t;
11791
11792     case CONSTRUCTOR:
11793       /* This is handled by tsubst_copy_and_build.  */
11794       gcc_unreachable ();
11795
11796     case VA_ARG_EXPR:
11797       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11798                                           in_decl),
11799                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11800
11801     case CLEANUP_POINT_EXPR:
11802       /* We shouldn't have built any of these during initial template
11803          generation.  Instead, they should be built during instantiation
11804          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11805       gcc_unreachable ();
11806
11807     case OFFSET_REF:
11808       r = build2
11809         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11810          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11811          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11812       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
11813       mark_used (TREE_OPERAND (r, 1));
11814       return r;
11815
11816     case EXPR_PACK_EXPANSION:
11817       error ("invalid use of pack expansion expression");
11818       return error_mark_node;
11819
11820     case NONTYPE_ARGUMENT_PACK:
11821       error ("use %<...%> to expand argument pack");
11822       return error_mark_node;
11823
11824     case INTEGER_CST:
11825     case REAL_CST:
11826     case STRING_CST:
11827     case COMPLEX_CST:
11828       {
11829         /* Instantiate any typedefs in the type.  */
11830         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11831         r = fold_convert (type, t);
11832         gcc_assert (TREE_CODE (r) == code);
11833         return r;
11834       }
11835
11836     case PTRMEM_CST:
11837       /* These can sometimes show up in a partial instantiation, but never
11838          involve template parms.  */
11839       gcc_assert (!uses_template_parms (t));
11840       return t;
11841
11842     default:
11843       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
11844       gcc_checking_assert (false);
11845       return t;
11846     }
11847 }
11848
11849 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11850
11851 static tree
11852 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11853                     tree in_decl)
11854 {
11855   tree new_clauses = NULL, nc, oc;
11856
11857   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11858     {
11859       nc = copy_node (oc);
11860       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11861       new_clauses = nc;
11862
11863       switch (OMP_CLAUSE_CODE (nc))
11864         {
11865         case OMP_CLAUSE_LASTPRIVATE:
11866           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11867             {
11868               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11869               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11870                            in_decl, /*integral_constant_expression_p=*/false);
11871               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11872                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11873             }
11874           /* FALLTHRU */
11875         case OMP_CLAUSE_PRIVATE:
11876         case OMP_CLAUSE_SHARED:
11877         case OMP_CLAUSE_FIRSTPRIVATE:
11878         case OMP_CLAUSE_REDUCTION:
11879         case OMP_CLAUSE_COPYIN:
11880         case OMP_CLAUSE_COPYPRIVATE:
11881         case OMP_CLAUSE_IF:
11882         case OMP_CLAUSE_NUM_THREADS:
11883         case OMP_CLAUSE_SCHEDULE:
11884         case OMP_CLAUSE_COLLAPSE:
11885           OMP_CLAUSE_OPERAND (nc, 0)
11886             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11887                            in_decl, /*integral_constant_expression_p=*/false);
11888           break;
11889         case OMP_CLAUSE_NOWAIT:
11890         case OMP_CLAUSE_ORDERED:
11891         case OMP_CLAUSE_DEFAULT:
11892         case OMP_CLAUSE_UNTIED:
11893           break;
11894         default:
11895           gcc_unreachable ();
11896         }
11897     }
11898
11899   return finish_omp_clauses (nreverse (new_clauses));
11900 }
11901
11902 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11903
11904 static tree
11905 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11906                           tree in_decl)
11907 {
11908 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11909
11910   tree purpose, value, chain;
11911
11912   if (t == NULL)
11913     return t;
11914
11915   if (TREE_CODE (t) != TREE_LIST)
11916     return tsubst_copy_and_build (t, args, complain, in_decl,
11917                                   /*function_p=*/false,
11918                                   /*integral_constant_expression_p=*/false);
11919
11920   if (t == void_list_node)
11921     return t;
11922
11923   purpose = TREE_PURPOSE (t);
11924   if (purpose)
11925     purpose = RECUR (purpose);
11926   value = TREE_VALUE (t);
11927   if (value && TREE_CODE (value) != LABEL_DECL)
11928     value = RECUR (value);
11929   chain = TREE_CHAIN (t);
11930   if (chain && chain != void_type_node)
11931     chain = RECUR (chain);
11932   return tree_cons (purpose, value, chain);
11933 #undef RECUR
11934 }
11935
11936 /* Substitute one OMP_FOR iterator.  */
11937
11938 static void
11939 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11940                          tree condv, tree incrv, tree *clauses,
11941                          tree args, tsubst_flags_t complain, tree in_decl,
11942                          bool integral_constant_expression_p)
11943 {
11944 #define RECUR(NODE)                             \
11945   tsubst_expr ((NODE), args, complain, in_decl, \
11946                integral_constant_expression_p)
11947   tree decl, init, cond, incr, auto_node;
11948
11949   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11950   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11951   decl = RECUR (TREE_OPERAND (init, 0));
11952   init = TREE_OPERAND (init, 1);
11953   auto_node = type_uses_auto (TREE_TYPE (decl));
11954   if (auto_node && init)
11955     {
11956       tree init_expr = init;
11957       if (TREE_CODE (init_expr) == DECL_EXPR)
11958         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11959       init_expr = RECUR (init_expr);
11960       TREE_TYPE (decl)
11961         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11962     }
11963   gcc_assert (!type_dependent_expression_p (decl));
11964
11965   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11966     {
11967       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11968       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11969       if (TREE_CODE (incr) == MODIFY_EXPR)
11970         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11971                                     RECUR (TREE_OPERAND (incr, 1)),
11972                                     complain);
11973       else
11974         incr = RECUR (incr);
11975       TREE_VEC_ELT (declv, i) = decl;
11976       TREE_VEC_ELT (initv, i) = init;
11977       TREE_VEC_ELT (condv, i) = cond;
11978       TREE_VEC_ELT (incrv, i) = incr;
11979       return;
11980     }
11981
11982   if (init && TREE_CODE (init) != DECL_EXPR)
11983     {
11984       tree c;
11985       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11986         {
11987           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11988                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11989               && OMP_CLAUSE_DECL (c) == decl)
11990             break;
11991           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11992                    && OMP_CLAUSE_DECL (c) == decl)
11993             error ("iteration variable %qD should not be firstprivate", decl);
11994           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11995                    && OMP_CLAUSE_DECL (c) == decl)
11996             error ("iteration variable %qD should not be reduction", decl);
11997         }
11998       if (c == NULL)
11999         {
12000           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
12001           OMP_CLAUSE_DECL (c) = decl;
12002           c = finish_omp_clauses (c);
12003           if (c)
12004             {
12005               OMP_CLAUSE_CHAIN (c) = *clauses;
12006               *clauses = c;
12007             }
12008         }
12009     }
12010   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
12011   if (COMPARISON_CLASS_P (cond))
12012     cond = build2 (TREE_CODE (cond), boolean_type_node,
12013                    RECUR (TREE_OPERAND (cond, 0)),
12014                    RECUR (TREE_OPERAND (cond, 1)));
12015   else
12016     cond = RECUR (cond);
12017   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12018   switch (TREE_CODE (incr))
12019     {
12020     case PREINCREMENT_EXPR:
12021     case PREDECREMENT_EXPR:
12022     case POSTINCREMENT_EXPR:
12023     case POSTDECREMENT_EXPR:
12024       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
12025                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
12026       break;
12027     case MODIFY_EXPR:
12028       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12029           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12030         {
12031           tree rhs = TREE_OPERAND (incr, 1);
12032           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12033                          RECUR (TREE_OPERAND (incr, 0)),
12034                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12035                                  RECUR (TREE_OPERAND (rhs, 0)),
12036                                  RECUR (TREE_OPERAND (rhs, 1))));
12037         }
12038       else
12039         incr = RECUR (incr);
12040       break;
12041     case MODOP_EXPR:
12042       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12043           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12044         {
12045           tree lhs = RECUR (TREE_OPERAND (incr, 0));
12046           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
12047                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
12048                                  TREE_TYPE (decl), lhs,
12049                                  RECUR (TREE_OPERAND (incr, 2))));
12050         }
12051       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
12052                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
12053                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
12054         {
12055           tree rhs = TREE_OPERAND (incr, 2);
12056           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12057                          RECUR (TREE_OPERAND (incr, 0)),
12058                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12059                                  RECUR (TREE_OPERAND (rhs, 0)),
12060                                  RECUR (TREE_OPERAND (rhs, 1))));
12061         }
12062       else
12063         incr = RECUR (incr);
12064       break;
12065     default:
12066       incr = RECUR (incr);
12067       break;
12068     }
12069
12070   TREE_VEC_ELT (declv, i) = decl;
12071   TREE_VEC_ELT (initv, i) = init;
12072   TREE_VEC_ELT (condv, i) = cond;
12073   TREE_VEC_ELT (incrv, i) = incr;
12074 #undef RECUR
12075 }
12076
12077 /* Like tsubst_copy for expressions, etc. but also does semantic
12078    processing.  */
12079
12080 static tree
12081 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12082              bool integral_constant_expression_p)
12083 {
12084 #define RECUR(NODE)                             \
12085   tsubst_expr ((NODE), args, complain, in_decl, \
12086                integral_constant_expression_p)
12087
12088   tree stmt, tmp;
12089
12090   if (t == NULL_TREE || t == error_mark_node)
12091     return t;
12092
12093   if (EXPR_HAS_LOCATION (t))
12094     input_location = EXPR_LOCATION (t);
12095   if (STATEMENT_CODE_P (TREE_CODE (t)))
12096     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12097
12098   switch (TREE_CODE (t))
12099     {
12100     case STATEMENT_LIST:
12101       {
12102         tree_stmt_iterator i;
12103         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12104           RECUR (tsi_stmt (i));
12105         break;
12106       }
12107
12108     case CTOR_INITIALIZER:
12109       finish_mem_initializers (tsubst_initializer_list
12110                                (TREE_OPERAND (t, 0), args));
12111       break;
12112
12113     case RETURN_EXPR:
12114       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12115       break;
12116
12117     case EXPR_STMT:
12118       tmp = RECUR (EXPR_STMT_EXPR (t));
12119       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12120         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12121       else
12122         finish_expr_stmt (tmp);
12123       break;
12124
12125     case USING_STMT:
12126       do_using_directive (USING_STMT_NAMESPACE (t));
12127       break;
12128
12129     case DECL_EXPR:
12130       {
12131         tree decl, pattern_decl;
12132         tree init;
12133
12134         pattern_decl = decl = DECL_EXPR_DECL (t);
12135         if (TREE_CODE (decl) == LABEL_DECL)
12136           finish_label_decl (DECL_NAME (decl));
12137         else if (TREE_CODE (decl) == USING_DECL)
12138           {
12139             tree scope = USING_DECL_SCOPE (decl);
12140             tree name = DECL_NAME (decl);
12141             tree decl;
12142
12143             scope = tsubst (scope, args, complain, in_decl);
12144             decl = lookup_qualified_name (scope, name,
12145                                           /*is_type_p=*/false,
12146                                           /*complain=*/false);
12147             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12148               qualified_name_lookup_error (scope, name, decl, input_location);
12149             else
12150               do_local_using_decl (decl, scope, name);
12151           }
12152         else
12153           {
12154             init = DECL_INITIAL (decl);
12155             decl = tsubst (decl, args, complain, in_decl);
12156             if (decl != error_mark_node)
12157               {
12158                 /* By marking the declaration as instantiated, we avoid
12159                    trying to instantiate it.  Since instantiate_decl can't
12160                    handle local variables, and since we've already done
12161                    all that needs to be done, that's the right thing to
12162                    do.  */
12163                 if (TREE_CODE (decl) == VAR_DECL)
12164                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12165                 if (TREE_CODE (decl) == VAR_DECL
12166                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12167                   /* Anonymous aggregates are a special case.  */
12168                   finish_anon_union (decl);
12169                 else
12170                   {
12171                     int const_init = false;
12172                     maybe_push_decl (decl);
12173                     if (TREE_CODE (decl) == VAR_DECL
12174                         && DECL_PRETTY_FUNCTION_P (decl))
12175                       {
12176                         /* For __PRETTY_FUNCTION__ we have to adjust the
12177                            initializer.  */
12178                         const char *const name
12179                           = cxx_printable_name (current_function_decl, 2);
12180                         init = cp_fname_init (name, &TREE_TYPE (decl));
12181                       }
12182                     else
12183                       {
12184                         tree t = RECUR (init);
12185
12186                         if (init && !t)
12187                           {
12188                             /* If we had an initializer but it
12189                                instantiated to nothing,
12190                                value-initialize the object.  This will
12191                                only occur when the initializer was a
12192                                pack expansion where the parameter packs
12193                                used in that expansion were of length
12194                                zero.  */
12195                             init = build_value_init (TREE_TYPE (decl),
12196                                                      complain);
12197                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12198                               init = get_target_expr_sfinae (init, complain);
12199                           }
12200                         else
12201                           init = t;
12202                       }
12203
12204                     if (TREE_CODE (decl) == VAR_DECL)
12205                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12206                                     (pattern_decl));
12207                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12208                   }
12209               }
12210           }
12211
12212         /* A DECL_EXPR can also be used as an expression, in the condition
12213            clause of an if/for/while construct.  */
12214         return decl;
12215       }
12216
12217     case FOR_STMT:
12218       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12219       RECUR (FOR_INIT_STMT (t));
12220       finish_for_init_stmt (stmt);
12221       tmp = RECUR (FOR_COND (t));
12222       finish_for_cond (tmp, stmt);
12223       tmp = RECUR (FOR_EXPR (t));
12224       finish_for_expr (tmp, stmt);
12225       RECUR (FOR_BODY (t));
12226       finish_for_stmt (stmt);
12227       break;
12228
12229     case RANGE_FOR_STMT:
12230       {
12231         tree decl, expr;
12232         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12233         decl = RANGE_FOR_DECL (t);
12234         decl = tsubst (decl, args, complain, in_decl);
12235         maybe_push_decl (decl);
12236         expr = RECUR (RANGE_FOR_EXPR (t));
12237         stmt = cp_convert_range_for (stmt, decl, expr);
12238         RECUR (RANGE_FOR_BODY (t));
12239         finish_for_stmt (stmt);
12240       }
12241       break;
12242
12243     case WHILE_STMT:
12244       stmt = begin_while_stmt ();
12245       tmp = RECUR (WHILE_COND (t));
12246       finish_while_stmt_cond (tmp, stmt);
12247       RECUR (WHILE_BODY (t));
12248       finish_while_stmt (stmt);
12249       break;
12250
12251     case DO_STMT:
12252       stmt = begin_do_stmt ();
12253       RECUR (DO_BODY (t));
12254       finish_do_body (stmt);
12255       tmp = RECUR (DO_COND (t));
12256       finish_do_stmt (tmp, stmt);
12257       break;
12258
12259     case IF_STMT:
12260       stmt = begin_if_stmt ();
12261       tmp = RECUR (IF_COND (t));
12262       finish_if_stmt_cond (tmp, stmt);
12263       RECUR (THEN_CLAUSE (t));
12264       finish_then_clause (stmt);
12265
12266       if (ELSE_CLAUSE (t))
12267         {
12268           begin_else_clause (stmt);
12269           RECUR (ELSE_CLAUSE (t));
12270           finish_else_clause (stmt);
12271         }
12272
12273       finish_if_stmt (stmt);
12274       break;
12275
12276     case BIND_EXPR:
12277       if (BIND_EXPR_BODY_BLOCK (t))
12278         stmt = begin_function_body ();
12279       else
12280         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12281                                     ? BCS_TRY_BLOCK : 0);
12282
12283       RECUR (BIND_EXPR_BODY (t));
12284
12285       if (BIND_EXPR_BODY_BLOCK (t))
12286         finish_function_body (stmt);
12287       else
12288         finish_compound_stmt (stmt);
12289       break;
12290
12291     case BREAK_STMT:
12292       finish_break_stmt ();
12293       break;
12294
12295     case CONTINUE_STMT:
12296       finish_continue_stmt ();
12297       break;
12298
12299     case SWITCH_STMT:
12300       stmt = begin_switch_stmt ();
12301       tmp = RECUR (SWITCH_STMT_COND (t));
12302       finish_switch_cond (tmp, stmt);
12303       RECUR (SWITCH_STMT_BODY (t));
12304       finish_switch_stmt (stmt);
12305       break;
12306
12307     case CASE_LABEL_EXPR:
12308       finish_case_label (EXPR_LOCATION (t),
12309                          RECUR (CASE_LOW (t)),
12310                          RECUR (CASE_HIGH (t)));
12311       break;
12312
12313     case LABEL_EXPR:
12314       {
12315         tree decl = LABEL_EXPR_LABEL (t);
12316         tree label;
12317
12318         label = finish_label_stmt (DECL_NAME (decl));
12319         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12320           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12321       }
12322       break;
12323
12324     case GOTO_EXPR:
12325       tmp = GOTO_DESTINATION (t);
12326       if (TREE_CODE (tmp) != LABEL_DECL)
12327         /* Computed goto's must be tsubst'd into.  On the other hand,
12328            non-computed gotos must not be; the identifier in question
12329            will have no binding.  */
12330         tmp = RECUR (tmp);
12331       else
12332         tmp = DECL_NAME (tmp);
12333       finish_goto_stmt (tmp);
12334       break;
12335
12336     case ASM_EXPR:
12337       tmp = finish_asm_stmt
12338         (ASM_VOLATILE_P (t),
12339          RECUR (ASM_STRING (t)),
12340          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12341          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12342          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12343          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12344       {
12345         tree asm_expr = tmp;
12346         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12347           asm_expr = TREE_OPERAND (asm_expr, 0);
12348         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12349       }
12350       break;
12351
12352     case TRY_BLOCK:
12353       if (CLEANUP_P (t))
12354         {
12355           stmt = begin_try_block ();
12356           RECUR (TRY_STMTS (t));
12357           finish_cleanup_try_block (stmt);
12358           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12359         }
12360       else
12361         {
12362           tree compound_stmt = NULL_TREE;
12363
12364           if (FN_TRY_BLOCK_P (t))
12365             stmt = begin_function_try_block (&compound_stmt);
12366           else
12367             stmt = begin_try_block ();
12368
12369           RECUR (TRY_STMTS (t));
12370
12371           if (FN_TRY_BLOCK_P (t))
12372             finish_function_try_block (stmt);
12373           else
12374             finish_try_block (stmt);
12375
12376           RECUR (TRY_HANDLERS (t));
12377           if (FN_TRY_BLOCK_P (t))
12378             finish_function_handler_sequence (stmt, compound_stmt);
12379           else
12380             finish_handler_sequence (stmt);
12381         }
12382       break;
12383
12384     case HANDLER:
12385       {
12386         tree decl = HANDLER_PARMS (t);
12387
12388         if (decl)
12389           {
12390             decl = tsubst (decl, args, complain, in_decl);
12391             /* Prevent instantiate_decl from trying to instantiate
12392                this variable.  We've already done all that needs to be
12393                done.  */
12394             if (decl != error_mark_node)
12395               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12396           }
12397         stmt = begin_handler ();
12398         finish_handler_parms (decl, stmt);
12399         RECUR (HANDLER_BODY (t));
12400         finish_handler (stmt);
12401       }
12402       break;
12403
12404     case TAG_DEFN:
12405       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12406       break;
12407
12408     case STATIC_ASSERT:
12409       {
12410         tree condition = 
12411           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12412                        args,
12413                        complain, in_decl,
12414                        /*integral_constant_expression_p=*/true);
12415         finish_static_assert (condition,
12416                               STATIC_ASSERT_MESSAGE (t),
12417                               STATIC_ASSERT_SOURCE_LOCATION (t),
12418                               /*member_p=*/false);
12419       }
12420       break;
12421
12422     case OMP_PARALLEL:
12423       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12424                                 args, complain, in_decl);
12425       stmt = begin_omp_parallel ();
12426       RECUR (OMP_PARALLEL_BODY (t));
12427       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12428         = OMP_PARALLEL_COMBINED (t);
12429       break;
12430
12431     case OMP_TASK:
12432       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12433                                 args, complain, in_decl);
12434       stmt = begin_omp_task ();
12435       RECUR (OMP_TASK_BODY (t));
12436       finish_omp_task (tmp, stmt);
12437       break;
12438
12439     case OMP_FOR:
12440       {
12441         tree clauses, body, pre_body;
12442         tree declv, initv, condv, incrv;
12443         int i;
12444
12445         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12446                                       args, complain, in_decl);
12447         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12448         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12449         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12450         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12451
12452         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12453           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12454                                    &clauses, args, complain, in_decl,
12455                                    integral_constant_expression_p);
12456
12457         stmt = begin_omp_structured_block ();
12458
12459         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12460           if (TREE_VEC_ELT (initv, i) == NULL
12461               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12462             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12463           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12464             {
12465               tree init = RECUR (TREE_VEC_ELT (initv, i));
12466               gcc_assert (init == TREE_VEC_ELT (declv, i));
12467               TREE_VEC_ELT (initv, i) = NULL_TREE;
12468             }
12469           else
12470             {
12471               tree decl_expr = TREE_VEC_ELT (initv, i);
12472               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12473               gcc_assert (init != NULL);
12474               TREE_VEC_ELT (initv, i) = RECUR (init);
12475               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12476               RECUR (decl_expr);
12477               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12478             }
12479
12480         pre_body = push_stmt_list ();
12481         RECUR (OMP_FOR_PRE_BODY (t));
12482         pre_body = pop_stmt_list (pre_body);
12483
12484         body = push_stmt_list ();
12485         RECUR (OMP_FOR_BODY (t));
12486         body = pop_stmt_list (body);
12487
12488         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12489                             body, pre_body, clauses);
12490
12491         add_stmt (finish_omp_structured_block (stmt));
12492       }
12493       break;
12494
12495     case OMP_SECTIONS:
12496     case OMP_SINGLE:
12497       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12498       stmt = push_stmt_list ();
12499       RECUR (OMP_BODY (t));
12500       stmt = pop_stmt_list (stmt);
12501
12502       t = copy_node (t);
12503       OMP_BODY (t) = stmt;
12504       OMP_CLAUSES (t) = tmp;
12505       add_stmt (t);
12506       break;
12507
12508     case OMP_SECTION:
12509     case OMP_CRITICAL:
12510     case OMP_MASTER:
12511     case OMP_ORDERED:
12512       stmt = push_stmt_list ();
12513       RECUR (OMP_BODY (t));
12514       stmt = pop_stmt_list (stmt);
12515
12516       t = copy_node (t);
12517       OMP_BODY (t) = stmt;
12518       add_stmt (t);
12519       break;
12520
12521     case OMP_ATOMIC:
12522       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12523       {
12524         tree op1 = TREE_OPERAND (t, 1);
12525         tree lhs = RECUR (TREE_OPERAND (op1, 0));
12526         tree rhs = RECUR (TREE_OPERAND (op1, 1));
12527         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
12528       }
12529       break;
12530
12531     case EXPR_PACK_EXPANSION:
12532       error ("invalid use of pack expansion expression");
12533       return error_mark_node;
12534
12535     case NONTYPE_ARGUMENT_PACK:
12536       error ("use %<...%> to expand argument pack");
12537       return error_mark_node;
12538
12539     default:
12540       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12541
12542       return tsubst_copy_and_build (t, args, complain, in_decl,
12543                                     /*function_p=*/false,
12544                                     integral_constant_expression_p);
12545     }
12546
12547   return NULL_TREE;
12548 #undef RECUR
12549 }
12550
12551 /* T is a postfix-expression that is not being used in a function
12552    call.  Return the substituted version of T.  */
12553
12554 static tree
12555 tsubst_non_call_postfix_expression (tree t, tree args,
12556                                     tsubst_flags_t complain,
12557                                     tree in_decl)
12558 {
12559   if (TREE_CODE (t) == SCOPE_REF)
12560     t = tsubst_qualified_id (t, args, complain, in_decl,
12561                              /*done=*/false, /*address_p=*/false);
12562   else
12563     t = tsubst_copy_and_build (t, args, complain, in_decl,
12564                                /*function_p=*/false,
12565                                /*integral_constant_expression_p=*/false);
12566
12567   return t;
12568 }
12569
12570 /* Like tsubst but deals with expressions and performs semantic
12571    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12572
12573 tree
12574 tsubst_copy_and_build (tree t,
12575                        tree args,
12576                        tsubst_flags_t complain,
12577                        tree in_decl,
12578                        bool function_p,
12579                        bool integral_constant_expression_p)
12580 {
12581 #define RECUR(NODE)                                             \
12582   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12583                          /*function_p=*/false,                  \
12584                          integral_constant_expression_p)
12585
12586   tree op1;
12587
12588   if (t == NULL_TREE || t == error_mark_node)
12589     return t;
12590
12591   switch (TREE_CODE (t))
12592     {
12593     case USING_DECL:
12594       t = DECL_NAME (t);
12595       /* Fall through.  */
12596     case IDENTIFIER_NODE:
12597       {
12598         tree decl;
12599         cp_id_kind idk;
12600         bool non_integral_constant_expression_p;
12601         const char *error_msg;
12602
12603         if (IDENTIFIER_TYPENAME_P (t))
12604           {
12605             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12606             t = mangle_conv_op_name_for_type (new_type);
12607           }
12608
12609         /* Look up the name.  */
12610         decl = lookup_name (t);
12611
12612         /* By convention, expressions use ERROR_MARK_NODE to indicate
12613            failure, not NULL_TREE.  */
12614         if (decl == NULL_TREE)
12615           decl = error_mark_node;
12616
12617         decl = finish_id_expression (t, decl, NULL_TREE,
12618                                      &idk,
12619                                      integral_constant_expression_p,
12620                                      /*allow_non_integral_constant_expression_p=*/false,
12621                                      &non_integral_constant_expression_p,
12622                                      /*template_p=*/false,
12623                                      /*done=*/true,
12624                                      /*address_p=*/false,
12625                                      /*template_arg_p=*/false,
12626                                      &error_msg,
12627                                      input_location);
12628         if (error_msg)
12629           error (error_msg);
12630         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12631           decl = unqualified_name_lookup_error (decl);
12632         return decl;
12633       }
12634
12635     case TEMPLATE_ID_EXPR:
12636       {
12637         tree object;
12638         tree templ = RECUR (TREE_OPERAND (t, 0));
12639         tree targs = TREE_OPERAND (t, 1);
12640
12641         if (targs)
12642           targs = tsubst_template_args (targs, args, complain, in_decl);
12643
12644         if (TREE_CODE (templ) == COMPONENT_REF)
12645           {
12646             object = TREE_OPERAND (templ, 0);
12647             templ = TREE_OPERAND (templ, 1);
12648           }
12649         else
12650           object = NULL_TREE;
12651         templ = lookup_template_function (templ, targs);
12652
12653         if (object)
12654           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12655                          object, templ, NULL_TREE);
12656         else
12657           return baselink_for_fns (templ);
12658       }
12659
12660     case INDIRECT_REF:
12661       {
12662         tree r = RECUR (TREE_OPERAND (t, 0));
12663
12664         if (REFERENCE_REF_P (t))
12665           {
12666             /* A type conversion to reference type will be enclosed in
12667                such an indirect ref, but the substitution of the cast
12668                will have also added such an indirect ref.  */
12669             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12670               r = convert_from_reference (r);
12671           }
12672         else
12673           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12674         return r;
12675       }
12676
12677     case NOP_EXPR:
12678       return build_nop
12679         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12680          RECUR (TREE_OPERAND (t, 0)));
12681
12682     case CAST_EXPR:
12683     case REINTERPRET_CAST_EXPR:
12684     case CONST_CAST_EXPR:
12685     case DYNAMIC_CAST_EXPR:
12686     case STATIC_CAST_EXPR:
12687       {
12688         tree type;
12689         tree op;
12690
12691         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12692         if (integral_constant_expression_p
12693             && !cast_valid_in_integral_constant_expression_p (type))
12694           {
12695             if (complain & tf_error)
12696               error ("a cast to a type other than an integral or "
12697                      "enumeration type cannot appear in a constant-expression");
12698             return error_mark_node; 
12699           }
12700
12701         op = RECUR (TREE_OPERAND (t, 0));
12702
12703         switch (TREE_CODE (t))
12704           {
12705           case CAST_EXPR:
12706             return build_functional_cast (type, op, complain);
12707           case REINTERPRET_CAST_EXPR:
12708             return build_reinterpret_cast (type, op, complain);
12709           case CONST_CAST_EXPR:
12710             return build_const_cast (type, op, complain);
12711           case DYNAMIC_CAST_EXPR:
12712             return build_dynamic_cast (type, op, complain);
12713           case STATIC_CAST_EXPR:
12714             return build_static_cast (type, op, complain);
12715           default:
12716             gcc_unreachable ();
12717           }
12718       }
12719
12720     case POSTDECREMENT_EXPR:
12721     case POSTINCREMENT_EXPR:
12722       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12723                                                 args, complain, in_decl);
12724       return build_x_unary_op (TREE_CODE (t), op1, complain);
12725
12726     case PREDECREMENT_EXPR:
12727     case PREINCREMENT_EXPR:
12728     case NEGATE_EXPR:
12729     case BIT_NOT_EXPR:
12730     case ABS_EXPR:
12731     case TRUTH_NOT_EXPR:
12732     case UNARY_PLUS_EXPR:  /* Unary + */
12733     case REALPART_EXPR:
12734     case IMAGPART_EXPR:
12735       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12736                                complain);
12737
12738     case ADDR_EXPR:
12739       op1 = TREE_OPERAND (t, 0);
12740       if (TREE_CODE (op1) == LABEL_DECL)
12741         return finish_label_address_expr (DECL_NAME (op1),
12742                                           EXPR_LOCATION (op1));
12743       if (TREE_CODE (op1) == SCOPE_REF)
12744         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12745                                    /*done=*/true, /*address_p=*/true);
12746       else
12747         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12748                                                   in_decl);
12749       return build_x_unary_op (ADDR_EXPR, op1, complain);
12750
12751     case PLUS_EXPR:
12752     case MINUS_EXPR:
12753     case MULT_EXPR:
12754     case TRUNC_DIV_EXPR:
12755     case CEIL_DIV_EXPR:
12756     case FLOOR_DIV_EXPR:
12757     case ROUND_DIV_EXPR:
12758     case EXACT_DIV_EXPR:
12759     case BIT_AND_EXPR:
12760     case BIT_IOR_EXPR:
12761     case BIT_XOR_EXPR:
12762     case TRUNC_MOD_EXPR:
12763     case FLOOR_MOD_EXPR:
12764     case TRUTH_ANDIF_EXPR:
12765     case TRUTH_ORIF_EXPR:
12766     case TRUTH_AND_EXPR:
12767     case TRUTH_OR_EXPR:
12768     case RSHIFT_EXPR:
12769     case LSHIFT_EXPR:
12770     case RROTATE_EXPR:
12771     case LROTATE_EXPR:
12772     case EQ_EXPR:
12773     case NE_EXPR:
12774     case MAX_EXPR:
12775     case MIN_EXPR:
12776     case LE_EXPR:
12777     case GE_EXPR:
12778     case LT_EXPR:
12779     case GT_EXPR:
12780     case MEMBER_REF:
12781     case DOTSTAR_EXPR:
12782       return build_x_binary_op
12783         (TREE_CODE (t),
12784          RECUR (TREE_OPERAND (t, 0)),
12785          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12786           ? ERROR_MARK
12787           : TREE_CODE (TREE_OPERAND (t, 0))),
12788          RECUR (TREE_OPERAND (t, 1)),
12789          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12790           ? ERROR_MARK
12791           : TREE_CODE (TREE_OPERAND (t, 1))),
12792          /*overload=*/NULL,
12793          complain);
12794
12795     case SCOPE_REF:
12796       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12797                                   /*address_p=*/false);
12798     case ARRAY_REF:
12799       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12800                                                 args, complain, in_decl);
12801       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12802
12803     case SIZEOF_EXPR:
12804       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12805         return tsubst_copy (t, args, complain, in_decl);
12806       /* Fall through */
12807       
12808     case ALIGNOF_EXPR:
12809       op1 = TREE_OPERAND (t, 0);
12810       if (!args)
12811         {
12812           /* When there are no ARGS, we are trying to evaluate a
12813              non-dependent expression from the parser.  Trying to do
12814              the substitutions may not work.  */
12815           if (!TYPE_P (op1))
12816             op1 = TREE_TYPE (op1);
12817         }
12818       else
12819         {
12820           ++cp_unevaluated_operand;
12821           ++c_inhibit_evaluation_warnings;
12822           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12823                                        /*function_p=*/false,
12824                                        /*integral_constant_expression_p=*/false);
12825           --cp_unevaluated_operand;
12826           --c_inhibit_evaluation_warnings;
12827         }
12828       if (TYPE_P (op1))
12829         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12830                                            complain & tf_error);
12831       else
12832         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12833                                            complain & tf_error);
12834
12835     case AT_ENCODE_EXPR:
12836       {
12837         op1 = TREE_OPERAND (t, 0);
12838         ++cp_unevaluated_operand;
12839         ++c_inhibit_evaluation_warnings;
12840         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12841                                      /*function_p=*/false,
12842                                      /*integral_constant_expression_p=*/false);
12843         --cp_unevaluated_operand;
12844         --c_inhibit_evaluation_warnings;
12845         return objc_build_encode_expr (op1);
12846       }
12847
12848     case NOEXCEPT_EXPR:
12849       op1 = TREE_OPERAND (t, 0);
12850       ++cp_unevaluated_operand;
12851       ++c_inhibit_evaluation_warnings;
12852       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12853                                    /*function_p=*/false,
12854                                    /*integral_constant_expression_p=*/false);
12855       --cp_unevaluated_operand;
12856       --c_inhibit_evaluation_warnings;
12857       return finish_noexcept_expr (op1, complain);
12858
12859     case MODOP_EXPR:
12860       {
12861         tree r = build_x_modify_expr
12862           (RECUR (TREE_OPERAND (t, 0)),
12863            TREE_CODE (TREE_OPERAND (t, 1)),
12864            RECUR (TREE_OPERAND (t, 2)),
12865            complain);
12866         /* TREE_NO_WARNING must be set if either the expression was
12867            parenthesized or it uses an operator such as >>= rather
12868            than plain assignment.  In the former case, it was already
12869            set and must be copied.  In the latter case,
12870            build_x_modify_expr sets it and it must not be reset
12871            here.  */
12872         if (TREE_NO_WARNING (t))
12873           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12874         return r;
12875       }
12876
12877     case ARROW_EXPR:
12878       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12879                                                 args, complain, in_decl);
12880       /* Remember that there was a reference to this entity.  */
12881       if (DECL_P (op1))
12882         mark_used (op1);
12883       return build_x_arrow (op1);
12884
12885     case NEW_EXPR:
12886       {
12887         tree placement = RECUR (TREE_OPERAND (t, 0));
12888         tree init = RECUR (TREE_OPERAND (t, 3));
12889         VEC(tree,gc) *placement_vec;
12890         VEC(tree,gc) *init_vec;
12891         tree ret;
12892
12893         if (placement == NULL_TREE)
12894           placement_vec = NULL;
12895         else
12896           {
12897             placement_vec = make_tree_vector ();
12898             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12899               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12900           }
12901
12902         /* If there was an initializer in the original tree, but it
12903            instantiated to an empty list, then we should pass a
12904            non-NULL empty vector to tell build_new that it was an
12905            empty initializer() rather than no initializer.  This can
12906            only happen when the initializer is a pack expansion whose
12907            parameter packs are of length zero.  */
12908         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12909           init_vec = NULL;
12910         else
12911           {
12912             init_vec = make_tree_vector ();
12913             if (init == void_zero_node)
12914               gcc_assert (init_vec != NULL);
12915             else
12916               {
12917                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12918                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12919               }
12920           }
12921
12922         ret = build_new (&placement_vec,
12923                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
12924                          RECUR (TREE_OPERAND (t, 2)),
12925                          &init_vec,
12926                          NEW_EXPR_USE_GLOBAL (t),
12927                          complain);
12928
12929         if (placement_vec != NULL)
12930           release_tree_vector (placement_vec);
12931         if (init_vec != NULL)
12932           release_tree_vector (init_vec);
12933
12934         return ret;
12935       }
12936
12937     case DELETE_EXPR:
12938      return delete_sanity
12939        (RECUR (TREE_OPERAND (t, 0)),
12940         RECUR (TREE_OPERAND (t, 1)),
12941         DELETE_EXPR_USE_VEC (t),
12942         DELETE_EXPR_USE_GLOBAL (t),
12943         complain);
12944
12945     case COMPOUND_EXPR:
12946       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12947                                     RECUR (TREE_OPERAND (t, 1)),
12948                                     complain);
12949
12950     case CALL_EXPR:
12951       {
12952         tree function;
12953         VEC(tree,gc) *call_args;
12954         unsigned int nargs, i;
12955         bool qualified_p;
12956         bool koenig_p;
12957         tree ret;
12958
12959         function = CALL_EXPR_FN (t);
12960         /* When we parsed the expression,  we determined whether or
12961            not Koenig lookup should be performed.  */
12962         koenig_p = KOENIG_LOOKUP_P (t);
12963         if (TREE_CODE (function) == SCOPE_REF)
12964           {
12965             qualified_p = true;
12966             function = tsubst_qualified_id (function, args, complain, in_decl,
12967                                             /*done=*/false,
12968                                             /*address_p=*/false);
12969           }
12970         else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
12971           {
12972             /* Do nothing; calling tsubst_copy_and_build on an identifier
12973                would incorrectly perform unqualified lookup again.
12974
12975                Note that we can also have an IDENTIFIER_NODE if the earlier
12976                unqualified lookup found a member function; in that case
12977                koenig_p will be false and we do want to do the lookup
12978                again to find the instantiated member function.
12979
12980                FIXME but doing that causes c++/15272, so we need to stop
12981                using IDENTIFIER_NODE in that situation.  */
12982             qualified_p = false;
12983           }
12984         else
12985           {
12986             if (TREE_CODE (function) == COMPONENT_REF)
12987               {
12988                 tree op = TREE_OPERAND (function, 1);
12989
12990                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12991                                || (BASELINK_P (op)
12992                                    && BASELINK_QUALIFIED_P (op)));
12993               }
12994             else
12995               qualified_p = false;
12996
12997             function = tsubst_copy_and_build (function, args, complain,
12998                                               in_decl,
12999                                               !qualified_p,
13000                                               integral_constant_expression_p);
13001
13002             if (BASELINK_P (function))
13003               qualified_p = true;
13004           }
13005
13006         nargs = call_expr_nargs (t);
13007         call_args = make_tree_vector ();
13008         for (i = 0; i < nargs; ++i)
13009           {
13010             tree arg = CALL_EXPR_ARG (t, i);
13011
13012             if (!PACK_EXPANSION_P (arg))
13013               VEC_safe_push (tree, gc, call_args,
13014                              RECUR (CALL_EXPR_ARG (t, i)));
13015             else
13016               {
13017                 /* Expand the pack expansion and push each entry onto
13018                    CALL_ARGS.  */
13019                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
13020                 if (TREE_CODE (arg) == TREE_VEC)
13021                   {
13022                     unsigned int len, j;
13023
13024                     len = TREE_VEC_LENGTH (arg);
13025                     for (j = 0; j < len; ++j)
13026                       {
13027                         tree value = TREE_VEC_ELT (arg, j);
13028                         if (value != NULL_TREE)
13029                           value = convert_from_reference (value);
13030                         VEC_safe_push (tree, gc, call_args, value);
13031                       }
13032                   }
13033                 else
13034                   {
13035                     /* A partial substitution.  Add one entry.  */
13036                     VEC_safe_push (tree, gc, call_args, arg);
13037                   }
13038               }
13039           }
13040
13041         /* We do not perform argument-dependent lookup if normal
13042            lookup finds a non-function, in accordance with the
13043            expected resolution of DR 218.  */
13044         if (koenig_p
13045             && ((is_overloaded_fn (function)
13046                  /* If lookup found a member function, the Koenig lookup is
13047                     not appropriate, even if an unqualified-name was used
13048                     to denote the function.  */
13049                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
13050                 || TREE_CODE (function) == IDENTIFIER_NODE)
13051             /* Only do this when substitution turns a dependent call
13052                into a non-dependent call.  */
13053             && type_dependent_expression_p_push (t)
13054             && !any_type_dependent_arguments_p (call_args))
13055           function = perform_koenig_lookup (function, call_args, false,
13056                                             tf_none);
13057
13058         if (TREE_CODE (function) == IDENTIFIER_NODE
13059             && !any_type_dependent_arguments_p (call_args))
13060           {
13061             if (koenig_p && (complain & tf_warning_or_error))
13062               {
13063                 /* For backwards compatibility and good diagnostics, try
13064                    the unqualified lookup again if we aren't in SFINAE
13065                    context.  */
13066                 tree unq = (tsubst_copy_and_build
13067                             (function, args, complain, in_decl, true,
13068                              integral_constant_expression_p));
13069                 if (unq != function)
13070                   {
13071                     tree fn = unq;
13072                     if (TREE_CODE (fn) == COMPONENT_REF)
13073                       fn = TREE_OPERAND (fn, 1);
13074                     if (is_overloaded_fn (fn))
13075                       fn = get_first_fn (fn);
13076                     permerror (EXPR_LOC_OR_HERE (t),
13077                                "%qD was not declared in this scope, "
13078                                "and no declarations were found by "
13079                                "argument-dependent lookup at the point "
13080                                "of instantiation", function);
13081                     if (DECL_CLASS_SCOPE_P (fn))
13082                       {
13083                         inform (EXPR_LOC_OR_HERE (t),
13084                                 "declarations in dependent base %qT are "
13085                                 "not found by unqualified lookup",
13086                                 DECL_CLASS_CONTEXT (fn));
13087                         if (current_class_ptr)
13088                           inform (EXPR_LOC_OR_HERE (t),
13089                                   "use %<this->%D%> instead", function);
13090                         else
13091                           inform (EXPR_LOC_OR_HERE (t),
13092                                   "use %<%T::%D%> instead",
13093                                   current_class_name, function);
13094                       }
13095                     else
13096                       inform (0, "%q+D declared here, later in the "
13097                                 "translation unit", fn);
13098                     function = unq;
13099                   }
13100               }
13101             if (TREE_CODE (function) == IDENTIFIER_NODE)
13102               {
13103                 unqualified_name_lookup_error (function);
13104                 release_tree_vector (call_args);
13105                 return error_mark_node;
13106               }
13107           }
13108
13109         /* Remember that there was a reference to this entity.  */
13110         if (DECL_P (function))
13111           mark_used (function);
13112
13113         if (TREE_CODE (function) == OFFSET_REF)
13114           ret = build_offset_ref_call_from_tree (function, &call_args);
13115         else if (TREE_CODE (function) == COMPONENT_REF)
13116           {
13117             tree instance = TREE_OPERAND (function, 0);
13118             tree fn = TREE_OPERAND (function, 1);
13119
13120             if (processing_template_decl
13121                 && (type_dependent_expression_p (instance)
13122                     || (!BASELINK_P (fn)
13123                         && TREE_CODE (fn) != FIELD_DECL)
13124                     || type_dependent_expression_p (fn)
13125                     || any_type_dependent_arguments_p (call_args)))
13126               ret = build_nt_call_vec (function, call_args);
13127             else if (!BASELINK_P (fn))
13128               ret = finish_call_expr (function, &call_args,
13129                                        /*disallow_virtual=*/false,
13130                                        /*koenig_p=*/false,
13131                                        complain);
13132             else
13133               ret = (build_new_method_call
13134                       (instance, fn,
13135                        &call_args, NULL_TREE,
13136                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
13137                        /*fn_p=*/NULL,
13138                        complain));
13139           }
13140         else
13141           ret = finish_call_expr (function, &call_args,
13142                                   /*disallow_virtual=*/qualified_p,
13143                                   koenig_p,
13144                                   complain);
13145
13146         release_tree_vector (call_args);
13147
13148         return ret;
13149       }
13150
13151     case COND_EXPR:
13152       return build_x_conditional_expr
13153         (RECUR (TREE_OPERAND (t, 0)),
13154          RECUR (TREE_OPERAND (t, 1)),
13155          RECUR (TREE_OPERAND (t, 2)),
13156          complain);
13157
13158     case PSEUDO_DTOR_EXPR:
13159       return finish_pseudo_destructor_expr
13160         (RECUR (TREE_OPERAND (t, 0)),
13161          RECUR (TREE_OPERAND (t, 1)),
13162          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13163
13164     case TREE_LIST:
13165       {
13166         tree purpose, value, chain;
13167
13168         if (t == void_list_node)
13169           return t;
13170
13171         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13172             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13173           {
13174             /* We have pack expansions, so expand those and
13175                create a new list out of it.  */
13176             tree purposevec = NULL_TREE;
13177             tree valuevec = NULL_TREE;
13178             tree chain;
13179             int i, len = -1;
13180
13181             /* Expand the argument expressions.  */
13182             if (TREE_PURPOSE (t))
13183               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13184                                                  complain, in_decl);
13185             if (TREE_VALUE (t))
13186               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13187                                                complain, in_decl);
13188
13189             /* Build the rest of the list.  */
13190             chain = TREE_CHAIN (t);
13191             if (chain && chain != void_type_node)
13192               chain = RECUR (chain);
13193
13194             /* Determine the number of arguments.  */
13195             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13196               {
13197                 len = TREE_VEC_LENGTH (purposevec);
13198                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13199               }
13200             else if (TREE_CODE (valuevec) == TREE_VEC)
13201               len = TREE_VEC_LENGTH (valuevec);
13202             else
13203               {
13204                 /* Since we only performed a partial substitution into
13205                    the argument pack, we only return a single list
13206                    node.  */
13207                 if (purposevec == TREE_PURPOSE (t)
13208                     && valuevec == TREE_VALUE (t)
13209                     && chain == TREE_CHAIN (t))
13210                   return t;
13211
13212                 return tree_cons (purposevec, valuevec, chain);
13213               }
13214             
13215             /* Convert the argument vectors into a TREE_LIST */
13216             i = len;
13217             while (i > 0)
13218               {
13219                 /* Grab the Ith values.  */
13220                 i--;
13221                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13222                                      : NULL_TREE;
13223                 value 
13224                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13225                              : NULL_TREE;
13226
13227                 /* Build the list (backwards).  */
13228                 chain = tree_cons (purpose, value, chain);
13229               }
13230
13231             return chain;
13232           }
13233
13234         purpose = TREE_PURPOSE (t);
13235         if (purpose)
13236           purpose = RECUR (purpose);
13237         value = TREE_VALUE (t);
13238         if (value)
13239           value = RECUR (value);
13240         chain = TREE_CHAIN (t);
13241         if (chain && chain != void_type_node)
13242           chain = RECUR (chain);
13243         if (purpose == TREE_PURPOSE (t)
13244             && value == TREE_VALUE (t)
13245             && chain == TREE_CHAIN (t))
13246           return t;
13247         return tree_cons (purpose, value, chain);
13248       }
13249
13250     case COMPONENT_REF:
13251       {
13252         tree object;
13253         tree object_type;
13254         tree member;
13255
13256         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13257                                                      args, complain, in_decl);
13258         /* Remember that there was a reference to this entity.  */
13259         if (DECL_P (object))
13260           mark_used (object);
13261         object_type = TREE_TYPE (object);
13262
13263         member = TREE_OPERAND (t, 1);
13264         if (BASELINK_P (member))
13265           member = tsubst_baselink (member,
13266                                     non_reference (TREE_TYPE (object)),
13267                                     args, complain, in_decl);
13268         else
13269           member = tsubst_copy (member, args, complain, in_decl);
13270         if (member == error_mark_node)
13271           return error_mark_node;
13272
13273         if (object_type && !CLASS_TYPE_P (object_type))
13274           {
13275             if (SCALAR_TYPE_P (object_type))
13276               {
13277                 tree s = NULL_TREE;
13278                 tree dtor = member;
13279
13280                 if (TREE_CODE (dtor) == SCOPE_REF)
13281                   {
13282                     s = TREE_OPERAND (dtor, 0);
13283                     dtor = TREE_OPERAND (dtor, 1);
13284                   }
13285                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13286                   {
13287                     dtor = TREE_OPERAND (dtor, 0);
13288                     if (TYPE_P (dtor))
13289                       return finish_pseudo_destructor_expr (object, s, dtor);
13290                   }
13291               }
13292           }
13293         else if (TREE_CODE (member) == SCOPE_REF
13294                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13295           {
13296             tree tmpl;
13297             tree args;
13298
13299             /* Lookup the template functions now that we know what the
13300                scope is.  */
13301             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13302             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13303             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
13304                                             /*is_type_p=*/false,
13305                                             /*complain=*/false);
13306             if (BASELINK_P (member))
13307               {
13308                 BASELINK_FUNCTIONS (member)
13309                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13310                               args);
13311                 member = (adjust_result_of_qualified_name_lookup
13312                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13313                            object_type));
13314               }
13315             else
13316               {
13317                 qualified_name_lookup_error (object_type, tmpl, member,
13318                                              input_location);
13319                 return error_mark_node;
13320               }
13321           }
13322         else if (TREE_CODE (member) == SCOPE_REF
13323                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13324                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13325           {
13326             if (complain & tf_error)
13327               {
13328                 if (TYPE_P (TREE_OPERAND (member, 0)))
13329                   error ("%qT is not a class or namespace",
13330                          TREE_OPERAND (member, 0));
13331                 else
13332                   error ("%qD is not a class or namespace",
13333                          TREE_OPERAND (member, 0));
13334               }
13335             return error_mark_node;
13336           }
13337         else if (TREE_CODE (member) == FIELD_DECL)
13338           return finish_non_static_data_member (member, object, NULL_TREE);
13339
13340         return finish_class_member_access_expr (object, member,
13341                                                 /*template_p=*/false,
13342                                                 complain);
13343       }
13344
13345     case THROW_EXPR:
13346       return build_throw
13347         (RECUR (TREE_OPERAND (t, 0)));
13348
13349     case CONSTRUCTOR:
13350       {
13351         VEC(constructor_elt,gc) *n;
13352         constructor_elt *ce;
13353         unsigned HOST_WIDE_INT idx;
13354         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13355         bool process_index_p;
13356         int newlen;
13357         bool need_copy_p = false;
13358         tree r;
13359
13360         if (type == error_mark_node)
13361           return error_mark_node;
13362
13363         /* digest_init will do the wrong thing if we let it.  */
13364         if (type && TYPE_PTRMEMFUNC_P (type))
13365           return t;
13366
13367         /* We do not want to process the index of aggregate
13368            initializers as they are identifier nodes which will be
13369            looked up by digest_init.  */
13370         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13371
13372         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13373         newlen = VEC_length (constructor_elt, n);
13374         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13375           {
13376             if (ce->index && process_index_p)
13377               ce->index = RECUR (ce->index);
13378
13379             if (PACK_EXPANSION_P (ce->value))
13380               {
13381                 /* Substitute into the pack expansion.  */
13382                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13383                                                   in_decl);
13384
13385                 if (ce->value == error_mark_node
13386                     || PACK_EXPANSION_P (ce->value))
13387                   ;
13388                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13389                   /* Just move the argument into place.  */
13390                   ce->value = TREE_VEC_ELT (ce->value, 0);
13391                 else
13392                   {
13393                     /* Update the length of the final CONSTRUCTOR
13394                        arguments vector, and note that we will need to
13395                        copy.*/
13396                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13397                     need_copy_p = true;
13398                   }
13399               }
13400             else
13401               ce->value = RECUR (ce->value);
13402           }
13403
13404         if (need_copy_p)
13405           {
13406             VEC(constructor_elt,gc) *old_n = n;
13407
13408             n = VEC_alloc (constructor_elt, gc, newlen);
13409             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13410               {
13411                 if (TREE_CODE (ce->value) == TREE_VEC)
13412                   {
13413                     int i, len = TREE_VEC_LENGTH (ce->value);
13414                     for (i = 0; i < len; ++i)
13415                       CONSTRUCTOR_APPEND_ELT (n, 0,
13416                                               TREE_VEC_ELT (ce->value, i));
13417                   }
13418                 else
13419                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13420               }
13421           }
13422
13423         r = build_constructor (init_list_type_node, n);
13424         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13425
13426         if (TREE_HAS_CONSTRUCTOR (t))
13427           return finish_compound_literal (type, r, complain);
13428
13429         TREE_TYPE (r) = type;
13430         return r;
13431       }
13432
13433     case TYPEID_EXPR:
13434       {
13435         tree operand_0 = TREE_OPERAND (t, 0);
13436         if (TYPE_P (operand_0))
13437           {
13438             operand_0 = tsubst (operand_0, args, complain, in_decl);
13439             return get_typeid (operand_0);
13440           }
13441         else
13442           {
13443             operand_0 = RECUR (operand_0);
13444             return build_typeid (operand_0);
13445           }
13446       }
13447
13448     case VAR_DECL:
13449       if (!args)
13450         return t;
13451       /* Fall through */
13452
13453     case PARM_DECL:
13454       {
13455         tree r = tsubst_copy (t, args, complain, in_decl);
13456
13457         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13458           /* If the original type was a reference, we'll be wrapped in
13459              the appropriate INDIRECT_REF.  */
13460           r = convert_from_reference (r);
13461         return r;
13462       }
13463
13464     case VA_ARG_EXPR:
13465       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13466                              tsubst (TREE_TYPE (t), args, complain, in_decl));
13467
13468     case OFFSETOF_EXPR:
13469       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13470
13471     case TRAIT_EXPR:
13472       {
13473         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13474                                   complain, in_decl);
13475
13476         tree type2 = TRAIT_EXPR_TYPE2 (t);
13477         if (type2)
13478           type2 = tsubst_copy (type2, args, complain, in_decl);
13479         
13480         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13481       }
13482
13483     case STMT_EXPR:
13484       {
13485         tree old_stmt_expr = cur_stmt_expr;
13486         tree stmt_expr = begin_stmt_expr ();
13487
13488         cur_stmt_expr = stmt_expr;
13489         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13490                      integral_constant_expression_p);
13491         stmt_expr = finish_stmt_expr (stmt_expr, false);
13492         cur_stmt_expr = old_stmt_expr;
13493
13494         /* If the resulting list of expression statement is empty,
13495            fold it further into void_zero_node.  */
13496         if (empty_expr_stmt_p (stmt_expr))
13497           stmt_expr = void_zero_node;
13498
13499         return stmt_expr;
13500       }
13501
13502     case CONST_DECL:
13503       t = tsubst_copy (t, args, complain, in_decl);
13504       /* As in finish_id_expression, we resolve enumeration constants
13505          to their underlying values.  */
13506       if (TREE_CODE (t) == CONST_DECL)
13507         {
13508           used_types_insert (TREE_TYPE (t));
13509           return DECL_INITIAL (t);
13510         }
13511       return t;
13512
13513     case LAMBDA_EXPR:
13514       {
13515         tree r = build_lambda_expr ();
13516
13517         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
13518         TREE_TYPE (r) = type;
13519         CLASSTYPE_LAMBDA_EXPR (type) = r;
13520
13521         LAMBDA_EXPR_LOCATION (r)
13522           = LAMBDA_EXPR_LOCATION (t);
13523         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13524           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13525         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13526         LAMBDA_EXPR_DISCRIMINATOR (r)
13527           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13528         LAMBDA_EXPR_CAPTURE_LIST (r)
13529           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13530         LAMBDA_EXPR_EXTRA_SCOPE (r)
13531           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13532         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
13533                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
13534
13535         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13536         determine_visibility (TYPE_NAME (type));
13537         /* Now that we know visibility, instantiate the type so we have a
13538            declaration of the op() for later calls to lambda_function.  */
13539         complete_type (type);
13540
13541         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13542         if (type)
13543           apply_lambda_return_type (r, type);
13544
13545         return build_lambda_object (r);
13546       }
13547
13548     case TARGET_EXPR:
13549       /* We can get here for a constant initializer of non-dependent type.
13550          FIXME stop folding in cp_parser_initializer_clause.  */
13551       gcc_assert (TREE_CONSTANT (t));
13552       {
13553         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
13554         TREE_CONSTANT (r) = true;
13555         return r;
13556       }
13557
13558     default:
13559       /* Handle Objective-C++ constructs, if appropriate.  */
13560       {
13561         tree subst
13562           = objcp_tsubst_copy_and_build (t, args, complain,
13563                                          in_decl, /*function_p=*/false);
13564         if (subst)
13565           return subst;
13566       }
13567       return tsubst_copy (t, args, complain, in_decl);
13568     }
13569
13570 #undef RECUR
13571 }
13572
13573 /* Verify that the instantiated ARGS are valid. For type arguments,
13574    make sure that the type's linkage is ok. For non-type arguments,
13575    make sure they are constants if they are integral or enumerations.
13576    Emit an error under control of COMPLAIN, and return TRUE on error.  */
13577
13578 static bool
13579 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
13580 {
13581   if (ARGUMENT_PACK_P (t))
13582     {
13583       tree vec = ARGUMENT_PACK_ARGS (t);
13584       int len = TREE_VEC_LENGTH (vec);
13585       bool result = false;
13586       int i;
13587
13588       for (i = 0; i < len; ++i)
13589         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
13590           result = true;
13591       return result;
13592     }
13593   else if (TYPE_P (t))
13594     {
13595       /* [basic.link]: A name with no linkage (notably, the name
13596          of a class or enumeration declared in a local scope)
13597          shall not be used to declare an entity with linkage.
13598          This implies that names with no linkage cannot be used as
13599          template arguments
13600
13601          DR 757 relaxes this restriction for C++0x.  */
13602       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
13603                  : no_linkage_check (t, /*relaxed_p=*/false));
13604
13605       if (nt)
13606         {
13607           /* DR 488 makes use of a type with no linkage cause
13608              type deduction to fail.  */
13609           if (complain & tf_error)
13610             {
13611               if (TYPE_ANONYMOUS_P (nt))
13612                 error ("%qT is/uses anonymous type", t);
13613               else
13614                 error ("template argument for %qD uses local type %qT",
13615                        tmpl, t);
13616             }
13617           return true;
13618         }
13619       /* In order to avoid all sorts of complications, we do not
13620          allow variably-modified types as template arguments.  */
13621       else if (variably_modified_type_p (t, NULL_TREE))
13622         {
13623           if (complain & tf_error)
13624             error ("%qT is a variably modified type", t);
13625           return true;
13626         }
13627     }
13628   /* A non-type argument of integral or enumerated type must be a
13629      constant.  */
13630   else if (TREE_TYPE (t)
13631            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
13632            && !TREE_CONSTANT (t))
13633     {
13634       if (complain & tf_error)
13635         error ("integral expression %qE is not constant", t);
13636       return true;
13637     }
13638   return false;
13639 }
13640
13641 static bool
13642 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
13643 {
13644   int ix, len = DECL_NTPARMS (tmpl);
13645   bool result = false;
13646
13647   for (ix = 0; ix != len; ix++)
13648     {
13649       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
13650         result = true;
13651     }
13652   if (result && (complain & tf_error))
13653     error ("  trying to instantiate %qD", tmpl);
13654   return result;
13655 }
13656
13657 /* In C++0x, it's possible to have a function template whose type depends
13658    on itself recursively.  This is most obvious with decltype, but can also
13659    occur with enumeration scope (c++/48969).  So we need to catch infinite
13660    recursion and reject the substitution at deduction time; this function
13661    will return error_mark_node for any repeated substitution.
13662
13663    This also catches excessive recursion such as when f<N> depends on
13664    f<N-1> across all integers, and returns error_mark_node for all the
13665    substitutions back up to the initial one.
13666
13667    This is, of course, not reentrant.  */
13668
13669 static tree
13670 deduction_tsubst_fntype (tree fn, tree targs)
13671 {
13672   static bool excessive_deduction_depth;
13673   static int deduction_depth;
13674   struct pending_template *old_last_pend = last_pending_template;
13675
13676   tree fntype = TREE_TYPE (fn);
13677   tree tinst;
13678   tree r;
13679
13680   if (excessive_deduction_depth)
13681     return error_mark_node;
13682
13683   tinst = build_tree_list (fn, targs);
13684   if (!push_tinst_level (tinst))
13685     {
13686       excessive_deduction_depth = true;
13687       ggc_free (tinst);
13688       return error_mark_node;
13689     }
13690
13691   input_location = DECL_SOURCE_LOCATION (fn);
13692   ++deduction_depth;
13693   push_deduction_access_scope (fn);
13694   r = tsubst (fntype, targs, tf_none, NULL_TREE);
13695   pop_deduction_access_scope (fn);
13696   --deduction_depth;
13697
13698   if (excessive_deduction_depth)
13699     {
13700       r = error_mark_node;
13701       if (deduction_depth == 0)
13702         /* Reset once we're all the way out.  */
13703         excessive_deduction_depth = false;
13704     }
13705
13706   pop_tinst_level ();
13707   /* We can't free this if a pending_template entry is pointing at it.  */
13708   if (last_pending_template == old_last_pend)
13709     ggc_free (tinst);
13710   return r;
13711 }
13712
13713 /* Instantiate the indicated variable or function template TMPL with
13714    the template arguments in TARG_PTR.  */
13715
13716 static tree
13717 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
13718 {
13719   tree targ_ptr = orig_args;
13720   tree fndecl;
13721   tree gen_tmpl;
13722   tree spec;
13723   HOST_WIDE_INT saved_processing_template_decl;
13724
13725   if (tmpl == error_mark_node)
13726     return error_mark_node;
13727
13728   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
13729
13730   /* If this function is a clone, handle it specially.  */
13731   if (DECL_CLONED_FUNCTION_P (tmpl))
13732     {
13733       tree spec;
13734       tree clone;
13735
13736       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
13737          DECL_CLONED_FUNCTION.  */
13738       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
13739                                    targ_ptr, complain);
13740       if (spec == error_mark_node)
13741         return error_mark_node;
13742
13743       /* Look for the clone.  */
13744       FOR_EACH_CLONE (clone, spec)
13745         if (DECL_NAME (clone) == DECL_NAME (tmpl))
13746           return clone;
13747       /* We should always have found the clone by now.  */
13748       gcc_unreachable ();
13749       return NULL_TREE;
13750     }
13751
13752   /* Check to see if we already have this specialization.  */
13753   gen_tmpl = most_general_template (tmpl);
13754   if (tmpl != gen_tmpl)
13755     /* The TMPL is a partial instantiation.  To get a full set of
13756        arguments we must add the arguments used to perform the
13757        partial instantiation.  */
13758     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13759                                             targ_ptr);
13760
13761   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13762      but it doesn't seem to be on the hot path.  */
13763   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13764
13765   gcc_assert (tmpl == gen_tmpl
13766               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13767                   == spec)
13768               || fndecl == NULL_TREE);
13769
13770   if (spec != NULL_TREE)
13771     return spec;
13772
13773   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13774                                complain))
13775     return error_mark_node;
13776
13777   /* We are building a FUNCTION_DECL, during which the access of its
13778      parameters and return types have to be checked.  However this
13779      FUNCTION_DECL which is the desired context for access checking
13780      is not built yet.  We solve this chicken-and-egg problem by
13781      deferring all checks until we have the FUNCTION_DECL.  */
13782   push_deferring_access_checks (dk_deferred);
13783
13784   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13785      (because, for example, we have encountered a non-dependent
13786      function call in the body of a template function and must now
13787      determine which of several overloaded functions will be called),
13788      within the instantiation itself we are not processing a
13789      template.  */  
13790   saved_processing_template_decl = processing_template_decl;
13791   processing_template_decl = 0;
13792   /* Substitute template parameters to obtain the specialization.  */
13793   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13794                    targ_ptr, complain, gen_tmpl);
13795   processing_template_decl = saved_processing_template_decl;
13796   if (fndecl == error_mark_node)
13797     return error_mark_node;
13798
13799   /* Now we know the specialization, compute access previously
13800      deferred.  */
13801   push_access_scope (fndecl);
13802
13803   /* Some typedefs referenced from within the template code need to be access
13804      checked at template instantiation time, i.e now. These types were
13805      added to the template at parsing time. Let's get those and perfom
13806      the acces checks then.  */
13807   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13808   perform_deferred_access_checks ();
13809   pop_access_scope (fndecl);
13810   pop_deferring_access_checks ();
13811
13812   /* The DECL_TI_TEMPLATE should always be the immediate parent
13813      template, not the most general template.  */
13814   DECL_TI_TEMPLATE (fndecl) = tmpl;
13815
13816   /* If we've just instantiated the main entry point for a function,
13817      instantiate all the alternate entry points as well.  We do this
13818      by cloning the instantiation of the main entry point, not by
13819      instantiating the template clones.  */
13820   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
13821     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13822
13823   return fndecl;
13824 }
13825
13826 /* Wrapper for instantiate_template_1.  */
13827
13828 tree
13829 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
13830 {
13831   tree ret;
13832   timevar_push (TV_TEMPLATE_INST);
13833   ret = instantiate_template_1 (tmpl, orig_args,  complain);
13834   timevar_pop (TV_TEMPLATE_INST);
13835   return ret;
13836 }
13837
13838 /* We're going to do deduction substitution on the type of TMPL, a function
13839    template.  In C++11 mode, push into that access scope.  In C++03 mode,
13840    disable access checking.  */
13841
13842 static void
13843 push_deduction_access_scope (tree tmpl)
13844 {
13845   if (cxx_dialect >= cxx0x)
13846     {
13847       int ptd = processing_template_decl;
13848       push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
13849       /* Preserve processing_template_decl across push_to_top_level.  */
13850       if (ptd && !processing_template_decl)
13851         ++processing_template_decl;
13852     }
13853   else
13854     push_deferring_access_checks (dk_no_check);
13855 }
13856
13857 /* And pop back out.  */
13858
13859 static void
13860 pop_deduction_access_scope (tree tmpl)
13861 {
13862   if (cxx_dialect >= cxx0x)
13863     pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
13864   else
13865     pop_deferring_access_checks ();
13866 }
13867
13868 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13869    NARGS elements of the arguments that are being used when calling
13870    it.  TARGS is a vector into which the deduced template arguments
13871    are placed.
13872
13873    Return zero for success, 2 for an incomplete match that doesn't resolve
13874    all the types, and 1 for complete failure.  An error message will be
13875    printed only for an incomplete match.
13876
13877    If FN is a conversion operator, or we are trying to produce a specific
13878    specialization, RETURN_TYPE is the return type desired.
13879
13880    The EXPLICIT_TARGS are explicit template arguments provided via a
13881    template-id.
13882
13883    The parameter STRICT is one of:
13884
13885    DEDUCE_CALL:
13886      We are deducing arguments for a function call, as in
13887      [temp.deduct.call].
13888
13889    DEDUCE_CONV:
13890      We are deducing arguments for a conversion function, as in
13891      [temp.deduct.conv].
13892
13893    DEDUCE_EXACT:
13894      We are deducing arguments when doing an explicit instantiation
13895      as in [temp.explicit], when determining an explicit specialization
13896      as in [temp.expl.spec], or when taking the address of a function
13897      template, as in [temp.deduct.funcaddr].  */
13898
13899 int
13900 fn_type_unification (tree fn,
13901                      tree explicit_targs,
13902                      tree targs,
13903                      const tree *args,
13904                      unsigned int nargs,
13905                      tree return_type,
13906                      unification_kind_t strict,
13907                      int flags)
13908 {
13909   tree parms;
13910   tree fntype;
13911   int result;
13912   bool incomplete_argument_packs_p = false;
13913
13914   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13915
13916   fntype = TREE_TYPE (fn);
13917   if (explicit_targs)
13918     {
13919       /* [temp.deduct]
13920
13921          The specified template arguments must match the template
13922          parameters in kind (i.e., type, nontype, template), and there
13923          must not be more arguments than there are parameters;
13924          otherwise type deduction fails.
13925
13926          Nontype arguments must match the types of the corresponding
13927          nontype template parameters, or must be convertible to the
13928          types of the corresponding nontype parameters as specified in
13929          _temp.arg.nontype_, otherwise type deduction fails.
13930
13931          All references in the function type of the function template
13932          to the corresponding template parameters are replaced by the
13933          specified template argument values.  If a substitution in a
13934          template parameter or in the function type of the function
13935          template results in an invalid type, type deduction fails.  */
13936       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13937       int i, len = TREE_VEC_LENGTH (tparms);
13938       tree converted_args;
13939       bool incomplete = false;
13940
13941       if (explicit_targs == error_mark_node)
13942         return 1;
13943
13944       converted_args
13945         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13946                                   /*require_all_args=*/false,
13947                                   /*use_default_args=*/false));
13948       if (converted_args == error_mark_node)
13949         return 1;
13950
13951       /* Substitute the explicit args into the function type.  This is
13952          necessary so that, for instance, explicitly declared function
13953          arguments can match null pointed constants.  If we were given
13954          an incomplete set of explicit args, we must not do semantic
13955          processing during substitution as we could create partial
13956          instantiations.  */
13957       for (i = 0; i < len; i++)
13958         {
13959           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13960           bool parameter_pack = false;
13961
13962           /* Dig out the actual parm.  */
13963           if (TREE_CODE (parm) == TYPE_DECL
13964               || TREE_CODE (parm) == TEMPLATE_DECL)
13965             {
13966               parm = TREE_TYPE (parm);
13967               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13968             }
13969           else if (TREE_CODE (parm) == PARM_DECL)
13970             {
13971               parm = DECL_INITIAL (parm);
13972               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13973             }
13974
13975           if (parameter_pack)
13976             {
13977               int level, idx;
13978               tree targ;
13979               template_parm_level_and_index (parm, &level, &idx);
13980
13981               /* Mark the argument pack as "incomplete". We could
13982                  still deduce more arguments during unification.
13983                  We remove this mark in type_unification_real.  */
13984               targ = TMPL_ARG (converted_args, level, idx);
13985               if (targ)
13986                 {
13987                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13988                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13989                     = ARGUMENT_PACK_ARGS (targ);
13990                 }
13991
13992               /* We have some incomplete argument packs.  */
13993               incomplete_argument_packs_p = true;
13994             }
13995         }
13996
13997       if (incomplete_argument_packs_p)
13998         /* Any substitution is guaranteed to be incomplete if there
13999            are incomplete argument packs, because we can still deduce
14000            more arguments.  */
14001         incomplete = 1;
14002       else
14003         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
14004
14005       processing_template_decl += incomplete;
14006       fntype = deduction_tsubst_fntype (fn, converted_args);
14007       processing_template_decl -= incomplete;
14008
14009       if (fntype == error_mark_node)
14010         return 1;
14011
14012       /* Place the explicitly specified arguments in TARGS.  */
14013       for (i = NUM_TMPL_ARGS (converted_args); i--;)
14014         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
14015     }
14016
14017   /* Never do unification on the 'this' parameter.  */
14018   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
14019
14020   if (return_type)
14021     {
14022       tree *new_args;
14023
14024       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
14025       new_args = XALLOCAVEC (tree, nargs + 1);
14026       new_args[0] = return_type;
14027       memcpy (new_args + 1, args, nargs * sizeof (tree));
14028       args = new_args;
14029       ++nargs;
14030     }
14031
14032   /* We allow incomplete unification without an error message here
14033      because the standard doesn't seem to explicitly prohibit it.  Our
14034      callers must be ready to deal with unification failures in any
14035      event.  */
14036   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
14037                                   targs, parms, args, nargs, /*subr=*/0,
14038                                   strict, flags);
14039
14040   /* Now that we have bindings for all of the template arguments,
14041      ensure that the arguments deduced for the template template
14042      parameters have compatible template parameter lists.  We cannot
14043      check this property before we have deduced all template
14044      arguments, because the template parameter types of a template
14045      template parameter might depend on prior template parameters
14046      deduced after the template template parameter.  The following
14047      ill-formed example illustrates this issue:
14048
14049        template<typename T, template<T> class C> void f(C<5>, T);
14050
14051        template<int N> struct X {};
14052
14053        void g() {
14054          f(X<5>(), 5l); // error: template argument deduction fails
14055        }
14056
14057      The template parameter list of 'C' depends on the template type
14058      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
14059      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
14060      time that we deduce 'C'.  */
14061   if (result == 0
14062       && !template_template_parm_bindings_ok_p 
14063            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
14064     return 1;
14065
14066   if (result == 0)
14067     /* All is well so far.  Now, check:
14068
14069        [temp.deduct]
14070
14071        When all template arguments have been deduced, all uses of
14072        template parameters in nondeduced contexts are replaced with
14073        the corresponding deduced argument values.  If the
14074        substitution results in an invalid type, as described above,
14075        type deduction fails.  */
14076     {
14077       tree substed = deduction_tsubst_fntype (fn, targs);
14078       if (substed == error_mark_node)
14079         return 1;
14080
14081       /* If we're looking for an exact match, check that what we got
14082          is indeed an exact match.  It might not be if some template
14083          parameters are used in non-deduced contexts.  */
14084       if (strict == DEDUCE_EXACT)
14085         {
14086           unsigned int i;
14087
14088           tree sarg
14089             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
14090           if (return_type)
14091             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
14092           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
14093             if (!same_type_p (args[i], TREE_VALUE (sarg)))
14094               return 1;
14095         }
14096     }
14097
14098   return result;
14099 }
14100
14101 /* Adjust types before performing type deduction, as described in
14102    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
14103    sections are symmetric.  PARM is the type of a function parameter
14104    or the return type of the conversion function.  ARG is the type of
14105    the argument passed to the call, or the type of the value
14106    initialized with the result of the conversion function.
14107    ARG_EXPR is the original argument expression, which may be null.  */
14108
14109 static int
14110 maybe_adjust_types_for_deduction (unification_kind_t strict,
14111                                   tree* parm,
14112                                   tree* arg,
14113                                   tree arg_expr)
14114 {
14115   int result = 0;
14116
14117   switch (strict)
14118     {
14119     case DEDUCE_CALL:
14120       break;
14121
14122     case DEDUCE_CONV:
14123       {
14124         /* Swap PARM and ARG throughout the remainder of this
14125            function; the handling is precisely symmetric since PARM
14126            will initialize ARG rather than vice versa.  */
14127         tree* temp = parm;
14128         parm = arg;
14129         arg = temp;
14130         break;
14131       }
14132
14133     case DEDUCE_EXACT:
14134       /* Core issue #873: Do the DR606 thing (see below) for these cases,
14135          too, but here handle it by stripping the reference from PARM
14136          rather than by adding it to ARG.  */
14137       if (TREE_CODE (*parm) == REFERENCE_TYPE
14138           && TYPE_REF_IS_RVALUE (*parm)
14139           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14140           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14141           && TREE_CODE (*arg) == REFERENCE_TYPE
14142           && !TYPE_REF_IS_RVALUE (*arg))
14143         *parm = TREE_TYPE (*parm);
14144       /* Nothing else to do in this case.  */
14145       return 0;
14146
14147     default:
14148       gcc_unreachable ();
14149     }
14150
14151   if (TREE_CODE (*parm) != REFERENCE_TYPE)
14152     {
14153       /* [temp.deduct.call]
14154
14155          If P is not a reference type:
14156
14157          --If A is an array type, the pointer type produced by the
14158          array-to-pointer standard conversion (_conv.array_) is
14159          used in place of A for type deduction; otherwise,
14160
14161          --If A is a function type, the pointer type produced by
14162          the function-to-pointer standard conversion
14163          (_conv.func_) is used in place of A for type deduction;
14164          otherwise,
14165
14166          --If A is a cv-qualified type, the top level
14167          cv-qualifiers of A's type are ignored for type
14168          deduction.  */
14169       if (TREE_CODE (*arg) == ARRAY_TYPE)
14170         *arg = build_pointer_type (TREE_TYPE (*arg));
14171       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
14172         *arg = build_pointer_type (*arg);
14173       else
14174         *arg = TYPE_MAIN_VARIANT (*arg);
14175     }
14176
14177   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
14178      of the form T&&, where T is a template parameter, and the argument
14179      is an lvalue, T is deduced as A& */
14180   if (TREE_CODE (*parm) == REFERENCE_TYPE
14181       && TYPE_REF_IS_RVALUE (*parm)
14182       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14183       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14184       && (arg_expr ? real_lvalue_p (arg_expr)
14185           /* try_one_overload doesn't provide an arg_expr, but
14186              functions are always lvalues.  */
14187           : TREE_CODE (*arg) == FUNCTION_TYPE))
14188     *arg = build_reference_type (*arg);
14189
14190   /* [temp.deduct.call]
14191
14192      If P is a cv-qualified type, the top level cv-qualifiers
14193      of P's type are ignored for type deduction.  If P is a
14194      reference type, the type referred to by P is used for
14195      type deduction.  */
14196   *parm = TYPE_MAIN_VARIANT (*parm);
14197   if (TREE_CODE (*parm) == REFERENCE_TYPE)
14198     {
14199       *parm = TREE_TYPE (*parm);
14200       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14201     }
14202
14203   /* DR 322. For conversion deduction, remove a reference type on parm
14204      too (which has been swapped into ARG).  */
14205   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
14206     *arg = TREE_TYPE (*arg);
14207
14208   return result;
14209 }
14210
14211 /* Most parms like fn_type_unification.
14212
14213    If SUBR is 1, we're being called recursively (to unify the
14214    arguments of a function or method parameter of a function
14215    template). */
14216
14217 static int
14218 type_unification_real (tree tparms,
14219                        tree targs,
14220                        tree xparms,
14221                        const tree *xargs,
14222                        unsigned int xnargs,
14223                        int subr,
14224                        unification_kind_t strict,
14225                        int flags)
14226 {
14227   tree parm, arg, arg_expr;
14228   int i;
14229   int ntparms = TREE_VEC_LENGTH (tparms);
14230   int sub_strict;
14231   int saw_undeduced = 0;
14232   tree parms;
14233   const tree *args;
14234   unsigned int nargs;
14235   unsigned int ia;
14236
14237   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
14238   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
14239   gcc_assert (ntparms > 0);
14240
14241   /* Reset the number of non-defaulted template arguments contained
14242      in TARGS.  */
14243   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
14244
14245   switch (strict)
14246     {
14247     case DEDUCE_CALL:
14248       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
14249                     | UNIFY_ALLOW_DERIVED);
14250       break;
14251
14252     case DEDUCE_CONV:
14253       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14254       break;
14255
14256     case DEDUCE_EXACT:
14257       sub_strict = UNIFY_ALLOW_NONE;
14258       break;
14259
14260     default:
14261       gcc_unreachable ();
14262     }
14263
14264  again:
14265   parms = xparms;
14266   args = xargs;
14267   nargs = xnargs;
14268
14269   ia = 0;
14270   while (parms && parms != void_list_node
14271          && ia < nargs)
14272     {
14273       parm = TREE_VALUE (parms);
14274
14275       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
14276           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
14277         /* For a function parameter pack that occurs at the end of the
14278            parameter-declaration-list, the type A of each remaining
14279            argument of the call is compared with the type P of the
14280            declarator-id of the function parameter pack.  */
14281         break;
14282
14283       parms = TREE_CHAIN (parms);
14284
14285       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
14286         /* For a function parameter pack that does not occur at the
14287            end of the parameter-declaration-list, the type of the
14288            parameter pack is a non-deduced context.  */
14289         continue;
14290
14291       arg = args[ia];
14292       ++ia;
14293       arg_expr = NULL;
14294
14295       if (arg == error_mark_node)
14296         return 1;
14297       if (arg == unknown_type_node)
14298         /* We can't deduce anything from this, but we might get all the
14299            template args from other function args.  */
14300         continue;
14301
14302       /* Conversions will be performed on a function argument that
14303          corresponds with a function parameter that contains only
14304          non-deducible template parameters and explicitly specified
14305          template parameters.  */
14306       if (!uses_template_parms (parm))
14307         {
14308           tree type;
14309
14310           if (!TYPE_P (arg))
14311             type = TREE_TYPE (arg);
14312           else
14313             type = arg;
14314
14315           if (same_type_p (parm, type))
14316             continue;
14317           if (strict != DEDUCE_EXACT
14318               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
14319                                   flags))
14320             continue;
14321
14322           return 1;
14323         }
14324
14325       if (!TYPE_P (arg))
14326         {
14327           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14328           if (type_unknown_p (arg))
14329             {
14330               /* [temp.deduct.type] 
14331
14332                  A template-argument can be deduced from a pointer to
14333                  function or pointer to member function argument if
14334                  the set of overloaded functions does not contain
14335                  function templates and at most one of a set of
14336                  overloaded functions provides a unique match.  */
14337               if (resolve_overloaded_unification
14338                   (tparms, targs, parm, arg, strict, sub_strict))
14339                 continue;
14340
14341               return 1;
14342             }
14343           arg_expr = arg;
14344           arg = unlowered_expr_type (arg);
14345           if (arg == error_mark_node)
14346             return 1;
14347         }
14348
14349       {
14350         int arg_strict = sub_strict;
14351
14352         if (!subr)
14353           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
14354                                                           arg_expr);
14355
14356         if (arg == init_list_type_node && arg_expr)
14357           arg = arg_expr;
14358         if (unify (tparms, targs, parm, arg, arg_strict))
14359           return 1;
14360       }
14361     }
14362
14363
14364   if (parms 
14365       && parms != void_list_node
14366       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14367     {
14368       /* Unify the remaining arguments with the pack expansion type.  */
14369       tree argvec;
14370       tree parmvec = make_tree_vec (1);
14371
14372       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14373       argvec = make_tree_vec (nargs - ia);
14374       for (i = 0; ia < nargs; ++ia, ++i)
14375         TREE_VEC_ELT (argvec, i) = args[ia];
14376
14377       /* Copy the parameter into parmvec.  */
14378       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14379       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14380                                 /*call_args_p=*/true, /*subr=*/subr))
14381         return 1;
14382
14383       /* Advance to the end of the list of parameters.  */
14384       parms = TREE_CHAIN (parms);
14385     }
14386
14387   /* Fail if we've reached the end of the parm list, and more args
14388      are present, and the parm list isn't variadic.  */
14389   if (ia < nargs && parms == void_list_node)
14390     return 1;
14391   /* Fail if parms are left and they don't have default values.  */
14392   if (parms && parms != void_list_node
14393       && TREE_PURPOSE (parms) == NULL_TREE)
14394     return 1;
14395
14396   if (!subr)
14397     {
14398       /* Check to see if we need another pass before we start clearing
14399          ARGUMENT_PACK_INCOMPLETE_P.  */
14400       for (i = 0; i < ntparms; i++)
14401         {
14402           tree targ = TREE_VEC_ELT (targs, i);
14403           tree tparm = TREE_VEC_ELT (tparms, i);
14404
14405           if (targ || tparm == error_mark_node)
14406             continue;
14407           tparm = TREE_VALUE (tparm);
14408
14409           /* If this is an undeduced nontype parameter that depends on
14410              a type parameter, try another pass; its type may have been
14411              deduced from a later argument than the one from which
14412              this parameter can be deduced.  */
14413           if (TREE_CODE (tparm) == PARM_DECL
14414               && uses_template_parms (TREE_TYPE (tparm))
14415               && !saw_undeduced++)
14416             goto again;
14417         }
14418
14419       for (i = 0; i < ntparms; i++)
14420         {
14421           tree targ = TREE_VEC_ELT (targs, i);
14422           tree tparm = TREE_VEC_ELT (tparms, i);
14423
14424           /* Clear the "incomplete" flags on all argument packs now so that
14425              substituting them into later default arguments works.  */
14426           if (targ && ARGUMENT_PACK_P (targ))
14427             {
14428               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
14429               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
14430             }
14431
14432           if (targ || tparm == error_mark_node)
14433             continue;
14434           tparm = TREE_VALUE (tparm);
14435
14436           /* Core issue #226 (C++0x) [temp.deduct]:
14437
14438              If a template argument has not been deduced, its
14439              default template argument, if any, is used. 
14440
14441              When we are in C++98 mode, TREE_PURPOSE will either
14442              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14443              to explicitly check cxx_dialect here.  */
14444           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14445             {
14446               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14447               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
14448               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
14449               arg = convert_template_argument (parm, arg, targs, tf_none,
14450                                                i, NULL_TREE);
14451               if (arg == error_mark_node)
14452                 return 1;
14453               else
14454                 {
14455                   TREE_VEC_ELT (targs, i) = arg;
14456                   /* The position of the first default template argument,
14457                      is also the number of non-defaulted arguments in TARGS.
14458                      Record that.  */
14459                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14460                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
14461                   continue;
14462                 }
14463             }
14464
14465           /* If the type parameter is a parameter pack, then it will
14466              be deduced to an empty parameter pack.  */
14467           if (template_parameter_pack_p (tparm))
14468             {
14469               tree arg;
14470
14471               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
14472                 {
14473                   arg = make_node (NONTYPE_ARGUMENT_PACK);
14474                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
14475                   TREE_CONSTANT (arg) = 1;
14476                 }
14477               else
14478                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
14479
14480               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
14481
14482               TREE_VEC_ELT (targs, i) = arg;
14483               continue;
14484             }
14485
14486           return 2;
14487         }
14488     }
14489 #ifdef ENABLE_CHECKING
14490   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14491     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
14492 #endif
14493
14494   return 0;
14495 }
14496
14497 /* Subroutine of type_unification_real.  Args are like the variables
14498    at the call site.  ARG is an overloaded function (or template-id);
14499    we try deducing template args from each of the overloads, and if
14500    only one succeeds, we go with that.  Modifies TARGS and returns
14501    true on success.  */
14502
14503 static bool
14504 resolve_overloaded_unification (tree tparms,
14505                                 tree targs,
14506                                 tree parm,
14507                                 tree arg,
14508                                 unification_kind_t strict,
14509                                 int sub_strict)
14510 {
14511   tree tempargs = copy_node (targs);
14512   int good = 0;
14513   tree goodfn = NULL_TREE;
14514   bool addr_p;
14515
14516   if (TREE_CODE (arg) == ADDR_EXPR)
14517     {
14518       arg = TREE_OPERAND (arg, 0);
14519       addr_p = true;
14520     }
14521   else
14522     addr_p = false;
14523
14524   if (TREE_CODE (arg) == COMPONENT_REF)
14525     /* Handle `&x' where `x' is some static or non-static member
14526        function name.  */
14527     arg = TREE_OPERAND (arg, 1);
14528
14529   if (TREE_CODE (arg) == OFFSET_REF)
14530     arg = TREE_OPERAND (arg, 1);
14531
14532   /* Strip baselink information.  */
14533   if (BASELINK_P (arg))
14534     arg = BASELINK_FUNCTIONS (arg);
14535
14536   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
14537     {
14538       /* If we got some explicit template args, we need to plug them into
14539          the affected templates before we try to unify, in case the
14540          explicit args will completely resolve the templates in question.  */
14541
14542       int ok = 0;
14543       tree expl_subargs = TREE_OPERAND (arg, 1);
14544       arg = TREE_OPERAND (arg, 0);
14545
14546       for (; arg; arg = OVL_NEXT (arg))
14547         {
14548           tree fn = OVL_CURRENT (arg);
14549           tree subargs, elem;
14550
14551           if (TREE_CODE (fn) != TEMPLATE_DECL)
14552             continue;
14553
14554           ++processing_template_decl;
14555           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14556                                   expl_subargs, /*check_ret=*/false);
14557           if (subargs && !any_dependent_template_arguments_p (subargs))
14558             {
14559               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
14560               if (try_one_overload (tparms, targs, tempargs, parm,
14561                                     elem, strict, sub_strict, addr_p)
14562                   && (!goodfn || !decls_match (goodfn, elem)))
14563                 {
14564                   goodfn = elem;
14565                   ++good;
14566                 }
14567             }
14568           else if (subargs)
14569             ++ok;
14570           --processing_template_decl;
14571         }
14572       /* If no templates (or more than one) are fully resolved by the
14573          explicit arguments, this template-id is a non-deduced context; it
14574          could still be OK if we deduce all template arguments for the
14575          enclosing call through other arguments.  */
14576       if (good != 1)
14577         good = ok;
14578     }
14579   else if (TREE_CODE (arg) != OVERLOAD
14580            && TREE_CODE (arg) != FUNCTION_DECL)
14581     /* If ARG is, for example, "(0, &f)" then its type will be unknown
14582        -- but the deduction does not succeed because the expression is
14583        not just the function on its own.  */
14584     return false;
14585   else
14586     for (; arg; arg = OVL_NEXT (arg))
14587       if (try_one_overload (tparms, targs, tempargs, parm,
14588                             TREE_TYPE (OVL_CURRENT (arg)),
14589                             strict, sub_strict, addr_p)
14590           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
14591         {
14592           goodfn = OVL_CURRENT (arg);
14593           ++good;
14594         }
14595
14596   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14597      to function or pointer to member function argument if the set of
14598      overloaded functions does not contain function templates and at most
14599      one of a set of overloaded functions provides a unique match.
14600
14601      So if we found multiple possibilities, we return success but don't
14602      deduce anything.  */
14603
14604   if (good == 1)
14605     {
14606       int i = TREE_VEC_LENGTH (targs);
14607       for (; i--; )
14608         if (TREE_VEC_ELT (tempargs, i))
14609           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
14610     }
14611   if (good)
14612     return true;
14613
14614   return false;
14615 }
14616
14617 /* Core DR 115: In contexts where deduction is done and fails, or in
14618    contexts where deduction is not done, if a template argument list is
14619    specified and it, along with any default template arguments, identifies
14620    a single function template specialization, then the template-id is an
14621    lvalue for the function template specialization.  */
14622
14623 tree
14624 resolve_nondeduced_context (tree orig_expr)
14625 {
14626   tree expr, offset, baselink;
14627   bool addr;
14628
14629   if (!type_unknown_p (orig_expr))
14630     return orig_expr;
14631
14632   expr = orig_expr;
14633   addr = false;
14634   offset = NULL_TREE;
14635   baselink = NULL_TREE;
14636
14637   if (TREE_CODE (expr) == ADDR_EXPR)
14638     {
14639       expr = TREE_OPERAND (expr, 0);
14640       addr = true;
14641     }
14642   if (TREE_CODE (expr) == OFFSET_REF)
14643     {
14644       offset = expr;
14645       expr = TREE_OPERAND (expr, 1);
14646     }
14647   if (TREE_CODE (expr) == BASELINK)
14648     {
14649       baselink = expr;
14650       expr = BASELINK_FUNCTIONS (expr);
14651     }
14652
14653   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
14654     {
14655       int good = 0;
14656       tree goodfn = NULL_TREE;
14657
14658       /* If we got some explicit template args, we need to plug them into
14659          the affected templates before we try to unify, in case the
14660          explicit args will completely resolve the templates in question.  */
14661
14662       tree expl_subargs = TREE_OPERAND (expr, 1);
14663       tree arg = TREE_OPERAND (expr, 0);
14664       tree badfn = NULL_TREE;
14665       tree badargs = NULL_TREE;
14666
14667       for (; arg; arg = OVL_NEXT (arg))
14668         {
14669           tree fn = OVL_CURRENT (arg);
14670           tree subargs, elem;
14671
14672           if (TREE_CODE (fn) != TEMPLATE_DECL)
14673             continue;
14674
14675           ++processing_template_decl;
14676           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14677                                   expl_subargs, /*check_ret=*/false);
14678           if (subargs && !any_dependent_template_arguments_p (subargs))
14679             {
14680               elem = instantiate_template (fn, subargs, tf_none);
14681               if (elem == error_mark_node)
14682                 {
14683                   badfn = fn;
14684                   badargs = subargs;
14685                 }
14686               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
14687                 {
14688                   goodfn = elem;
14689                   ++good;
14690                 }
14691             }
14692           --processing_template_decl;
14693         }
14694       if (good == 1)
14695         {
14696           mark_used (goodfn);
14697           expr = goodfn;
14698           if (baselink)
14699             expr = build_baselink (BASELINK_BINFO (baselink),
14700                                    BASELINK_ACCESS_BINFO (baselink),
14701                                    expr, BASELINK_OPTYPE (baselink));
14702           if (offset)
14703             {
14704               tree base
14705                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
14706               expr = build_offset_ref (base, expr, addr);
14707             }
14708           if (addr)
14709             expr = cp_build_addr_expr (expr, tf_warning_or_error);
14710           return expr;
14711         }
14712       else if (good == 0 && badargs)
14713         /* There were no good options and at least one bad one, so let the
14714            user know what the problem is.  */
14715         instantiate_template (badfn, badargs, tf_warning_or_error);
14716     }
14717   return orig_expr;
14718 }
14719
14720 /* Subroutine of resolve_overloaded_unification; does deduction for a single
14721    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
14722    different overloads deduce different arguments for a given parm.
14723    ADDR_P is true if the expression for which deduction is being
14724    performed was of the form "& fn" rather than simply "fn".
14725
14726    Returns 1 on success.  */
14727
14728 static int
14729 try_one_overload (tree tparms,
14730                   tree orig_targs,
14731                   tree targs,
14732                   tree parm,
14733                   tree arg,
14734                   unification_kind_t strict,
14735                   int sub_strict,
14736                   bool addr_p)
14737 {
14738   int nargs;
14739   tree tempargs;
14740   int i;
14741
14742   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14743      to function or pointer to member function argument if the set of
14744      overloaded functions does not contain function templates and at most
14745      one of a set of overloaded functions provides a unique match.
14746
14747      So if this is a template, just return success.  */
14748
14749   if (uses_template_parms (arg))
14750     return 1;
14751
14752   if (TREE_CODE (arg) == METHOD_TYPE)
14753     arg = build_ptrmemfunc_type (build_pointer_type (arg));
14754   else if (addr_p)
14755     arg = build_pointer_type (arg);
14756
14757   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
14758
14759   /* We don't copy orig_targs for this because if we have already deduced
14760      some template args from previous args, unify would complain when we
14761      try to deduce a template parameter for the same argument, even though
14762      there isn't really a conflict.  */
14763   nargs = TREE_VEC_LENGTH (targs);
14764   tempargs = make_tree_vec (nargs);
14765
14766   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
14767     return 0;
14768
14769   /* First make sure we didn't deduce anything that conflicts with
14770      explicitly specified args.  */
14771   for (i = nargs; i--; )
14772     {
14773       tree elt = TREE_VEC_ELT (tempargs, i);
14774       tree oldelt = TREE_VEC_ELT (orig_targs, i);
14775
14776       if (!elt)
14777         /*NOP*/;
14778       else if (uses_template_parms (elt))
14779         /* Since we're unifying against ourselves, we will fill in
14780            template args used in the function parm list with our own
14781            template parms.  Discard them.  */
14782         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
14783       else if (oldelt && !template_args_equal (oldelt, elt))
14784         return 0;
14785     }
14786
14787   for (i = nargs; i--; )
14788     {
14789       tree elt = TREE_VEC_ELT (tempargs, i);
14790
14791       if (elt)
14792         TREE_VEC_ELT (targs, i) = elt;
14793     }
14794
14795   return 1;
14796 }
14797
14798 /* PARM is a template class (perhaps with unbound template
14799    parameters).  ARG is a fully instantiated type.  If ARG can be
14800    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
14801    TARGS are as for unify.  */
14802
14803 static tree
14804 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
14805 {
14806   tree copy_of_targs;
14807
14808   if (!CLASSTYPE_TEMPLATE_INFO (arg)
14809       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
14810           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
14811     return NULL_TREE;
14812
14813   /* We need to make a new template argument vector for the call to
14814      unify.  If we used TARGS, we'd clutter it up with the result of
14815      the attempted unification, even if this class didn't work out.
14816      We also don't want to commit ourselves to all the unifications
14817      we've already done, since unification is supposed to be done on
14818      an argument-by-argument basis.  In other words, consider the
14819      following pathological case:
14820
14821        template <int I, int J, int K>
14822        struct S {};
14823
14824        template <int I, int J>
14825        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
14826
14827        template <int I, int J, int K>
14828        void f(S<I, J, K>, S<I, I, I>);
14829
14830        void g() {
14831          S<0, 0, 0> s0;
14832          S<0, 1, 2> s2;
14833
14834          f(s0, s2);
14835        }
14836
14837      Now, by the time we consider the unification involving `s2', we
14838      already know that we must have `f<0, 0, 0>'.  But, even though
14839      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14840      because there are two ways to unify base classes of S<0, 1, 2>
14841      with S<I, I, I>.  If we kept the already deduced knowledge, we
14842      would reject the possibility I=1.  */
14843   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14844
14845   /* If unification failed, we're done.  */
14846   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14847              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14848     return NULL_TREE;
14849
14850   return arg;
14851 }
14852
14853 /* Given a template type PARM and a class type ARG, find the unique
14854    base type in ARG that is an instance of PARM.  We do not examine
14855    ARG itself; only its base-classes.  If there is not exactly one
14856    appropriate base class, return NULL_TREE.  PARM may be the type of
14857    a partial specialization, as well as a plain template type.  Used
14858    by unify.  */
14859
14860 static tree
14861 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14862 {
14863   tree rval = NULL_TREE;
14864   tree binfo;
14865
14866   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14867
14868   binfo = TYPE_BINFO (complete_type (arg));
14869   if (!binfo)
14870     /* The type could not be completed.  */
14871     return NULL_TREE;
14872
14873   /* Walk in inheritance graph order.  The search order is not
14874      important, and this avoids multiple walks of virtual bases.  */
14875   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14876     {
14877       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14878
14879       if (r)
14880         {
14881           /* If there is more than one satisfactory baseclass, then:
14882
14883                [temp.deduct.call]
14884
14885               If they yield more than one possible deduced A, the type
14886               deduction fails.
14887
14888              applies.  */
14889           if (rval && !same_type_p (r, rval))
14890             return NULL_TREE;
14891
14892           rval = r;
14893         }
14894     }
14895
14896   return rval;
14897 }
14898
14899 /* Returns the level of DECL, which declares a template parameter.  */
14900
14901 static int
14902 template_decl_level (tree decl)
14903 {
14904   switch (TREE_CODE (decl))
14905     {
14906     case TYPE_DECL:
14907     case TEMPLATE_DECL:
14908       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14909
14910     case PARM_DECL:
14911       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14912
14913     default:
14914       gcc_unreachable ();
14915     }
14916   return 0;
14917 }
14918
14919 /* Decide whether ARG can be unified with PARM, considering only the
14920    cv-qualifiers of each type, given STRICT as documented for unify.
14921    Returns nonzero iff the unification is OK on that basis.  */
14922
14923 static int
14924 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14925 {
14926   int arg_quals = cp_type_quals (arg);
14927   int parm_quals = cp_type_quals (parm);
14928
14929   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14930       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14931     {
14932       /*  Although a CVR qualifier is ignored when being applied to a
14933           substituted template parameter ([8.3.2]/1 for example), that
14934           does not allow us to unify "const T" with "int&" because both
14935           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
14936           It is ok when we're allowing additional CV qualifiers
14937           at the outer level [14.8.2.1]/3,1st bullet.  */
14938       if ((TREE_CODE (arg) == REFERENCE_TYPE
14939            || TREE_CODE (arg) == FUNCTION_TYPE
14940            || TREE_CODE (arg) == METHOD_TYPE)
14941           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14942         return 0;
14943
14944       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14945           && (parm_quals & TYPE_QUAL_RESTRICT))
14946         return 0;
14947     }
14948
14949   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14950       && (arg_quals & parm_quals) != parm_quals)
14951     return 0;
14952
14953   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14954       && (parm_quals & arg_quals) != arg_quals)
14955     return 0;
14956
14957   return 1;
14958 }
14959
14960 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14961 void 
14962 template_parm_level_and_index (tree parm, int* level, int* index)
14963 {
14964   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14965       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14966       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14967     {
14968       *index = TEMPLATE_TYPE_IDX (parm);
14969       *level = TEMPLATE_TYPE_LEVEL (parm);
14970     }
14971   else
14972     {
14973       *index = TEMPLATE_PARM_IDX (parm);
14974       *level = TEMPLATE_PARM_LEVEL (parm);
14975     }
14976 }
14977
14978 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14979    expansion at the end of PACKED_PARMS. Returns 0 if the type
14980    deduction succeeds, 1 otherwise. STRICT is the same as in
14981    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14982    call argument list. We'll need to adjust the arguments to make them
14983    types. SUBR tells us if this is from a recursive call to
14984    type_unification_real.  */
14985 int
14986 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14987                       tree packed_args, int strict, bool call_args_p,
14988                       bool subr)
14989 {
14990   tree parm 
14991     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14992   tree pattern = PACK_EXPANSION_PATTERN (parm);
14993   tree pack, packs = NULL_TREE;
14994   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14995   int len = TREE_VEC_LENGTH (packed_args);
14996
14997   /* Determine the parameter packs we will be deducing from the
14998      pattern, and record their current deductions.  */
14999   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
15000        pack; pack = TREE_CHAIN (pack))
15001     {
15002       tree parm_pack = TREE_VALUE (pack);
15003       int idx, level;
15004
15005       /* Determine the index and level of this parameter pack.  */
15006       template_parm_level_and_index (parm_pack, &level, &idx);
15007
15008       /* Keep track of the parameter packs and their corresponding
15009          argument packs.  */
15010       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
15011       TREE_TYPE (packs) = make_tree_vec (len - start);
15012     }
15013   
15014   /* Loop through all of the arguments that have not yet been
15015      unified and unify each with the pattern.  */
15016   for (i = start; i < len; i++)
15017     {
15018       tree parm = pattern;
15019
15020       /* For each parameter pack, clear out the deduced value so that
15021          we can deduce it again.  */
15022       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15023         {
15024           int idx, level;
15025           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15026
15027           TMPL_ARG (targs, level, idx) = NULL_TREE;
15028         }
15029
15030       /* Unify the pattern with the current argument.  */
15031       {
15032         tree arg = TREE_VEC_ELT (packed_args, i);
15033         tree arg_expr = NULL_TREE;
15034         int arg_strict = strict;
15035         bool skip_arg_p = false;
15036
15037         if (call_args_p)
15038           {
15039             int sub_strict;
15040
15041             /* This mirrors what we do in type_unification_real.  */
15042             switch (strict)
15043               {
15044               case DEDUCE_CALL:
15045                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
15046                               | UNIFY_ALLOW_MORE_CV_QUAL
15047                               | UNIFY_ALLOW_DERIVED);
15048                 break;
15049                 
15050               case DEDUCE_CONV:
15051                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
15052                 break;
15053                 
15054               case DEDUCE_EXACT:
15055                 sub_strict = UNIFY_ALLOW_NONE;
15056                 break;
15057                 
15058               default:
15059                 gcc_unreachable ();
15060               }
15061
15062             if (!TYPE_P (arg))
15063               {
15064                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
15065                 if (type_unknown_p (arg))
15066                   {
15067                     /* [temp.deduct.type] A template-argument can be
15068                        deduced from a pointer to function or pointer
15069                        to member function argument if the set of
15070                        overloaded functions does not contain function
15071                        templates and at most one of a set of
15072                        overloaded functions provides a unique
15073                        match.  */
15074
15075                     if (resolve_overloaded_unification
15076                         (tparms, targs, parm, arg,
15077                          (unification_kind_t) strict,
15078                          sub_strict)
15079                         != 0)
15080                       return 1;
15081                     skip_arg_p = true;
15082                   }
15083
15084                 if (!skip_arg_p)
15085                   {
15086                     arg_expr = arg;
15087                     arg = unlowered_expr_type (arg);
15088                     if (arg == error_mark_node)
15089                       return 1;
15090                   }
15091               }
15092       
15093             arg_strict = sub_strict;
15094
15095             if (!subr)
15096               arg_strict |= 
15097                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
15098                                                   &parm, &arg, arg_expr);
15099           }
15100
15101         if (!skip_arg_p)
15102           {
15103             /* For deduction from an init-list we need the actual list.  */
15104             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
15105               arg = arg_expr;
15106             if (unify (tparms, targs, parm, arg, arg_strict))
15107               return 1;
15108           }
15109       }
15110
15111       /* For each parameter pack, collect the deduced value.  */
15112       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15113         {
15114           int idx, level;
15115           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15116
15117           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
15118             TMPL_ARG (targs, level, idx);
15119         }
15120     }
15121
15122   /* Verify that the results of unification with the parameter packs
15123      produce results consistent with what we've seen before, and make
15124      the deduced argument packs available.  */
15125   for (pack = packs; pack; pack = TREE_CHAIN (pack))
15126     {
15127       tree old_pack = TREE_VALUE (pack);
15128       tree new_args = TREE_TYPE (pack);
15129       int i, len = TREE_VEC_LENGTH (new_args);
15130       int idx, level;
15131       bool nondeduced_p = false;
15132
15133       /* By default keep the original deduced argument pack.
15134          If necessary, more specific code is going to update the
15135          resulting deduced argument later down in this function.  */
15136       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15137       TMPL_ARG (targs, level, idx) = old_pack;
15138
15139       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
15140          actually deduce anything.  */
15141       for (i = 0; i < len && !nondeduced_p; ++i)
15142         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
15143           nondeduced_p = true;
15144       if (nondeduced_p)
15145         continue;
15146
15147       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
15148         {
15149           /* Prepend the explicit arguments onto NEW_ARGS.  */
15150           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15151           tree old_args = new_args;
15152           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
15153           int len = explicit_len + TREE_VEC_LENGTH (old_args);
15154
15155           /* Copy the explicit arguments.  */
15156           new_args = make_tree_vec (len);
15157           for (i = 0; i < explicit_len; i++)
15158             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
15159
15160           /* Copy the deduced arguments.  */
15161           for (; i < len; i++)
15162             TREE_VEC_ELT (new_args, i) =
15163               TREE_VEC_ELT (old_args, i - explicit_len);
15164         }
15165
15166       if (!old_pack)
15167         {
15168           tree result;
15169           /* Build the deduced *_ARGUMENT_PACK.  */
15170           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
15171             {
15172               result = make_node (NONTYPE_ARGUMENT_PACK);
15173               TREE_TYPE (result) = 
15174                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
15175               TREE_CONSTANT (result) = 1;
15176             }
15177           else
15178             result = cxx_make_type (TYPE_ARGUMENT_PACK);
15179
15180           SET_ARGUMENT_PACK_ARGS (result, new_args);
15181
15182           /* Note the deduced argument packs for this parameter
15183              pack.  */
15184           TMPL_ARG (targs, level, idx) = result;
15185         }
15186       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
15187                && (ARGUMENT_PACK_ARGS (old_pack) 
15188                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
15189         {
15190           /* We only had the explicitly-provided arguments before, but
15191              now we have a complete set of arguments.  */
15192           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15193
15194           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
15195           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
15196           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
15197         }
15198       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
15199                                     new_args))
15200         /* Inconsistent unification of this parameter pack.  */
15201         return 1;
15202     }
15203
15204   return 0;
15205 }
15206
15207 /* Deduce the value of template parameters.  TPARMS is the (innermost)
15208    set of template parameters to a template.  TARGS is the bindings
15209    for those template parameters, as determined thus far; TARGS may
15210    include template arguments for outer levels of template parameters
15211    as well.  PARM is a parameter to a template function, or a
15212    subcomponent of that parameter; ARG is the corresponding argument.
15213    This function attempts to match PARM with ARG in a manner
15214    consistent with the existing assignments in TARGS.  If more values
15215    are deduced, then TARGS is updated.
15216
15217    Returns 0 if the type deduction succeeds, 1 otherwise.  The
15218    parameter STRICT is a bitwise or of the following flags:
15219
15220      UNIFY_ALLOW_NONE:
15221        Require an exact match between PARM and ARG.
15222      UNIFY_ALLOW_MORE_CV_QUAL:
15223        Allow the deduced ARG to be more cv-qualified (by qualification
15224        conversion) than ARG.
15225      UNIFY_ALLOW_LESS_CV_QUAL:
15226        Allow the deduced ARG to be less cv-qualified than ARG.
15227      UNIFY_ALLOW_DERIVED:
15228        Allow the deduced ARG to be a template base class of ARG,
15229        or a pointer to a template base class of the type pointed to by
15230        ARG.
15231      UNIFY_ALLOW_INTEGER:
15232        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
15233        case for more information.
15234      UNIFY_ALLOW_OUTER_LEVEL:
15235        This is the outermost level of a deduction. Used to determine validity
15236        of qualification conversions. A valid qualification conversion must
15237        have const qualified pointers leading up to the inner type which
15238        requires additional CV quals, except at the outer level, where const
15239        is not required [conv.qual]. It would be normal to set this flag in
15240        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
15241      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
15242        This is the outermost level of a deduction, and PARM can be more CV
15243        qualified at this point.
15244      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
15245        This is the outermost level of a deduction, and PARM can be less CV
15246        qualified at this point.  */
15247
15248 static int
15249 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
15250 {
15251   int idx;
15252   tree targ;
15253   tree tparm;
15254   int strict_in = strict;
15255
15256   /* I don't think this will do the right thing with respect to types.
15257      But the only case I've seen it in so far has been array bounds, where
15258      signedness is the only information lost, and I think that will be
15259      okay.  */
15260   while (TREE_CODE (parm) == NOP_EXPR)
15261     parm = TREE_OPERAND (parm, 0);
15262
15263   if (arg == error_mark_node)
15264     return 1;
15265   if (arg == unknown_type_node
15266       || arg == init_list_type_node)
15267     /* We can't deduce anything from this, but we might get all the
15268        template args from other function args.  */
15269     return 0;
15270
15271   /* If PARM uses template parameters, then we can't bail out here,
15272      even if ARG == PARM, since we won't record unifications for the
15273      template parameters.  We might need them if we're trying to
15274      figure out which of two things is more specialized.  */
15275   if (arg == parm && !uses_template_parms (parm))
15276     return 0;
15277
15278   /* Handle init lists early, so the rest of the function can assume
15279      we're dealing with a type. */
15280   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
15281     {
15282       tree elt, elttype;
15283       unsigned i;
15284       tree orig_parm = parm;
15285
15286       /* Replace T with std::initializer_list<T> for deduction.  */
15287       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15288           && flag_deduce_init_list)
15289         parm = listify (parm);
15290
15291       if (!is_std_init_list (parm))
15292         /* We can only deduce from an initializer list argument if the
15293            parameter is std::initializer_list; otherwise this is a
15294            non-deduced context. */
15295         return 0;
15296
15297       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
15298
15299       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
15300         {
15301           int elt_strict = strict;
15302
15303           if (elt == error_mark_node)
15304             return 1;
15305
15306           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
15307             {
15308               tree type = TREE_TYPE (elt);
15309               /* It should only be possible to get here for a call.  */
15310               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
15311               elt_strict |= maybe_adjust_types_for_deduction
15312                 (DEDUCE_CALL, &elttype, &type, elt);
15313               elt = type;
15314             }
15315
15316           if (unify (tparms, targs, elttype, elt, elt_strict))
15317             return 1;
15318         }
15319
15320       /* If the std::initializer_list<T> deduction worked, replace the
15321          deduced A with std::initializer_list<A>.  */
15322       if (orig_parm != parm)
15323         {
15324           idx = TEMPLATE_TYPE_IDX (orig_parm);
15325           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15326           targ = listify (targ);
15327           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
15328         }
15329       return 0;
15330     }
15331
15332   /* Immediately reject some pairs that won't unify because of
15333      cv-qualification mismatches.  */
15334   if (TREE_CODE (arg) == TREE_CODE (parm)
15335       && TYPE_P (arg)
15336       /* It is the elements of the array which hold the cv quals of an array
15337          type, and the elements might be template type parms. We'll check
15338          when we recurse.  */
15339       && TREE_CODE (arg) != ARRAY_TYPE
15340       /* We check the cv-qualifiers when unifying with template type
15341          parameters below.  We want to allow ARG `const T' to unify with
15342          PARM `T' for example, when computing which of two templates
15343          is more specialized, for example.  */
15344       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
15345       && !check_cv_quals_for_unify (strict_in, arg, parm))
15346     return 1;
15347
15348   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
15349       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
15350     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
15351   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
15352   strict &= ~UNIFY_ALLOW_DERIVED;
15353   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
15354   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
15355
15356   switch (TREE_CODE (parm))
15357     {
15358     case TYPENAME_TYPE:
15359     case SCOPE_REF:
15360     case UNBOUND_CLASS_TEMPLATE:
15361       /* In a type which contains a nested-name-specifier, template
15362          argument values cannot be deduced for template parameters used
15363          within the nested-name-specifier.  */
15364       return 0;
15365
15366     case TEMPLATE_TYPE_PARM:
15367     case TEMPLATE_TEMPLATE_PARM:
15368     case BOUND_TEMPLATE_TEMPLATE_PARM:
15369       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15370       if (tparm == error_mark_node)
15371         return 1;
15372
15373       if (TEMPLATE_TYPE_LEVEL (parm)
15374           != template_decl_level (tparm))
15375         /* The PARM is not one we're trying to unify.  Just check
15376            to see if it matches ARG.  */
15377         return (TREE_CODE (arg) == TREE_CODE (parm)
15378                 && same_type_p (parm, arg)) ? 0 : 1;
15379       idx = TEMPLATE_TYPE_IDX (parm);
15380       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15381       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15382
15383       /* Check for mixed types and values.  */
15384       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15385            && TREE_CODE (tparm) != TYPE_DECL)
15386           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15387               && TREE_CODE (tparm) != TEMPLATE_DECL))
15388         return 1;
15389
15390       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15391         {
15392           /* ARG must be constructed from a template class or a template
15393              template parameter.  */
15394           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15395               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15396             return 1;
15397
15398           {
15399             tree parmvec = TYPE_TI_ARGS (parm);
15400             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15401             tree full_argvec = add_to_template_args (targs, argvec);
15402             tree parm_parms 
15403               = DECL_INNERMOST_TEMPLATE_PARMS
15404                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15405             int i, len;
15406             int parm_variadic_p = 0;
15407
15408             /* The resolution to DR150 makes clear that default
15409                arguments for an N-argument may not be used to bind T
15410                to a template template parameter with fewer than N
15411                parameters.  It is not safe to permit the binding of
15412                default arguments as an extension, as that may change
15413                the meaning of a conforming program.  Consider:
15414
15415                   struct Dense { static const unsigned int dim = 1; };
15416
15417                   template <template <typename> class View,
15418                             typename Block>
15419                   void operator+(float, View<Block> const&);
15420
15421                   template <typename Block,
15422                             unsigned int Dim = Block::dim>
15423                   struct Lvalue_proxy { operator float() const; };
15424
15425                   void
15426                   test_1d (void) {
15427                     Lvalue_proxy<Dense> p;
15428                     float b;
15429                     b + p;
15430                   }
15431
15432               Here, if Lvalue_proxy is permitted to bind to View, then
15433               the global operator+ will be used; if they are not, the
15434               Lvalue_proxy will be converted to float.  */
15435             if (coerce_template_parms (parm_parms,
15436                                        full_argvec,
15437                                        TYPE_TI_TEMPLATE (parm),
15438                                        tf_none,
15439                                        /*require_all_args=*/true,
15440                                        /*use_default_args=*/false)
15441                 == error_mark_node)
15442               return 1;
15443
15444             /* Deduce arguments T, i from TT<T> or TT<i>.
15445                We check each element of PARMVEC and ARGVEC individually
15446                rather than the whole TREE_VEC since they can have
15447                different number of elements.  */
15448
15449             parmvec = expand_template_argument_pack (parmvec);
15450             argvec = expand_template_argument_pack (argvec);
15451
15452             len = TREE_VEC_LENGTH (parmvec);
15453
15454             /* Check if the parameters end in a pack, making them
15455                variadic.  */
15456             if (len > 0
15457                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15458               parm_variadic_p = 1;
15459             
15460             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15461               return 1;
15462
15463              for (i = 0; i < len - parm_variadic_p; ++i)
15464               {
15465                 if (unify (tparms, targs,
15466                            TREE_VEC_ELT (parmvec, i),
15467                            TREE_VEC_ELT (argvec, i),
15468                            UNIFY_ALLOW_NONE))
15469                   return 1;
15470               }
15471
15472             if (parm_variadic_p
15473                 && unify_pack_expansion (tparms, targs,
15474                                          parmvec, argvec,
15475                                          UNIFY_ALLOW_NONE,
15476                                          /*call_args_p=*/false,
15477                                          /*subr=*/false))
15478               return 1;
15479           }
15480           arg = TYPE_TI_TEMPLATE (arg);
15481
15482           /* Fall through to deduce template name.  */
15483         }
15484
15485       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15486           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15487         {
15488           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
15489
15490           /* Simple cases: Value already set, does match or doesn't.  */
15491           if (targ != NULL_TREE && template_args_equal (targ, arg))
15492             return 0;
15493           else if (targ)
15494             return 1;
15495         }
15496       else
15497         {
15498           /* If PARM is `const T' and ARG is only `int', we don't have
15499              a match unless we are allowing additional qualification.
15500              If ARG is `const int' and PARM is just `T' that's OK;
15501              that binds `const int' to `T'.  */
15502           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
15503                                          arg, parm))
15504             return 1;
15505
15506           /* Consider the case where ARG is `const volatile int' and
15507              PARM is `const T'.  Then, T should be `volatile int'.  */
15508           arg = cp_build_qualified_type_real
15509             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
15510           if (arg == error_mark_node)
15511             return 1;
15512
15513           /* Simple cases: Value already set, does match or doesn't.  */
15514           if (targ != NULL_TREE && same_type_p (targ, arg))
15515             return 0;
15516           else if (targ)
15517             return 1;
15518
15519           /* Make sure that ARG is not a variable-sized array.  (Note
15520              that were talking about variable-sized arrays (like
15521              `int[n]'), rather than arrays of unknown size (like
15522              `int[]').)  We'll get very confused by such a type since
15523              the bound of the array will not be computable in an
15524              instantiation.  Besides, such types are not allowed in
15525              ISO C++, so we can do as we please here.  */
15526           if (variably_modified_type_p (arg, NULL_TREE))
15527             return 1;
15528
15529           /* Strip typedefs as in convert_template_argument.  */
15530           arg = canonicalize_type_argument (arg, tf_none);
15531         }
15532
15533       /* If ARG is a parameter pack or an expansion, we cannot unify
15534          against it unless PARM is also a parameter pack.  */
15535       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15536           && !template_parameter_pack_p (parm))
15537         return 1;
15538
15539       /* If the argument deduction results is a METHOD_TYPE,
15540          then there is a problem.
15541          METHOD_TYPE doesn't map to any real C++ type the result of
15542          the deduction can not be of that type.  */
15543       if (TREE_CODE (arg) == METHOD_TYPE)
15544         return 1;
15545
15546       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15547       return 0;
15548
15549     case TEMPLATE_PARM_INDEX:
15550       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15551       if (tparm == error_mark_node)
15552         return 1;
15553
15554       if (TEMPLATE_PARM_LEVEL (parm)
15555           != template_decl_level (tparm))
15556         /* The PARM is not one we're trying to unify.  Just check
15557            to see if it matches ARG.  */
15558         return !(TREE_CODE (arg) == TREE_CODE (parm)
15559                  && cp_tree_equal (parm, arg));
15560
15561       idx = TEMPLATE_PARM_IDX (parm);
15562       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15563
15564       if (targ)
15565         return !cp_tree_equal (targ, arg);
15566
15567       /* [temp.deduct.type] If, in the declaration of a function template
15568          with a non-type template-parameter, the non-type
15569          template-parameter is used in an expression in the function
15570          parameter-list and, if the corresponding template-argument is
15571          deduced, the template-argument type shall match the type of the
15572          template-parameter exactly, except that a template-argument
15573          deduced from an array bound may be of any integral type.
15574          The non-type parameter might use already deduced type parameters.  */
15575       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
15576       if (!TREE_TYPE (arg))
15577         /* Template-parameter dependent expression.  Just accept it for now.
15578            It will later be processed in convert_template_argument.  */
15579         ;
15580       else if (same_type_p (TREE_TYPE (arg), tparm))
15581         /* OK */;
15582       else if ((strict & UNIFY_ALLOW_INTEGER)
15583                && (TREE_CODE (tparm) == INTEGER_TYPE
15584                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
15585         /* Convert the ARG to the type of PARM; the deduced non-type
15586            template argument must exactly match the types of the
15587            corresponding parameter.  */
15588         arg = fold (build_nop (tparm, arg));
15589       else if (uses_template_parms (tparm))
15590         /* We haven't deduced the type of this parameter yet.  Try again
15591            later.  */
15592         return 0;
15593       else
15594         return 1;
15595
15596       /* If ARG is a parameter pack or an expansion, we cannot unify
15597          against it unless PARM is also a parameter pack.  */
15598       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15599           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
15600         return 1;
15601
15602       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15603       return 0;
15604
15605     case PTRMEM_CST:
15606      {
15607         /* A pointer-to-member constant can be unified only with
15608          another constant.  */
15609       if (TREE_CODE (arg) != PTRMEM_CST)
15610         return 1;
15611
15612       /* Just unify the class member. It would be useless (and possibly
15613          wrong, depending on the strict flags) to unify also
15614          PTRMEM_CST_CLASS, because we want to be sure that both parm and
15615          arg refer to the same variable, even if through different
15616          classes. For instance:
15617
15618          struct A { int x; };
15619          struct B : A { };
15620
15621          Unification of &A::x and &B::x must succeed.  */
15622       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
15623                     PTRMEM_CST_MEMBER (arg), strict);
15624      }
15625
15626     case POINTER_TYPE:
15627       {
15628         if (TREE_CODE (arg) != POINTER_TYPE)
15629           return 1;
15630
15631         /* [temp.deduct.call]
15632
15633            A can be another pointer or pointer to member type that can
15634            be converted to the deduced A via a qualification
15635            conversion (_conv.qual_).
15636
15637            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
15638            This will allow for additional cv-qualification of the
15639            pointed-to types if appropriate.  */
15640
15641         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
15642           /* The derived-to-base conversion only persists through one
15643              level of pointers.  */
15644           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
15645
15646         return unify (tparms, targs, TREE_TYPE (parm),
15647                       TREE_TYPE (arg), strict);
15648       }
15649
15650     case REFERENCE_TYPE:
15651       if (TREE_CODE (arg) != REFERENCE_TYPE)
15652         return 1;
15653       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15654                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15655
15656     case ARRAY_TYPE:
15657       if (TREE_CODE (arg) != ARRAY_TYPE)
15658         return 1;
15659       if ((TYPE_DOMAIN (parm) == NULL_TREE)
15660           != (TYPE_DOMAIN (arg) == NULL_TREE))
15661         return 1;
15662       if (TYPE_DOMAIN (parm) != NULL_TREE)
15663         {
15664           tree parm_max;
15665           tree arg_max;
15666           bool parm_cst;
15667           bool arg_cst;
15668
15669           /* Our representation of array types uses "N - 1" as the
15670              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
15671              not an integer constant.  We cannot unify arbitrarily
15672              complex expressions, so we eliminate the MINUS_EXPRs
15673              here.  */
15674           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
15675           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
15676           if (!parm_cst)
15677             {
15678               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
15679               parm_max = TREE_OPERAND (parm_max, 0);
15680             }
15681           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
15682           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
15683           if (!arg_cst)
15684             {
15685               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
15686                  trying to unify the type of a variable with the type
15687                  of a template parameter.  For example:
15688
15689                    template <unsigned int N>
15690                    void f (char (&) [N]);
15691                    int g(); 
15692                    void h(int i) {
15693                      char a[g(i)];
15694                      f(a); 
15695                    }
15696
15697                 Here, the type of the ARG will be "int [g(i)]", and
15698                 may be a SAVE_EXPR, etc.  */
15699               if (TREE_CODE (arg_max) != MINUS_EXPR)
15700                 return 1;
15701               arg_max = TREE_OPERAND (arg_max, 0);
15702             }
15703
15704           /* If only one of the bounds used a MINUS_EXPR, compensate
15705              by adding one to the other bound.  */
15706           if (parm_cst && !arg_cst)
15707             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
15708                                     integer_type_node,
15709                                     parm_max,
15710                                     integer_one_node);
15711           else if (arg_cst && !parm_cst)
15712             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
15713                                    integer_type_node,
15714                                    arg_max,
15715                                    integer_one_node);
15716
15717           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
15718             return 1;
15719         }
15720       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15721                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15722
15723     case REAL_TYPE:
15724     case COMPLEX_TYPE:
15725     case VECTOR_TYPE:
15726     case INTEGER_TYPE:
15727     case BOOLEAN_TYPE:
15728     case ENUMERAL_TYPE:
15729     case VOID_TYPE:
15730       if (TREE_CODE (arg) != TREE_CODE (parm))
15731         return 1;
15732
15733       /* We have already checked cv-qualification at the top of the
15734          function.  */
15735       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
15736         return 1;
15737
15738       /* As far as unification is concerned, this wins.  Later checks
15739          will invalidate it if necessary.  */
15740       return 0;
15741
15742       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
15743       /* Type INTEGER_CST can come from ordinary constant template args.  */
15744     case INTEGER_CST:
15745       while (TREE_CODE (arg) == NOP_EXPR)
15746         arg = TREE_OPERAND (arg, 0);
15747
15748       if (TREE_CODE (arg) != INTEGER_CST)
15749         return 1;
15750       return !tree_int_cst_equal (parm, arg);
15751
15752     case TREE_VEC:
15753       {
15754         int i;
15755         if (TREE_CODE (arg) != TREE_VEC)
15756           return 1;
15757         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
15758           return 1;
15759         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
15760           if (unify (tparms, targs,
15761                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
15762                      UNIFY_ALLOW_NONE))
15763             return 1;
15764         return 0;
15765       }
15766
15767     case RECORD_TYPE:
15768     case UNION_TYPE:
15769       if (TREE_CODE (arg) != TREE_CODE (parm))
15770         return 1;
15771
15772       if (TYPE_PTRMEMFUNC_P (parm))
15773         {
15774           if (!TYPE_PTRMEMFUNC_P (arg))
15775             return 1;
15776
15777           return unify (tparms, targs,
15778                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
15779                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
15780                         strict);
15781         }
15782
15783       if (CLASSTYPE_TEMPLATE_INFO (parm))
15784         {
15785           tree t = NULL_TREE;
15786
15787           if (strict_in & UNIFY_ALLOW_DERIVED)
15788             {
15789               /* First, we try to unify the PARM and ARG directly.  */
15790               t = try_class_unification (tparms, targs,
15791                                          parm, arg);
15792
15793               if (!t)
15794                 {
15795                   /* Fallback to the special case allowed in
15796                      [temp.deduct.call]:
15797
15798                        If P is a class, and P has the form
15799                        template-id, then A can be a derived class of
15800                        the deduced A.  Likewise, if P is a pointer to
15801                        a class of the form template-id, A can be a
15802                        pointer to a derived class pointed to by the
15803                        deduced A.  */
15804                   t = get_template_base (tparms, targs, parm, arg);
15805
15806                   if (!t)
15807                     return 1;
15808                 }
15809             }
15810           else if (CLASSTYPE_TEMPLATE_INFO (arg)
15811                    && (CLASSTYPE_TI_TEMPLATE (parm)
15812                        == CLASSTYPE_TI_TEMPLATE (arg)))
15813             /* Perhaps PARM is something like S<U> and ARG is S<int>.
15814                Then, we should unify `int' and `U'.  */
15815             t = arg;
15816           else
15817             /* There's no chance of unification succeeding.  */
15818             return 1;
15819
15820           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
15821                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
15822         }
15823       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
15824         return 1;
15825       return 0;
15826
15827     case METHOD_TYPE:
15828     case FUNCTION_TYPE:
15829       {
15830         unsigned int nargs;
15831         tree *args;
15832         tree a;
15833         unsigned int i;
15834
15835         if (TREE_CODE (arg) != TREE_CODE (parm))
15836           return 1;
15837
15838         /* CV qualifications for methods can never be deduced, they must
15839            match exactly.  We need to check them explicitly here,
15840            because type_unification_real treats them as any other
15841            cv-qualified parameter.  */
15842         if (TREE_CODE (parm) == METHOD_TYPE
15843             && (!check_cv_quals_for_unify
15844                 (UNIFY_ALLOW_NONE,
15845                  class_of_this_parm (arg),
15846                  class_of_this_parm (parm))))
15847           return 1;
15848
15849         if (unify (tparms, targs, TREE_TYPE (parm),
15850                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15851           return 1;
15852
15853         nargs = list_length (TYPE_ARG_TYPES (arg));
15854         args = XALLOCAVEC (tree, nargs);
15855         for (a = TYPE_ARG_TYPES (arg), i = 0;
15856              a != NULL_TREE && a != void_list_node;
15857              a = TREE_CHAIN (a), ++i)
15858           args[i] = TREE_VALUE (a);
15859         nargs = i;
15860
15861         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15862                                       args, nargs, 1, DEDUCE_EXACT,
15863                                       LOOKUP_NORMAL);
15864       }
15865
15866     case OFFSET_TYPE:
15867       /* Unify a pointer to member with a pointer to member function, which
15868          deduces the type of the member as a function type. */
15869       if (TYPE_PTRMEMFUNC_P (arg))
15870         {
15871           tree method_type;
15872           tree fntype;
15873
15874           /* Check top-level cv qualifiers */
15875           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15876             return 1;
15877
15878           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15879                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15880             return 1;
15881
15882           /* Determine the type of the function we are unifying against. */
15883           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15884           fntype =
15885             build_function_type (TREE_TYPE (method_type),
15886                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15887
15888           /* Extract the cv-qualifiers of the member function from the
15889              implicit object parameter and place them on the function
15890              type to be restored later. */
15891           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
15892           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15893         }
15894
15895       if (TREE_CODE (arg) != OFFSET_TYPE)
15896         return 1;
15897       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15898                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15899         return 1;
15900       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15901                     strict);
15902
15903     case CONST_DECL:
15904       if (DECL_TEMPLATE_PARM_P (parm))
15905         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15906       if (arg != integral_constant_value (parm))
15907         return 1;
15908       return 0;
15909
15910     case FIELD_DECL:
15911     case TEMPLATE_DECL:
15912       /* Matched cases are handled by the ARG == PARM test above.  */
15913       return 1;
15914
15915     case VAR_DECL:
15916       /* A non-type template parameter that is a variable should be a
15917          an integral constant, in which case, it whould have been
15918          folded into its (constant) value. So we should not be getting
15919          a variable here.  */
15920       gcc_unreachable ();
15921
15922     case TYPE_ARGUMENT_PACK:
15923     case NONTYPE_ARGUMENT_PACK:
15924       {
15925         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15926         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15927         int i, len = TREE_VEC_LENGTH (packed_parms);
15928         int argslen = TREE_VEC_LENGTH (packed_args);
15929         int parm_variadic_p = 0;
15930
15931         for (i = 0; i < len; ++i)
15932           {
15933             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15934               {
15935                 if (i == len - 1)
15936                   /* We can unify against something with a trailing
15937                      parameter pack.  */
15938                   parm_variadic_p = 1;
15939                 else
15940                   /* Since there is something following the pack
15941                      expansion, we cannot unify this template argument
15942                      list.  */
15943                   return 0;
15944               }
15945           }
15946           
15947
15948         /* If we don't have enough arguments to satisfy the parameters
15949            (not counting the pack expression at the end), or we have
15950            too many arguments for a parameter list that doesn't end in
15951            a pack expression, we can't unify.  */
15952         if (argslen < (len - parm_variadic_p)
15953             || (argslen > len && !parm_variadic_p))
15954           return 1;
15955
15956         /* Unify all of the parameters that precede the (optional)
15957            pack expression.  */
15958         for (i = 0; i < len - parm_variadic_p; ++i)
15959           {
15960             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15961                        TREE_VEC_ELT (packed_args, i), strict))
15962               return 1;
15963           }
15964
15965         if (parm_variadic_p)
15966           return unify_pack_expansion (tparms, targs, 
15967                                        packed_parms, packed_args,
15968                                        strict, /*call_args_p=*/false,
15969                                        /*subr=*/false);
15970         return 0;
15971       }
15972
15973       break;
15974
15975     case TYPEOF_TYPE:
15976     case DECLTYPE_TYPE:
15977     case UNDERLYING_TYPE:
15978       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
15979          or UNDERLYING_TYPE nodes.  */
15980       return 0;
15981
15982     case ERROR_MARK:
15983       /* Unification fails if we hit an error node.  */
15984       return 1;
15985
15986     default:
15987       /* An unresolved overload is a nondeduced context.  */
15988       if (type_unknown_p (parm))
15989         return 0;
15990       gcc_assert (EXPR_P (parm));
15991
15992       /* We must be looking at an expression.  This can happen with
15993          something like:
15994
15995            template <int I>
15996            void foo(S<I>, S<I + 2>);
15997
15998          This is a "nondeduced context":
15999
16000            [deduct.type]
16001
16002            The nondeduced contexts are:
16003
16004            --A type that is a template-id in which one or more of
16005              the template-arguments is an expression that references
16006              a template-parameter.
16007
16008          In these cases, we assume deduction succeeded, but don't
16009          actually infer any unifications.  */
16010
16011       if (!uses_template_parms (parm)
16012           && !template_args_equal (parm, arg))
16013         return 1;
16014       else
16015         return 0;
16016     }
16017 }
16018 \f
16019 /* Note that DECL can be defined in this translation unit, if
16020    required.  */
16021
16022 static void
16023 mark_definable (tree decl)
16024 {
16025   tree clone;
16026   DECL_NOT_REALLY_EXTERN (decl) = 1;
16027   FOR_EACH_CLONE (clone, decl)
16028     DECL_NOT_REALLY_EXTERN (clone) = 1;
16029 }
16030
16031 /* Called if RESULT is explicitly instantiated, or is a member of an
16032    explicitly instantiated class.  */
16033
16034 void
16035 mark_decl_instantiated (tree result, int extern_p)
16036 {
16037   SET_DECL_EXPLICIT_INSTANTIATION (result);
16038
16039   /* If this entity has already been written out, it's too late to
16040      make any modifications.  */
16041   if (TREE_ASM_WRITTEN (result))
16042     return;
16043
16044   if (TREE_CODE (result) != FUNCTION_DECL)
16045     /* The TREE_PUBLIC flag for function declarations will have been
16046        set correctly by tsubst.  */
16047     TREE_PUBLIC (result) = 1;
16048
16049   /* This might have been set by an earlier implicit instantiation.  */
16050   DECL_COMDAT (result) = 0;
16051
16052   if (extern_p)
16053     DECL_NOT_REALLY_EXTERN (result) = 0;
16054   else
16055     {
16056       mark_definable (result);
16057       /* Always make artificials weak.  */
16058       if (DECL_ARTIFICIAL (result) && flag_weak)
16059         comdat_linkage (result);
16060       /* For WIN32 we also want to put explicit instantiations in
16061          linkonce sections.  */
16062       else if (TREE_PUBLIC (result))
16063         maybe_make_one_only (result);
16064     }
16065
16066   /* If EXTERN_P, then this function will not be emitted -- unless
16067      followed by an explicit instantiation, at which point its linkage
16068      will be adjusted.  If !EXTERN_P, then this function will be
16069      emitted here.  In neither circumstance do we want
16070      import_export_decl to adjust the linkage.  */
16071   DECL_INTERFACE_KNOWN (result) = 1;
16072 }
16073
16074 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
16075    important template arguments.  If any are missing, we check whether
16076    they're important by using error_mark_node for substituting into any
16077    args that were used for partial ordering (the ones between ARGS and END)
16078    and seeing if it bubbles up.  */
16079
16080 static bool
16081 check_undeduced_parms (tree targs, tree args, tree end)
16082 {
16083   bool found = false;
16084   int i;
16085   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
16086     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
16087       {
16088         found = true;
16089         TREE_VEC_ELT (targs, i) = error_mark_node;
16090       }
16091   if (found)
16092     {
16093       for (; args != end; args = TREE_CHAIN (args))
16094         {
16095           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
16096           if (substed == error_mark_node)
16097             return true;
16098         }
16099     }
16100   return false;
16101 }
16102
16103 /* Given two function templates PAT1 and PAT2, return:
16104
16105    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
16106    -1 if PAT2 is more specialized than PAT1.
16107    0 if neither is more specialized.
16108
16109    LEN indicates the number of parameters we should consider
16110    (defaulted parameters should not be considered).
16111
16112    The 1998 std underspecified function template partial ordering, and
16113    DR214 addresses the issue.  We take pairs of arguments, one from
16114    each of the templates, and deduce them against each other.  One of
16115    the templates will be more specialized if all the *other*
16116    template's arguments deduce against its arguments and at least one
16117    of its arguments *does* *not* deduce against the other template's
16118    corresponding argument.  Deduction is done as for class templates.
16119    The arguments used in deduction have reference and top level cv
16120    qualifiers removed.  Iff both arguments were originally reference
16121    types *and* deduction succeeds in both directions, the template
16122    with the more cv-qualified argument wins for that pairing (if
16123    neither is more cv-qualified, they both are equal).  Unlike regular
16124    deduction, after all the arguments have been deduced in this way,
16125    we do *not* verify the deduced template argument values can be
16126    substituted into non-deduced contexts.
16127
16128    The logic can be a bit confusing here, because we look at deduce1 and
16129    targs1 to see if pat2 is at least as specialized, and vice versa; if we
16130    can find template arguments for pat1 to make arg1 look like arg2, that
16131    means that arg2 is at least as specialized as arg1.  */
16132
16133 int
16134 more_specialized_fn (tree pat1, tree pat2, int len)
16135 {
16136   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
16137   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
16138   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
16139   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
16140   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
16141   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
16142   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
16143   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
16144   tree origs1, origs2;
16145   bool lose1 = false;
16146   bool lose2 = false;
16147
16148   /* Remove the this parameter from non-static member functions.  If
16149      one is a non-static member function and the other is not a static
16150      member function, remove the first parameter from that function
16151      also.  This situation occurs for operator functions where we
16152      locate both a member function (with this pointer) and non-member
16153      operator (with explicit first operand).  */
16154   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
16155     {
16156       len--; /* LEN is the number of significant arguments for DECL1 */
16157       args1 = TREE_CHAIN (args1);
16158       if (!DECL_STATIC_FUNCTION_P (decl2))
16159         args2 = TREE_CHAIN (args2);
16160     }
16161   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
16162     {
16163       args2 = TREE_CHAIN (args2);
16164       if (!DECL_STATIC_FUNCTION_P (decl1))
16165         {
16166           len--;
16167           args1 = TREE_CHAIN (args1);
16168         }
16169     }
16170
16171   /* If only one is a conversion operator, they are unordered.  */
16172   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
16173     return 0;
16174
16175   /* Consider the return type for a conversion function */
16176   if (DECL_CONV_FN_P (decl1))
16177     {
16178       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
16179       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
16180       len++;
16181     }
16182
16183   processing_template_decl++;
16184
16185   origs1 = args1;
16186   origs2 = args2;
16187
16188   while (len--
16189          /* Stop when an ellipsis is seen.  */
16190          && args1 != NULL_TREE && args2 != NULL_TREE)
16191     {
16192       tree arg1 = TREE_VALUE (args1);
16193       tree arg2 = TREE_VALUE (args2);
16194       int deduce1, deduce2;
16195       int quals1 = -1;
16196       int quals2 = -1;
16197
16198       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16199           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16200         {
16201           /* When both arguments are pack expansions, we need only
16202              unify the patterns themselves.  */
16203           arg1 = PACK_EXPANSION_PATTERN (arg1);
16204           arg2 = PACK_EXPANSION_PATTERN (arg2);
16205
16206           /* This is the last comparison we need to do.  */
16207           len = 0;
16208         }
16209
16210       if (TREE_CODE (arg1) == REFERENCE_TYPE)
16211         {
16212           arg1 = TREE_TYPE (arg1);
16213           quals1 = cp_type_quals (arg1);
16214         }
16215
16216       if (TREE_CODE (arg2) == REFERENCE_TYPE)
16217         {
16218           arg2 = TREE_TYPE (arg2);
16219           quals2 = cp_type_quals (arg2);
16220         }
16221
16222       if ((quals1 < 0) != (quals2 < 0))
16223         {
16224           /* Only of the args is a reference, see if we should apply
16225              array/function pointer decay to it.  This is not part of
16226              DR214, but is, IMHO, consistent with the deduction rules
16227              for the function call itself, and with our earlier
16228              implementation of the underspecified partial ordering
16229              rules.  (nathan).  */
16230           if (quals1 >= 0)
16231             {
16232               switch (TREE_CODE (arg1))
16233                 {
16234                 case ARRAY_TYPE:
16235                   arg1 = TREE_TYPE (arg1);
16236                   /* FALLTHROUGH. */
16237                 case FUNCTION_TYPE:
16238                   arg1 = build_pointer_type (arg1);
16239                   break;
16240
16241                 default:
16242                   break;
16243                 }
16244             }
16245           else
16246             {
16247               switch (TREE_CODE (arg2))
16248                 {
16249                 case ARRAY_TYPE:
16250                   arg2 = TREE_TYPE (arg2);
16251                   /* FALLTHROUGH. */
16252                 case FUNCTION_TYPE:
16253                   arg2 = build_pointer_type (arg2);
16254                   break;
16255
16256                 default:
16257                   break;
16258                 }
16259             }
16260         }
16261
16262       arg1 = TYPE_MAIN_VARIANT (arg1);
16263       arg2 = TYPE_MAIN_VARIANT (arg2);
16264
16265       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
16266         {
16267           int i, len2 = list_length (args2);
16268           tree parmvec = make_tree_vec (1);
16269           tree argvec = make_tree_vec (len2);
16270           tree ta = args2;
16271
16272           /* Setup the parameter vector, which contains only ARG1.  */
16273           TREE_VEC_ELT (parmvec, 0) = arg1;
16274
16275           /* Setup the argument vector, which contains the remaining
16276              arguments.  */
16277           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
16278             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16279
16280           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
16281                                            argvec, UNIFY_ALLOW_NONE, 
16282                                            /*call_args_p=*/false, 
16283                                            /*subr=*/0);
16284
16285           /* We cannot deduce in the other direction, because ARG1 is
16286              a pack expansion but ARG2 is not.  */
16287           deduce2 = 0;
16288         }
16289       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16290         {
16291           int i, len1 = list_length (args1);
16292           tree parmvec = make_tree_vec (1);
16293           tree argvec = make_tree_vec (len1);
16294           tree ta = args1;
16295
16296           /* Setup the parameter vector, which contains only ARG1.  */
16297           TREE_VEC_ELT (parmvec, 0) = arg2;
16298
16299           /* Setup the argument vector, which contains the remaining
16300              arguments.  */
16301           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
16302             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16303
16304           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
16305                                            argvec, UNIFY_ALLOW_NONE, 
16306                                            /*call_args_p=*/false, 
16307                                            /*subr=*/0);
16308
16309           /* We cannot deduce in the other direction, because ARG2 is
16310              a pack expansion but ARG1 is not.*/
16311           deduce1 = 0;
16312         }
16313
16314       else
16315         {
16316           /* The normal case, where neither argument is a pack
16317              expansion.  */
16318           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
16319           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
16320         }
16321
16322       /* If we couldn't deduce arguments for tparms1 to make arg1 match
16323          arg2, then arg2 is not as specialized as arg1.  */
16324       if (!deduce1)
16325         lose2 = true;
16326       if (!deduce2)
16327         lose1 = true;
16328
16329       /* "If, for a given type, deduction succeeds in both directions
16330          (i.e., the types are identical after the transformations above)
16331          and if the type from the argument template is more cv-qualified
16332          than the type from the parameter template (as described above)
16333          that type is considered to be more specialized than the other. If
16334          neither type is more cv-qualified than the other then neither type
16335          is more specialized than the other."  */
16336
16337       if (deduce1 && deduce2
16338           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
16339         {
16340           if ((quals1 & quals2) == quals2)
16341             lose2 = true;
16342           if ((quals1 & quals2) == quals1)
16343             lose1 = true;
16344         }
16345
16346       if (lose1 && lose2)
16347         /* We've failed to deduce something in either direction.
16348            These must be unordered.  */
16349         break;
16350
16351       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16352           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16353         /* We have already processed all of the arguments in our
16354            handing of the pack expansion type.  */
16355         len = 0;
16356
16357       args1 = TREE_CHAIN (args1);
16358       args2 = TREE_CHAIN (args2);
16359     }
16360
16361   /* "In most cases, all template parameters must have values in order for
16362      deduction to succeed, but for partial ordering purposes a template
16363      parameter may remain without a value provided it is not used in the
16364      types being used for partial ordering."
16365
16366      Thus, if we are missing any of the targs1 we need to substitute into
16367      origs1, then pat2 is not as specialized as pat1.  This can happen when
16368      there is a nondeduced context.  */
16369   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
16370     lose2 = true;
16371   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
16372     lose1 = true;
16373
16374   processing_template_decl--;
16375
16376   /* All things being equal, if the next argument is a pack expansion
16377      for one function but not for the other, prefer the
16378      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16379   if (lose1 == lose2
16380       && args1 && TREE_VALUE (args1)
16381       && args2 && TREE_VALUE (args2))
16382     {
16383       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16384       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16385     }
16386
16387   if (lose1 == lose2)
16388     return 0;
16389   else if (!lose1)
16390     return 1;
16391   else
16392     return -1;
16393 }
16394
16395 /* Determine which of two partial specializations is more specialized.
16396
16397    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16398    to the first partial specialization.  The TREE_VALUE is the
16399    innermost set of template parameters for the partial
16400    specialization.  PAT2 is similar, but for the second template.
16401
16402    Return 1 if the first partial specialization is more specialized;
16403    -1 if the second is more specialized; 0 if neither is more
16404    specialized.
16405
16406    See [temp.class.order] for information about determining which of
16407    two templates is more specialized.  */
16408
16409 static int
16410 more_specialized_class (tree pat1, tree pat2)
16411 {
16412   tree targs;
16413   tree tmpl1, tmpl2;
16414   int winner = 0;
16415   bool any_deductions = false;
16416
16417   tmpl1 = TREE_TYPE (pat1);
16418   tmpl2 = TREE_TYPE (pat2);
16419
16420   /* Just like what happens for functions, if we are ordering between
16421      different class template specializations, we may encounter dependent
16422      types in the arguments, and we need our dependency check functions
16423      to behave correctly.  */
16424   ++processing_template_decl;
16425   targs = get_class_bindings (TREE_VALUE (pat1),
16426                               CLASSTYPE_TI_ARGS (tmpl1),
16427                               CLASSTYPE_TI_ARGS (tmpl2));
16428   if (targs)
16429     {
16430       --winner;
16431       any_deductions = true;
16432     }
16433
16434   targs = get_class_bindings (TREE_VALUE (pat2),
16435                               CLASSTYPE_TI_ARGS (tmpl2),
16436                               CLASSTYPE_TI_ARGS (tmpl1));
16437   if (targs)
16438     {
16439       ++winner;
16440       any_deductions = true;
16441     }
16442   --processing_template_decl;
16443
16444   /* In the case of a tie where at least one of the class templates
16445      has a parameter pack at the end, the template with the most
16446      non-packed parameters wins.  */
16447   if (winner == 0
16448       && any_deductions
16449       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16450           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16451     {
16452       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
16453       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
16454       int len1 = TREE_VEC_LENGTH (args1);
16455       int len2 = TREE_VEC_LENGTH (args2);
16456
16457       /* We don't count the pack expansion at the end.  */
16458       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
16459         --len1;
16460       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
16461         --len2;
16462
16463       if (len1 > len2)
16464         return 1;
16465       else if (len1 < len2)
16466         return -1;
16467     }
16468
16469   return winner;
16470 }
16471
16472 /* Return the template arguments that will produce the function signature
16473    DECL from the function template FN, with the explicit template
16474    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
16475    also match.  Return NULL_TREE if no satisfactory arguments could be
16476    found.  */
16477
16478 static tree
16479 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
16480 {
16481   int ntparms = DECL_NTPARMS (fn);
16482   tree targs = make_tree_vec (ntparms);
16483   tree decl_type;
16484   tree decl_arg_types;
16485   tree *args;
16486   unsigned int nargs, ix;
16487   tree arg;
16488
16489   /* Substitute the explicit template arguments into the type of DECL.
16490      The call to fn_type_unification will handle substitution into the
16491      FN.  */
16492   decl_type = TREE_TYPE (decl);
16493   if (explicit_args && uses_template_parms (decl_type))
16494     {
16495       tree tmpl;
16496       tree converted_args;
16497
16498       if (DECL_TEMPLATE_INFO (decl))
16499         tmpl = DECL_TI_TEMPLATE (decl);
16500       else
16501         /* We can get here for some invalid specializations.  */
16502         return NULL_TREE;
16503
16504       converted_args
16505         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16506                                  explicit_args, NULL_TREE,
16507                                  tf_none,
16508                                  /*require_all_args=*/false,
16509                                  /*use_default_args=*/false);
16510       if (converted_args == error_mark_node)
16511         return NULL_TREE;
16512
16513       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
16514       if (decl_type == error_mark_node)
16515         return NULL_TREE;
16516     }
16517
16518   /* Never do unification on the 'this' parameter.  */
16519   decl_arg_types = skip_artificial_parms_for (decl, 
16520                                               TYPE_ARG_TYPES (decl_type));
16521
16522   nargs = list_length (decl_arg_types);
16523   args = XALLOCAVEC (tree, nargs);
16524   for (arg = decl_arg_types, ix = 0;
16525        arg != NULL_TREE && arg != void_list_node;
16526        arg = TREE_CHAIN (arg), ++ix)
16527     args[ix] = TREE_VALUE (arg);
16528
16529   if (fn_type_unification (fn, explicit_args, targs,
16530                            args, ix,
16531                            (check_rettype || DECL_CONV_FN_P (fn)
16532                             ? TREE_TYPE (decl_type) : NULL_TREE),
16533                            DEDUCE_EXACT, LOOKUP_NORMAL))
16534     return NULL_TREE;
16535
16536   return targs;
16537 }
16538
16539 /* Return the innermost template arguments that, when applied to a
16540    template specialization whose innermost template parameters are
16541    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
16542    ARGS.
16543
16544    For example, suppose we have:
16545
16546      template <class T, class U> struct S {};
16547      template <class T> struct S<T*, int> {};
16548
16549    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
16550    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
16551    int}.  The resulting vector will be {double}, indicating that `T'
16552    is bound to `double'.  */
16553
16554 static tree
16555 get_class_bindings (tree tparms, tree spec_args, tree args)
16556 {
16557   int i, ntparms = TREE_VEC_LENGTH (tparms);
16558   tree deduced_args;
16559   tree innermost_deduced_args;
16560
16561   innermost_deduced_args = make_tree_vec (ntparms);
16562   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16563     {
16564       deduced_args = copy_node (args);
16565       SET_TMPL_ARGS_LEVEL (deduced_args,
16566                            TMPL_ARGS_DEPTH (deduced_args),
16567                            innermost_deduced_args);
16568     }
16569   else
16570     deduced_args = innermost_deduced_args;
16571
16572   if (unify (tparms, deduced_args,
16573              INNERMOST_TEMPLATE_ARGS (spec_args),
16574              INNERMOST_TEMPLATE_ARGS (args),
16575              UNIFY_ALLOW_NONE))
16576     return NULL_TREE;
16577
16578   for (i =  0; i < ntparms; ++i)
16579     if (! TREE_VEC_ELT (innermost_deduced_args, i))
16580       return NULL_TREE;
16581
16582   /* Verify that nondeduced template arguments agree with the type
16583      obtained from argument deduction.
16584
16585      For example:
16586
16587        struct A { typedef int X; };
16588        template <class T, class U> struct C {};
16589        template <class T> struct C<T, typename T::X> {};
16590
16591      Then with the instantiation `C<A, int>', we can deduce that
16592      `T' is `A' but unify () does not check whether `typename T::X'
16593      is `int'.  */
16594   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
16595   if (spec_args == error_mark_node
16596       /* We only need to check the innermost arguments; the other
16597          arguments will always agree.  */
16598       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
16599                               INNERMOST_TEMPLATE_ARGS (args)))
16600     return NULL_TREE;
16601
16602   /* Now that we have bindings for all of the template arguments,
16603      ensure that the arguments deduced for the template template
16604      parameters have compatible template parameter lists.  See the use
16605      of template_template_parm_bindings_ok_p in fn_type_unification
16606      for more information.  */
16607   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
16608     return NULL_TREE;
16609
16610   return deduced_args;
16611 }
16612
16613 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
16614    Return the TREE_LIST node with the most specialized template, if
16615    any.  If there is no most specialized template, the error_mark_node
16616    is returned.
16617
16618    Note that this function does not look at, or modify, the
16619    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
16620    returned is one of the elements of INSTANTIATIONS, callers may
16621    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
16622    and retrieve it from the value returned.  */
16623
16624 tree
16625 most_specialized_instantiation (tree templates)
16626 {
16627   tree fn, champ;
16628
16629   ++processing_template_decl;
16630
16631   champ = templates;
16632   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
16633     {
16634       int fate = 0;
16635
16636       if (get_bindings (TREE_VALUE (champ),
16637                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16638                         NULL_TREE, /*check_ret=*/true))
16639         fate--;
16640
16641       if (get_bindings (TREE_VALUE (fn),
16642                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16643                         NULL_TREE, /*check_ret=*/true))
16644         fate++;
16645
16646       if (fate == -1)
16647         champ = fn;
16648       else if (!fate)
16649         {
16650           /* Equally specialized, move to next function.  If there
16651              is no next function, nothing's most specialized.  */
16652           fn = TREE_CHAIN (fn);
16653           champ = fn;
16654           if (!fn)
16655             break;
16656         }
16657     }
16658
16659   if (champ)
16660     /* Now verify that champ is better than everything earlier in the
16661        instantiation list.  */
16662     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
16663       if (get_bindings (TREE_VALUE (champ),
16664                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16665                         NULL_TREE, /*check_ret=*/true)
16666           || !get_bindings (TREE_VALUE (fn),
16667                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16668                             NULL_TREE, /*check_ret=*/true))
16669         {
16670           champ = NULL_TREE;
16671           break;
16672         }
16673
16674   processing_template_decl--;
16675
16676   if (!champ)
16677     return error_mark_node;
16678
16679   return champ;
16680 }
16681
16682 /* If DECL is a specialization of some template, return the most
16683    general such template.  Otherwise, returns NULL_TREE.
16684
16685    For example, given:
16686
16687      template <class T> struct S { template <class U> void f(U); };
16688
16689    if TMPL is `template <class U> void S<int>::f(U)' this will return
16690    the full template.  This function will not trace past partial
16691    specializations, however.  For example, given in addition:
16692
16693      template <class T> struct S<T*> { template <class U> void f(U); };
16694
16695    if TMPL is `template <class U> void S<int*>::f(U)' this will return
16696    `template <class T> template <class U> S<T*>::f(U)'.  */
16697
16698 tree
16699 most_general_template (tree decl)
16700 {
16701   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
16702      an immediate specialization.  */
16703   if (TREE_CODE (decl) == FUNCTION_DECL)
16704     {
16705       if (DECL_TEMPLATE_INFO (decl)) {
16706         decl = DECL_TI_TEMPLATE (decl);
16707
16708         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
16709            template friend.  */
16710         if (TREE_CODE (decl) != TEMPLATE_DECL)
16711           return NULL_TREE;
16712       } else
16713         return NULL_TREE;
16714     }
16715
16716   /* Look for more and more general templates.  */
16717   while (DECL_TEMPLATE_INFO (decl))
16718     {
16719       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
16720          (See cp-tree.h for details.)  */
16721       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
16722         break;
16723
16724       if (CLASS_TYPE_P (TREE_TYPE (decl))
16725           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
16726         break;
16727
16728       /* Stop if we run into an explicitly specialized class template.  */
16729       if (!DECL_NAMESPACE_SCOPE_P (decl)
16730           && DECL_CONTEXT (decl)
16731           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
16732         break;
16733
16734       decl = DECL_TI_TEMPLATE (decl);
16735     }
16736
16737   return decl;
16738 }
16739
16740 /* Return the most specialized of the class template partial
16741    specializations of TMPL which can produce TYPE, a specialization of
16742    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
16743    a _TYPE node corresponding to the partial specialization, while the
16744    TREE_PURPOSE is the set of template arguments that must be
16745    substituted into the TREE_TYPE in order to generate TYPE.
16746
16747    If the choice of partial specialization is ambiguous, a diagnostic
16748    is issued, and the error_mark_node is returned.  If there are no
16749    partial specializations of TMPL matching TYPE, then NULL_TREE is
16750    returned.  */
16751
16752 static tree
16753 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
16754 {
16755   tree list = NULL_TREE;
16756   tree t;
16757   tree champ;
16758   int fate;
16759   bool ambiguous_p;
16760   tree args;
16761   tree outer_args = NULL_TREE;
16762
16763   tmpl = most_general_template (tmpl);
16764   args = CLASSTYPE_TI_ARGS (type);
16765
16766   /* For determining which partial specialization to use, only the
16767      innermost args are interesting.  */
16768   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16769     {
16770       outer_args = strip_innermost_template_args (args, 1);
16771       args = INNERMOST_TEMPLATE_ARGS (args);
16772     }
16773
16774   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
16775     {
16776       tree partial_spec_args;
16777       tree spec_args;
16778       tree parms = TREE_VALUE (t);
16779
16780       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
16781
16782       ++processing_template_decl;
16783
16784       if (outer_args)
16785         {
16786           int i;
16787
16788           /* Discard the outer levels of args, and then substitute in the
16789              template args from the enclosing class.  */
16790           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
16791           partial_spec_args = tsubst_template_args
16792             (partial_spec_args, outer_args, tf_none, NULL_TREE);
16793
16794           /* PARMS already refers to just the innermost parms, but the
16795              template parms in partial_spec_args had their levels lowered
16796              by tsubst, so we need to do the same for the parm list.  We
16797              can't just tsubst the TREE_VEC itself, as tsubst wants to
16798              treat a TREE_VEC as an argument vector.  */
16799           parms = copy_node (parms);
16800           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
16801             TREE_VEC_ELT (parms, i) =
16802               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
16803
16804         }
16805
16806       partial_spec_args =
16807           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16808                                  add_to_template_args (outer_args,
16809                                                        partial_spec_args),
16810                                  tmpl, tf_none,
16811                                  /*require_all_args=*/true,
16812                                  /*use_default_args=*/true);
16813
16814       --processing_template_decl;
16815
16816       if (partial_spec_args == error_mark_node)
16817         return error_mark_node;
16818
16819       spec_args = get_class_bindings (parms,
16820                                       partial_spec_args,
16821                                       args);
16822       if (spec_args)
16823         {
16824           if (outer_args)
16825             spec_args = add_to_template_args (outer_args, spec_args);
16826           list = tree_cons (spec_args, TREE_VALUE (t), list);
16827           TREE_TYPE (list) = TREE_TYPE (t);
16828         }
16829     }
16830
16831   if (! list)
16832     return NULL_TREE;
16833
16834   ambiguous_p = false;
16835   t = list;
16836   champ = t;
16837   t = TREE_CHAIN (t);
16838   for (; t; t = TREE_CHAIN (t))
16839     {
16840       fate = more_specialized_class (champ, t);
16841       if (fate == 1)
16842         ;
16843       else
16844         {
16845           if (fate == 0)
16846             {
16847               t = TREE_CHAIN (t);
16848               if (! t)
16849                 {
16850                   ambiguous_p = true;
16851                   break;
16852                 }
16853             }
16854           champ = t;
16855         }
16856     }
16857
16858   if (!ambiguous_p)
16859     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16860       {
16861         fate = more_specialized_class (champ, t);
16862         if (fate != 1)
16863           {
16864             ambiguous_p = true;
16865             break;
16866           }
16867       }
16868
16869   if (ambiguous_p)
16870     {
16871       const char *str;
16872       char *spaces = NULL;
16873       if (!(complain & tf_error))
16874         return error_mark_node;
16875       error ("ambiguous class template instantiation for %q#T", type);
16876       str = ngettext ("candidate is:", "candidates are:", list_length (list));
16877       for (t = list; t; t = TREE_CHAIN (t))
16878         {
16879           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16880           spaces = spaces ? spaces : get_spaces (str);
16881         }
16882       free (spaces);
16883       return error_mark_node;
16884     }
16885
16886   return champ;
16887 }
16888
16889 /* Explicitly instantiate DECL.  */
16890
16891 void
16892 do_decl_instantiation (tree decl, tree storage)
16893 {
16894   tree result = NULL_TREE;
16895   int extern_p = 0;
16896
16897   if (!decl || decl == error_mark_node)
16898     /* An error occurred, for which grokdeclarator has already issued
16899        an appropriate message.  */
16900     return;
16901   else if (! DECL_LANG_SPECIFIC (decl))
16902     {
16903       error ("explicit instantiation of non-template %q#D", decl);
16904       return;
16905     }
16906   else if (TREE_CODE (decl) == VAR_DECL)
16907     {
16908       /* There is an asymmetry here in the way VAR_DECLs and
16909          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16910          the latter, the DECL we get back will be marked as a
16911          template instantiation, and the appropriate
16912          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16913          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16914          should handle VAR_DECLs as it currently handles
16915          FUNCTION_DECLs.  */
16916       if (!DECL_CLASS_SCOPE_P (decl))
16917         {
16918           error ("%qD is not a static data member of a class template", decl);
16919           return;
16920         }
16921       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16922       if (!result || TREE_CODE (result) != VAR_DECL)
16923         {
16924           error ("no matching template for %qD found", decl);
16925           return;
16926         }
16927       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16928         {
16929           error ("type %qT for explicit instantiation %qD does not match "
16930                  "declared type %qT", TREE_TYPE (result), decl,
16931                  TREE_TYPE (decl));
16932           return;
16933         }
16934     }
16935   else if (TREE_CODE (decl) != FUNCTION_DECL)
16936     {
16937       error ("explicit instantiation of %q#D", decl);
16938       return;
16939     }
16940   else
16941     result = decl;
16942
16943   /* Check for various error cases.  Note that if the explicit
16944      instantiation is valid the RESULT will currently be marked as an
16945      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16946      until we get here.  */
16947
16948   if (DECL_TEMPLATE_SPECIALIZATION (result))
16949     {
16950       /* DR 259 [temp.spec].
16951
16952          Both an explicit instantiation and a declaration of an explicit
16953          specialization shall not appear in a program unless the explicit
16954          instantiation follows a declaration of the explicit specialization.
16955
16956          For a given set of template parameters, if an explicit
16957          instantiation of a template appears after a declaration of an
16958          explicit specialization for that template, the explicit
16959          instantiation has no effect.  */
16960       return;
16961     }
16962   else if (DECL_EXPLICIT_INSTANTIATION (result))
16963     {
16964       /* [temp.spec]
16965
16966          No program shall explicitly instantiate any template more
16967          than once.
16968
16969          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16970          the first instantiation was `extern' and the second is not,
16971          and EXTERN_P for the opposite case.  */
16972       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16973         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16974       /* If an "extern" explicit instantiation follows an ordinary
16975          explicit instantiation, the template is instantiated.  */
16976       if (extern_p)
16977         return;
16978     }
16979   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16980     {
16981       error ("no matching template for %qD found", result);
16982       return;
16983     }
16984   else if (!DECL_TEMPLATE_INFO (result))
16985     {
16986       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16987       return;
16988     }
16989
16990   if (storage == NULL_TREE)
16991     ;
16992   else if (storage == ridpointers[(int) RID_EXTERN])
16993     {
16994       if (!in_system_header && (cxx_dialect == cxx98))
16995         pedwarn (input_location, OPT_pedantic, 
16996                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16997                  "instantiations");
16998       extern_p = 1;
16999     }
17000   else
17001     error ("storage class %qD applied to template instantiation", storage);
17002
17003   check_explicit_instantiation_namespace (result);
17004   mark_decl_instantiated (result, extern_p);
17005   if (! extern_p)
17006     instantiate_decl (result, /*defer_ok=*/1,
17007                       /*expl_inst_class_mem_p=*/false);
17008 }
17009
17010 static void
17011 mark_class_instantiated (tree t, int extern_p)
17012 {
17013   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
17014   SET_CLASSTYPE_INTERFACE_KNOWN (t);
17015   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
17016   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
17017   if (! extern_p)
17018     {
17019       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
17020       rest_of_type_compilation (t, 1);
17021     }
17022 }
17023
17024 /* Called from do_type_instantiation through binding_table_foreach to
17025    do recursive instantiation for the type bound in ENTRY.  */
17026 static void
17027 bt_instantiate_type_proc (binding_entry entry, void *data)
17028 {
17029   tree storage = *(tree *) data;
17030
17031   if (MAYBE_CLASS_TYPE_P (entry->type)
17032       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
17033     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
17034 }
17035
17036 /* Called from do_type_instantiation to instantiate a member
17037    (a member function or a static member variable) of an
17038    explicitly instantiated class template.  */
17039 static void
17040 instantiate_class_member (tree decl, int extern_p)
17041 {
17042   mark_decl_instantiated (decl, extern_p);
17043   if (! extern_p)
17044     instantiate_decl (decl, /*defer_ok=*/1,
17045                       /*expl_inst_class_mem_p=*/true);
17046 }
17047
17048 /* Perform an explicit instantiation of template class T.  STORAGE, if
17049    non-null, is the RID for extern, inline or static.  COMPLAIN is
17050    nonzero if this is called from the parser, zero if called recursively,
17051    since the standard is unclear (as detailed below).  */
17052
17053 void
17054 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
17055 {
17056   int extern_p = 0;
17057   int nomem_p = 0;
17058   int static_p = 0;
17059   int previous_instantiation_extern_p = 0;
17060
17061   if (TREE_CODE (t) == TYPE_DECL)
17062     t = TREE_TYPE (t);
17063
17064   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
17065     {
17066       error ("explicit instantiation of non-template type %qT", t);
17067       return;
17068     }
17069
17070   complete_type (t);
17071
17072   if (!COMPLETE_TYPE_P (t))
17073     {
17074       if (complain & tf_error)
17075         error ("explicit instantiation of %q#T before definition of template",
17076                t);
17077       return;
17078     }
17079
17080   if (storage != NULL_TREE)
17081     {
17082       if (!in_system_header)
17083         {
17084           if (storage == ridpointers[(int) RID_EXTERN])
17085             {
17086               if (cxx_dialect == cxx98)
17087                 pedwarn (input_location, OPT_pedantic, 
17088                          "ISO C++ 1998 forbids the use of %<extern%> on "
17089                          "explicit instantiations");
17090             }
17091           else
17092             pedwarn (input_location, OPT_pedantic, 
17093                      "ISO C++ forbids the use of %qE"
17094                      " on explicit instantiations", storage);
17095         }
17096
17097       if (storage == ridpointers[(int) RID_INLINE])
17098         nomem_p = 1;
17099       else if (storage == ridpointers[(int) RID_EXTERN])
17100         extern_p = 1;
17101       else if (storage == ridpointers[(int) RID_STATIC])
17102         static_p = 1;
17103       else
17104         {
17105           error ("storage class %qD applied to template instantiation",
17106                  storage);
17107           extern_p = 0;
17108         }
17109     }
17110
17111   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
17112     {
17113       /* DR 259 [temp.spec].
17114
17115          Both an explicit instantiation and a declaration of an explicit
17116          specialization shall not appear in a program unless the explicit
17117          instantiation follows a declaration of the explicit specialization.
17118
17119          For a given set of template parameters, if an explicit
17120          instantiation of a template appears after a declaration of an
17121          explicit specialization for that template, the explicit
17122          instantiation has no effect.  */
17123       return;
17124     }
17125   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
17126     {
17127       /* [temp.spec]
17128
17129          No program shall explicitly instantiate any template more
17130          than once.
17131
17132          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
17133          instantiation was `extern'.  If EXTERN_P then the second is.
17134          These cases are OK.  */
17135       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
17136
17137       if (!previous_instantiation_extern_p && !extern_p
17138           && (complain & tf_error))
17139         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
17140
17141       /* If we've already instantiated the template, just return now.  */
17142       if (!CLASSTYPE_INTERFACE_ONLY (t))
17143         return;
17144     }
17145
17146   check_explicit_instantiation_namespace (TYPE_NAME (t));
17147   mark_class_instantiated (t, extern_p);
17148
17149   if (nomem_p)
17150     return;
17151
17152   {
17153     tree tmp;
17154
17155     /* In contrast to implicit instantiation, where only the
17156        declarations, and not the definitions, of members are
17157        instantiated, we have here:
17158
17159          [temp.explicit]
17160
17161          The explicit instantiation of a class template specialization
17162          implies the instantiation of all of its members not
17163          previously explicitly specialized in the translation unit
17164          containing the explicit instantiation.
17165
17166        Of course, we can't instantiate member template classes, since
17167        we don't have any arguments for them.  Note that the standard
17168        is unclear on whether the instantiation of the members are
17169        *explicit* instantiations or not.  However, the most natural
17170        interpretation is that it should be an explicit instantiation.  */
17171
17172     if (! static_p)
17173       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
17174         if (TREE_CODE (tmp) == FUNCTION_DECL
17175             && DECL_TEMPLATE_INSTANTIATION (tmp))
17176           instantiate_class_member (tmp, extern_p);
17177
17178     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
17179       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
17180         instantiate_class_member (tmp, extern_p);
17181
17182     if (CLASSTYPE_NESTED_UTDS (t))
17183       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
17184                              bt_instantiate_type_proc, &storage);
17185   }
17186 }
17187
17188 /* Given a function DECL, which is a specialization of TMPL, modify
17189    DECL to be a re-instantiation of TMPL with the same template
17190    arguments.  TMPL should be the template into which tsubst'ing
17191    should occur for DECL, not the most general template.
17192
17193    One reason for doing this is a scenario like this:
17194
17195      template <class T>
17196      void f(const T&, int i);
17197
17198      void g() { f(3, 7); }
17199
17200      template <class T>
17201      void f(const T& t, const int i) { }
17202
17203    Note that when the template is first instantiated, with
17204    instantiate_template, the resulting DECL will have no name for the
17205    first parameter, and the wrong type for the second.  So, when we go
17206    to instantiate the DECL, we regenerate it.  */
17207
17208 static void
17209 regenerate_decl_from_template (tree decl, tree tmpl)
17210 {
17211   /* The arguments used to instantiate DECL, from the most general
17212      template.  */
17213   tree args;
17214   tree code_pattern;
17215
17216   args = DECL_TI_ARGS (decl);
17217   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
17218
17219   /* Make sure that we can see identifiers, and compute access
17220      correctly.  */
17221   push_access_scope (decl);
17222
17223   if (TREE_CODE (decl) == FUNCTION_DECL)
17224     {
17225       tree decl_parm;
17226       tree pattern_parm;
17227       tree specs;
17228       int args_depth;
17229       int parms_depth;
17230
17231       args_depth = TMPL_ARGS_DEPTH (args);
17232       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
17233       if (args_depth > parms_depth)
17234         args = get_innermost_template_args (args, parms_depth);
17235
17236       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
17237                                               args, tf_error, NULL_TREE,
17238                                               /*defer_ok*/false);
17239       if (specs)
17240         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
17241                                                     specs);
17242
17243       /* Merge parameter declarations.  */
17244       decl_parm = skip_artificial_parms_for (decl,
17245                                              DECL_ARGUMENTS (decl));
17246       pattern_parm
17247         = skip_artificial_parms_for (code_pattern,
17248                                      DECL_ARGUMENTS (code_pattern));
17249       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
17250         {
17251           tree parm_type;
17252           tree attributes;
17253           
17254           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17255             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
17256           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
17257                               NULL_TREE);
17258           parm_type = type_decays_to (parm_type);
17259           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17260             TREE_TYPE (decl_parm) = parm_type;
17261           attributes = DECL_ATTRIBUTES (pattern_parm);
17262           if (DECL_ATTRIBUTES (decl_parm) != attributes)
17263             {
17264               DECL_ATTRIBUTES (decl_parm) = attributes;
17265               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17266             }
17267           decl_parm = DECL_CHAIN (decl_parm);
17268           pattern_parm = DECL_CHAIN (pattern_parm);
17269         }
17270       /* Merge any parameters that match with the function parameter
17271          pack.  */
17272       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
17273         {
17274           int i, len;
17275           tree expanded_types;
17276           /* Expand the TYPE_PACK_EXPANSION that provides the types for
17277              the parameters in this function parameter pack.  */
17278           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
17279                                                  args, tf_error, NULL_TREE);
17280           len = TREE_VEC_LENGTH (expanded_types);
17281           for (i = 0; i < len; i++)
17282             {
17283               tree parm_type;
17284               tree attributes;
17285           
17286               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17287                 /* Rename the parameter to include the index.  */
17288                 DECL_NAME (decl_parm) = 
17289                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
17290               parm_type = TREE_VEC_ELT (expanded_types, i);
17291               parm_type = type_decays_to (parm_type);
17292               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17293                 TREE_TYPE (decl_parm) = parm_type;
17294               attributes = DECL_ATTRIBUTES (pattern_parm);
17295               if (DECL_ATTRIBUTES (decl_parm) != attributes)
17296                 {
17297                   DECL_ATTRIBUTES (decl_parm) = attributes;
17298                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17299                 }
17300               decl_parm = DECL_CHAIN (decl_parm);
17301             }
17302         }
17303       /* Merge additional specifiers from the CODE_PATTERN.  */
17304       if (DECL_DECLARED_INLINE_P (code_pattern)
17305           && !DECL_DECLARED_INLINE_P (decl))
17306         DECL_DECLARED_INLINE_P (decl) = 1;
17307     }
17308   else if (TREE_CODE (decl) == VAR_DECL)
17309     {
17310       DECL_INITIAL (decl) =
17311         tsubst_expr (DECL_INITIAL (code_pattern), args,
17312                      tf_error, DECL_TI_TEMPLATE (decl),
17313                      /*integral_constant_expression_p=*/false);
17314       if (VAR_HAD_UNKNOWN_BOUND (decl))
17315         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
17316                                    tf_error, DECL_TI_TEMPLATE (decl));
17317     }
17318   else
17319     gcc_unreachable ();
17320
17321   pop_access_scope (decl);
17322 }
17323
17324 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
17325    substituted to get DECL.  */
17326
17327 tree
17328 template_for_substitution (tree decl)
17329 {
17330   tree tmpl = DECL_TI_TEMPLATE (decl);
17331
17332   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
17333      for the instantiation.  This is not always the most general
17334      template.  Consider, for example:
17335
17336         template <class T>
17337         struct S { template <class U> void f();
17338                    template <> void f<int>(); };
17339
17340      and an instantiation of S<double>::f<int>.  We want TD to be the
17341      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
17342   while (/* An instantiation cannot have a definition, so we need a
17343             more general template.  */
17344          DECL_TEMPLATE_INSTANTIATION (tmpl)
17345            /* We must also deal with friend templates.  Given:
17346
17347                 template <class T> struct S {
17348                   template <class U> friend void f() {};
17349                 };
17350
17351               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
17352               so far as the language is concerned, but that's still
17353               where we get the pattern for the instantiation from.  On
17354               other hand, if the definition comes outside the class, say:
17355
17356                 template <class T> struct S {
17357                   template <class U> friend void f();
17358                 };
17359                 template <class U> friend void f() {}
17360
17361               we don't need to look any further.  That's what the check for
17362               DECL_INITIAL is for.  */
17363           || (TREE_CODE (decl) == FUNCTION_DECL
17364               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
17365               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
17366     {
17367       /* The present template, TD, should not be a definition.  If it
17368          were a definition, we should be using it!  Note that we
17369          cannot restructure the loop to just keep going until we find
17370          a template with a definition, since that might go too far if
17371          a specialization was declared, but not defined.  */
17372       gcc_assert (TREE_CODE (decl) != VAR_DECL
17373                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
17374
17375       /* Fetch the more general template.  */
17376       tmpl = DECL_TI_TEMPLATE (tmpl);
17377     }
17378
17379   return tmpl;
17380 }
17381
17382 /* Returns true if we need to instantiate this template instance even if we
17383    know we aren't going to emit it..  */
17384
17385 bool
17386 always_instantiate_p (tree decl)
17387 {
17388   /* We always instantiate inline functions so that we can inline them.  An
17389      explicit instantiation declaration prohibits implicit instantiation of
17390      non-inline functions.  With high levels of optimization, we would
17391      normally inline non-inline functions -- but we're not allowed to do
17392      that for "extern template" functions.  Therefore, we check
17393      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17394   return ((TREE_CODE (decl) == FUNCTION_DECL
17395            && DECL_DECLARED_INLINE_P (decl))
17396           /* And we need to instantiate static data members so that
17397              their initializers are available in integral constant
17398              expressions.  */
17399           || (TREE_CODE (decl) == VAR_DECL
17400               && decl_maybe_constant_var_p (decl)));
17401 }
17402
17403 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
17404    instantiate it now, modifying TREE_TYPE (fn).  */
17405
17406 void
17407 maybe_instantiate_noexcept (tree fn)
17408 {
17409   tree fntype, spec, noex, clone;
17410
17411   if (DECL_CLONED_FUNCTION_P (fn))
17412     fn = DECL_CLONED_FUNCTION (fn);
17413   fntype = TREE_TYPE (fn);
17414   spec = TYPE_RAISES_EXCEPTIONS (fntype);
17415
17416   if (!DEFERRED_NOEXCEPT_SPEC_P (spec))
17417     return;
17418
17419   noex = TREE_PURPOSE (spec);
17420
17421   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
17422     {
17423       push_tinst_level (fn);
17424       push_access_scope (fn);
17425       input_location = DECL_SOURCE_LOCATION (fn);
17426       noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
17427                                     DEFERRED_NOEXCEPT_ARGS (noex),
17428                                     tf_warning_or_error, fn, /*function_p=*/false,
17429                                     /*integral_constant_expression_p=*/true);
17430       pop_access_scope (fn);
17431       pop_tinst_level ();
17432       spec = build_noexcept_spec (noex, tf_warning_or_error);
17433       if (spec == error_mark_node)
17434         spec = noexcept_false_spec;
17435     }
17436   else
17437     {
17438       /* This is an implicitly declared function, so NOEX is a list of
17439          other functions to evaluate and merge.  */
17440       tree elt;
17441       spec = noexcept_true_spec;
17442       for (elt = noex; elt; elt = OVL_NEXT (elt))
17443         {
17444           tree fn = OVL_CURRENT (elt);
17445           tree subspec;
17446           maybe_instantiate_noexcept (fn);
17447           subspec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn));
17448           spec = merge_exception_specifiers (spec, subspec, NULL_TREE);
17449         }
17450     }
17451
17452   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
17453
17454   FOR_EACH_CLONE (clone, fn)
17455     {
17456       if (TREE_TYPE (clone) == fntype)
17457         TREE_TYPE (clone) = TREE_TYPE (fn);
17458       else
17459         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
17460     }
17461 }
17462
17463 /* Produce the definition of D, a _DECL generated from a template.  If
17464    DEFER_OK is nonzero, then we don't have to actually do the
17465    instantiation now; we just have to do it sometime.  Normally it is
17466    an error if this is an explicit instantiation but D is undefined.
17467    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
17468    explicitly instantiated class template.  */
17469
17470 tree
17471 instantiate_decl (tree d, int defer_ok,
17472                   bool expl_inst_class_mem_p)
17473 {
17474   tree tmpl = DECL_TI_TEMPLATE (d);
17475   tree gen_args;
17476   tree args;
17477   tree td;
17478   tree code_pattern;
17479   tree spec;
17480   tree gen_tmpl;
17481   bool pattern_defined;
17482   int need_push;
17483   location_t saved_loc = input_location;
17484   bool external_p;
17485
17486   /* This function should only be used to instantiate templates for
17487      functions and static member variables.  */
17488   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
17489               || TREE_CODE (d) == VAR_DECL);
17490
17491   /* Variables are never deferred; if instantiation is required, they
17492      are instantiated right away.  That allows for better code in the
17493      case that an expression refers to the value of the variable --
17494      if the variable has a constant value the referring expression can
17495      take advantage of that fact.  */
17496   if (TREE_CODE (d) == VAR_DECL
17497       || DECL_DECLARED_CONSTEXPR_P (d))
17498     defer_ok = 0;
17499
17500   /* Don't instantiate cloned functions.  Instead, instantiate the
17501      functions they cloned.  */
17502   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
17503     d = DECL_CLONED_FUNCTION (d);
17504
17505   if (DECL_TEMPLATE_INSTANTIATED (d)
17506       || DECL_TEMPLATE_SPECIALIZATION (d))
17507     /* D has already been instantiated or explicitly specialized, so
17508        there's nothing for us to do here.
17509
17510        It might seem reasonable to check whether or not D is an explicit
17511        instantiation, and, if so, stop here.  But when an explicit
17512        instantiation is deferred until the end of the compilation,
17513        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
17514        the instantiation.  */
17515     return d;
17516
17517   /* Check to see whether we know that this template will be
17518      instantiated in some other file, as with "extern template"
17519      extension.  */
17520   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
17521
17522   /* In general, we do not instantiate such templates.  */
17523   if (external_p && !always_instantiate_p (d))
17524     return d;
17525
17526   gen_tmpl = most_general_template (tmpl);
17527   gen_args = DECL_TI_ARGS (d);
17528
17529   if (tmpl != gen_tmpl)
17530     /* We should already have the extra args.  */
17531     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
17532                 == TMPL_ARGS_DEPTH (gen_args));
17533   /* And what's in the hash table should match D.  */
17534   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
17535               || spec == NULL_TREE);
17536
17537   /* This needs to happen before any tsubsting.  */
17538   if (! push_tinst_level (d))
17539     return d;
17540
17541   timevar_push (TV_TEMPLATE_INST);
17542
17543   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
17544      for the instantiation.  */
17545   td = template_for_substitution (d);
17546   code_pattern = DECL_TEMPLATE_RESULT (td);
17547
17548   /* We should never be trying to instantiate a member of a class
17549      template or partial specialization.  */
17550   gcc_assert (d != code_pattern);
17551
17552   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
17553       || DECL_TEMPLATE_SPECIALIZATION (td))
17554     /* In the case of a friend template whose definition is provided
17555        outside the class, we may have too many arguments.  Drop the
17556        ones we don't need.  The same is true for specializations.  */
17557     args = get_innermost_template_args
17558       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
17559   else
17560     args = gen_args;
17561
17562   if (TREE_CODE (d) == FUNCTION_DECL)
17563     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
17564                        || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
17565   else
17566     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
17567
17568   /* We may be in the middle of deferred access check.  Disable it now.  */
17569   push_deferring_access_checks (dk_no_deferred);
17570
17571   /* Unless an explicit instantiation directive has already determined
17572      the linkage of D, remember that a definition is available for
17573      this entity.  */
17574   if (pattern_defined
17575       && !DECL_INTERFACE_KNOWN (d)
17576       && !DECL_NOT_REALLY_EXTERN (d))
17577     mark_definable (d);
17578
17579   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
17580   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
17581   input_location = DECL_SOURCE_LOCATION (d);
17582
17583   /* If D is a member of an explicitly instantiated class template,
17584      and no definition is available, treat it like an implicit
17585      instantiation.  */
17586   if (!pattern_defined && expl_inst_class_mem_p
17587       && DECL_EXPLICIT_INSTANTIATION (d))
17588     {
17589       /* Leave linkage flags alone on instantiations with anonymous
17590          visibility.  */
17591       if (TREE_PUBLIC (d))
17592         {
17593           DECL_NOT_REALLY_EXTERN (d) = 0;
17594           DECL_INTERFACE_KNOWN (d) = 0;
17595         }
17596       SET_DECL_IMPLICIT_INSTANTIATION (d);
17597     }
17598
17599   if (TREE_CODE (d) == FUNCTION_DECL)
17600     maybe_instantiate_noexcept (d);
17601
17602   /* Recheck the substitutions to obtain any warning messages
17603      about ignoring cv qualifiers.  Don't do this for artificial decls,
17604      as it breaks the context-sensitive substitution for lambda op(). */
17605   if (!defer_ok && !DECL_ARTIFICIAL (d))
17606     {
17607       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
17608       tree type = TREE_TYPE (gen);
17609
17610       /* Make sure that we can see identifiers, and compute access
17611          correctly.  D is already the target FUNCTION_DECL with the
17612          right context.  */
17613       push_access_scope (d);
17614
17615       if (TREE_CODE (gen) == FUNCTION_DECL)
17616         {
17617           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
17618           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
17619                                           d, /*defer_ok*/true);
17620           /* Don't simply tsubst the function type, as that will give
17621              duplicate warnings about poor parameter qualifications.
17622              The function arguments are the same as the decl_arguments
17623              without the top level cv qualifiers.  */
17624           type = TREE_TYPE (type);
17625         }
17626       tsubst (type, gen_args, tf_warning_or_error, d);
17627
17628       pop_access_scope (d);
17629     }
17630
17631   /* Defer all other templates, unless we have been explicitly
17632      forbidden from doing so.  */
17633   if (/* If there is no definition, we cannot instantiate the
17634          template.  */
17635       ! pattern_defined
17636       /* If it's OK to postpone instantiation, do so.  */
17637       || defer_ok
17638       /* If this is a static data member that will be defined
17639          elsewhere, we don't want to instantiate the entire data
17640          member, but we do want to instantiate the initializer so that
17641          we can substitute that elsewhere.  */
17642       || (external_p && TREE_CODE (d) == VAR_DECL))
17643     {
17644       /* The definition of the static data member is now required so
17645          we must substitute the initializer.  */
17646       if (TREE_CODE (d) == VAR_DECL
17647           && !DECL_INITIAL (d)
17648           && DECL_INITIAL (code_pattern))
17649         {
17650           tree ns;
17651           tree init;
17652           bool const_init = false;
17653
17654           ns = decl_namespace_context (d);
17655           push_nested_namespace (ns);
17656           push_nested_class (DECL_CONTEXT (d));
17657           init = tsubst_expr (DECL_INITIAL (code_pattern),
17658                               args,
17659                               tf_warning_or_error, NULL_TREE,
17660                               /*integral_constant_expression_p=*/false);
17661           /* Make sure the initializer is still constant, in case of
17662              circular dependency (template/instantiate6.C). */
17663           const_init
17664             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17665           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
17666                           /*asmspec_tree=*/NULL_TREE,
17667                           LOOKUP_ONLYCONVERTING);
17668           pop_nested_class ();
17669           pop_nested_namespace (ns);
17670         }
17671
17672       /* We restore the source position here because it's used by
17673          add_pending_template.  */
17674       input_location = saved_loc;
17675
17676       if (at_eof && !pattern_defined
17677           && DECL_EXPLICIT_INSTANTIATION (d)
17678           && DECL_NOT_REALLY_EXTERN (d))
17679         /* [temp.explicit]
17680
17681            The definition of a non-exported function template, a
17682            non-exported member function template, or a non-exported
17683            member function or static data member of a class template
17684            shall be present in every translation unit in which it is
17685            explicitly instantiated.  */
17686         permerror (input_location,  "explicit instantiation of %qD "
17687                    "but no definition available", d);
17688
17689       /* If we're in unevaluated context, we just wanted to get the
17690          constant value; this isn't an odr use, so don't queue
17691          a full instantiation.  */
17692       if (cp_unevaluated_operand != 0)
17693         goto out;
17694       /* ??? Historically, we have instantiated inline functions, even
17695          when marked as "extern template".  */
17696       if (!(external_p && TREE_CODE (d) == VAR_DECL))
17697         add_pending_template (d);
17698       goto out;
17699     }
17700   /* Tell the repository that D is available in this translation unit
17701      -- and see if it is supposed to be instantiated here.  */
17702   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
17703     {
17704       /* In a PCH file, despite the fact that the repository hasn't
17705          requested instantiation in the PCH it is still possible that
17706          an instantiation will be required in a file that includes the
17707          PCH.  */
17708       if (pch_file)
17709         add_pending_template (d);
17710       /* Instantiate inline functions so that the inliner can do its
17711          job, even though we'll not be emitting a copy of this
17712          function.  */
17713       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
17714         goto out;
17715     }
17716
17717   need_push = !cfun || !global_bindings_p ();
17718   if (need_push)
17719     push_to_top_level ();
17720
17721   /* Mark D as instantiated so that recursive calls to
17722      instantiate_decl do not try to instantiate it again.  */
17723   DECL_TEMPLATE_INSTANTIATED (d) = 1;
17724
17725   /* Regenerate the declaration in case the template has been modified
17726      by a subsequent redeclaration.  */
17727   regenerate_decl_from_template (d, td);
17728
17729   /* We already set the file and line above.  Reset them now in case
17730      they changed as a result of calling regenerate_decl_from_template.  */
17731   input_location = DECL_SOURCE_LOCATION (d);
17732
17733   if (TREE_CODE (d) == VAR_DECL)
17734     {
17735       tree init;
17736       bool const_init = false;
17737
17738       /* Clear out DECL_RTL; whatever was there before may not be right
17739          since we've reset the type of the declaration.  */
17740       SET_DECL_RTL (d, NULL);
17741       DECL_IN_AGGR_P (d) = 0;
17742
17743       /* The initializer is placed in DECL_INITIAL by
17744          regenerate_decl_from_template so we don't need to
17745          push/pop_access_scope again here.  Pull it out so that
17746          cp_finish_decl can process it.  */
17747       init = DECL_INITIAL (d);
17748       DECL_INITIAL (d) = NULL_TREE;
17749       DECL_INITIALIZED_P (d) = 0;
17750
17751       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
17752          initializer.  That function will defer actual emission until
17753          we have a chance to determine linkage.  */
17754       DECL_EXTERNAL (d) = 0;
17755
17756       /* Enter the scope of D so that access-checking works correctly.  */
17757       push_nested_class (DECL_CONTEXT (d));
17758       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17759       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
17760       pop_nested_class ();
17761     }
17762   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
17763     synthesize_method (d);
17764   else if (TREE_CODE (d) == FUNCTION_DECL)
17765     {
17766       htab_t saved_local_specializations;
17767       tree subst_decl;
17768       tree tmpl_parm;
17769       tree spec_parm;
17770
17771       /* Save away the current list, in case we are instantiating one
17772          template from within the body of another.  */
17773       saved_local_specializations = local_specializations;
17774
17775       /* Set up the list of local specializations.  */
17776       local_specializations = htab_create (37,
17777                                            hash_local_specialization,
17778                                            eq_local_specializations,
17779                                            NULL);
17780
17781       /* Set up context.  */
17782       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
17783
17784       /* Create substitution entries for the parameters.  */
17785       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
17786       tmpl_parm = DECL_ARGUMENTS (subst_decl);
17787       spec_parm = DECL_ARGUMENTS (d);
17788       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
17789         {
17790           register_local_specialization (spec_parm, tmpl_parm);
17791           spec_parm = skip_artificial_parms_for (d, spec_parm);
17792           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
17793         }
17794       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17795         {
17796           register_local_specialization (spec_parm, tmpl_parm);
17797           tmpl_parm = DECL_CHAIN (tmpl_parm);
17798           spec_parm = DECL_CHAIN (spec_parm);
17799         }
17800       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17801         {
17802           /* Register the (value) argument pack as a specialization of
17803              TMPL_PARM, then move on.  */
17804           tree argpack = make_fnparm_pack (spec_parm);
17805           register_local_specialization (argpack, tmpl_parm);
17806           tmpl_parm = DECL_CHAIN (tmpl_parm);
17807           spec_parm = NULL_TREE;
17808         }
17809       gcc_assert (!spec_parm);
17810
17811       /* Substitute into the body of the function.  */
17812       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
17813                    tf_warning_or_error, tmpl,
17814                    /*integral_constant_expression_p=*/false);
17815
17816       /* Set the current input_location to the end of the function
17817          so that finish_function knows where we are.  */
17818       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
17819
17820       /* We don't need the local specializations any more.  */
17821       htab_delete (local_specializations);
17822       local_specializations = saved_local_specializations;
17823
17824       /* Finish the function.  */
17825       d = finish_function (0);
17826       expand_or_defer_fn (d);
17827     }
17828
17829   /* We're not deferring instantiation any more.  */
17830   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
17831
17832   if (need_push)
17833     pop_from_top_level ();
17834
17835 out:
17836   input_location = saved_loc;
17837   pop_deferring_access_checks ();
17838   pop_tinst_level ();
17839
17840   timevar_pop (TV_TEMPLATE_INST);
17841
17842   return d;
17843 }
17844
17845 /* Run through the list of templates that we wish we could
17846    instantiate, and instantiate any we can.  RETRIES is the
17847    number of times we retry pending template instantiation.  */
17848
17849 void
17850 instantiate_pending_templates (int retries)
17851 {
17852   int reconsider;
17853   location_t saved_loc = input_location;
17854
17855   /* Instantiating templates may trigger vtable generation.  This in turn
17856      may require further template instantiations.  We place a limit here
17857      to avoid infinite loop.  */
17858   if (pending_templates && retries >= max_tinst_depth)
17859     {
17860       tree decl = pending_templates->tinst->decl;
17861
17862       error ("template instantiation depth exceeds maximum of %d"
17863              " instantiating %q+D, possibly from virtual table generation"
17864              " (use -ftemplate-depth= to increase the maximum)",
17865              max_tinst_depth, decl);
17866       if (TREE_CODE (decl) == FUNCTION_DECL)
17867         /* Pretend that we defined it.  */
17868         DECL_INITIAL (decl) = error_mark_node;
17869       return;
17870     }
17871
17872   do
17873     {
17874       struct pending_template **t = &pending_templates;
17875       struct pending_template *last = NULL;
17876       reconsider = 0;
17877       while (*t)
17878         {
17879           tree instantiation = reopen_tinst_level ((*t)->tinst);
17880           bool complete = false;
17881
17882           if (TYPE_P (instantiation))
17883             {
17884               tree fn;
17885
17886               if (!COMPLETE_TYPE_P (instantiation))
17887                 {
17888                   instantiate_class_template (instantiation);
17889                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
17890                     for (fn = TYPE_METHODS (instantiation);
17891                          fn;
17892                          fn = TREE_CHAIN (fn))
17893                       if (! DECL_ARTIFICIAL (fn))
17894                         instantiate_decl (fn,
17895                                           /*defer_ok=*/0,
17896                                           /*expl_inst_class_mem_p=*/false);
17897                   if (COMPLETE_TYPE_P (instantiation))
17898                     reconsider = 1;
17899                 }
17900
17901               complete = COMPLETE_TYPE_P (instantiation);
17902             }
17903           else
17904             {
17905               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
17906                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
17907                 {
17908                   instantiation
17909                     = instantiate_decl (instantiation,
17910                                         /*defer_ok=*/0,
17911                                         /*expl_inst_class_mem_p=*/false);
17912                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
17913                     reconsider = 1;
17914                 }
17915
17916               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
17917                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
17918             }
17919
17920           if (complete)
17921             /* If INSTANTIATION has been instantiated, then we don't
17922                need to consider it again in the future.  */
17923             *t = (*t)->next;
17924           else
17925             {
17926               last = *t;
17927               t = &(*t)->next;
17928             }
17929           tinst_depth = 0;
17930           current_tinst_level = NULL;
17931         }
17932       last_pending_template = last;
17933     }
17934   while (reconsider);
17935
17936   input_location = saved_loc;
17937 }
17938
17939 /* Substitute ARGVEC into T, which is a list of initializers for
17940    either base class or a non-static data member.  The TREE_PURPOSEs
17941    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17942    instantiate_decl.  */
17943
17944 static tree
17945 tsubst_initializer_list (tree t, tree argvec)
17946 {
17947   tree inits = NULL_TREE;
17948
17949   for (; t; t = TREE_CHAIN (t))
17950     {
17951       tree decl;
17952       tree init;
17953       tree expanded_bases = NULL_TREE;
17954       tree expanded_arguments = NULL_TREE;
17955       int i, len = 1;
17956
17957       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17958         {
17959           tree expr;
17960           tree arg;
17961
17962           /* Expand the base class expansion type into separate base
17963              classes.  */
17964           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17965                                                  tf_warning_or_error,
17966                                                  NULL_TREE);
17967           if (expanded_bases == error_mark_node)
17968             continue;
17969           
17970           /* We'll be building separate TREE_LISTs of arguments for
17971              each base.  */
17972           len = TREE_VEC_LENGTH (expanded_bases);
17973           expanded_arguments = make_tree_vec (len);
17974           for (i = 0; i < len; i++)
17975             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17976
17977           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17978              expand each argument in the TREE_VALUE of t.  */
17979           expr = make_node (EXPR_PACK_EXPANSION);
17980           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17981             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17982
17983           if (TREE_VALUE (t) == void_type_node)
17984             /* VOID_TYPE_NODE is used to indicate
17985                value-initialization.  */
17986             {
17987               for (i = 0; i < len; i++)
17988                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17989             }
17990           else
17991             {
17992               /* Substitute parameter packs into each argument in the
17993                  TREE_LIST.  */
17994               in_base_initializer = 1;
17995               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17996                 {
17997                   tree expanded_exprs;
17998
17999                   /* Expand the argument.  */
18000                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
18001                   expanded_exprs 
18002                     = tsubst_pack_expansion (expr, argvec,
18003                                              tf_warning_or_error,
18004                                              NULL_TREE);
18005                   if (expanded_exprs == error_mark_node)
18006                     continue;
18007
18008                   /* Prepend each of the expanded expressions to the
18009                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
18010                   for (i = 0; i < len; i++)
18011                     {
18012                       TREE_VEC_ELT (expanded_arguments, i) = 
18013                         tree_cons (NULL_TREE, 
18014                                    TREE_VEC_ELT (expanded_exprs, i),
18015                                    TREE_VEC_ELT (expanded_arguments, i));
18016                     }
18017                 }
18018               in_base_initializer = 0;
18019
18020               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
18021                  since we built them backwards.  */
18022               for (i = 0; i < len; i++)
18023                 {
18024                   TREE_VEC_ELT (expanded_arguments, i) = 
18025                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
18026                 }
18027             }
18028         }
18029
18030       for (i = 0; i < len; ++i)
18031         {
18032           if (expanded_bases)
18033             {
18034               decl = TREE_VEC_ELT (expanded_bases, i);
18035               decl = expand_member_init (decl);
18036               init = TREE_VEC_ELT (expanded_arguments, i);
18037             }
18038           else
18039             {
18040               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
18041                                   tf_warning_or_error, NULL_TREE);
18042
18043               decl = expand_member_init (decl);
18044               if (decl && !DECL_P (decl))
18045                 in_base_initializer = 1;
18046
18047               init = TREE_VALUE (t);
18048               if (init != void_type_node)
18049                 init = tsubst_expr (init, argvec,
18050                                     tf_warning_or_error, NULL_TREE,
18051                                     /*integral_constant_expression_p=*/false);
18052               in_base_initializer = 0;
18053             }
18054
18055           if (decl)
18056             {
18057               init = build_tree_list (decl, init);
18058               TREE_CHAIN (init) = inits;
18059               inits = init;
18060             }
18061         }
18062     }
18063   return inits;
18064 }
18065
18066 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
18067
18068 static void
18069 set_current_access_from_decl (tree decl)
18070 {
18071   if (TREE_PRIVATE (decl))
18072     current_access_specifier = access_private_node;
18073   else if (TREE_PROTECTED (decl))
18074     current_access_specifier = access_protected_node;
18075   else
18076     current_access_specifier = access_public_node;
18077 }
18078
18079 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
18080    is the instantiation (which should have been created with
18081    start_enum) and ARGS are the template arguments to use.  */
18082
18083 static void
18084 tsubst_enum (tree tag, tree newtag, tree args)
18085 {
18086   tree e;
18087
18088   if (SCOPED_ENUM_P (newtag))
18089     begin_scope (sk_scoped_enum, newtag);
18090
18091   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
18092     {
18093       tree value;
18094       tree decl;
18095
18096       decl = TREE_VALUE (e);
18097       /* Note that in a template enum, the TREE_VALUE is the
18098          CONST_DECL, not the corresponding INTEGER_CST.  */
18099       value = tsubst_expr (DECL_INITIAL (decl),
18100                            args, tf_warning_or_error, NULL_TREE,
18101                            /*integral_constant_expression_p=*/true);
18102
18103       /* Give this enumeration constant the correct access.  */
18104       set_current_access_from_decl (decl);
18105
18106       /* Actually build the enumerator itself.  */
18107       build_enumerator
18108         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
18109     }
18110
18111   if (SCOPED_ENUM_P (newtag))
18112     finish_scope ();
18113
18114   finish_enum_value_list (newtag);
18115   finish_enum (newtag);
18116
18117   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
18118     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
18119 }
18120
18121 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
18122    its type -- but without substituting the innermost set of template
18123    arguments.  So, innermost set of template parameters will appear in
18124    the type.  */
18125
18126 tree
18127 get_mostly_instantiated_function_type (tree decl)
18128 {
18129   tree fn_type;
18130   tree tmpl;
18131   tree targs;
18132   tree tparms;
18133   int parm_depth;
18134
18135   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
18136   targs = DECL_TI_ARGS (decl);
18137   tparms = DECL_TEMPLATE_PARMS (tmpl);
18138   parm_depth = TMPL_PARMS_DEPTH (tparms);
18139
18140   /* There should be as many levels of arguments as there are levels
18141      of parameters.  */
18142   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
18143
18144   fn_type = TREE_TYPE (tmpl);
18145
18146   if (parm_depth == 1)
18147     /* No substitution is necessary.  */
18148     ;
18149   else
18150     {
18151       int i;
18152       tree partial_args;
18153
18154       /* Replace the innermost level of the TARGS with NULL_TREEs to
18155          let tsubst know not to substitute for those parameters.  */
18156       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
18157       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
18158         SET_TMPL_ARGS_LEVEL (partial_args, i,
18159                              TMPL_ARGS_LEVEL (targs, i));
18160       SET_TMPL_ARGS_LEVEL (partial_args,
18161                            TMPL_ARGS_DEPTH (targs),
18162                            make_tree_vec (DECL_NTPARMS (tmpl)));
18163
18164       /* Make sure that we can see identifiers, and compute access
18165          correctly.  */
18166       push_access_scope (decl);
18167
18168       ++processing_template_decl;
18169       /* Now, do the (partial) substitution to figure out the
18170          appropriate function type.  */
18171       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
18172       --processing_template_decl;
18173
18174       /* Substitute into the template parameters to obtain the real
18175          innermost set of parameters.  This step is important if the
18176          innermost set of template parameters contains value
18177          parameters whose types depend on outer template parameters.  */
18178       TREE_VEC_LENGTH (partial_args)--;
18179       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
18180
18181       pop_access_scope (decl);
18182     }
18183
18184   return fn_type;
18185 }
18186
18187 /* Return truthvalue if we're processing a template different from
18188    the last one involved in diagnostics.  */
18189 int
18190 problematic_instantiation_changed (void)
18191 {
18192   return last_template_error_tick != tinst_level_tick;
18193 }
18194
18195 /* Remember current template involved in diagnostics.  */
18196 void
18197 record_last_problematic_instantiation (void)
18198 {
18199   last_template_error_tick = tinst_level_tick;
18200 }
18201
18202 struct tinst_level *
18203 current_instantiation (void)
18204 {
18205   return current_tinst_level;
18206 }
18207
18208 /* [temp.param] Check that template non-type parm TYPE is of an allowable
18209    type. Return zero for ok, nonzero for disallowed. Issue error and
18210    warning messages under control of COMPLAIN.  */
18211
18212 static int
18213 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
18214 {
18215   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
18216     return 0;
18217   else if (POINTER_TYPE_P (type))
18218     return 0;
18219   else if (TYPE_PTR_TO_MEMBER_P (type))
18220     return 0;
18221   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
18222     return 0;
18223   else if (TREE_CODE (type) == TYPENAME_TYPE)
18224     return 0;
18225   else if (TREE_CODE (type) == DECLTYPE_TYPE)
18226     return 0;
18227
18228   if (complain & tf_error)
18229     error ("%q#T is not a valid type for a template constant parameter", type);
18230   return 1;
18231 }
18232
18233 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
18234    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
18235
18236 static bool
18237 dependent_type_p_r (tree type)
18238 {
18239   tree scope;
18240
18241   /* [temp.dep.type]
18242
18243      A type is dependent if it is:
18244
18245      -- a template parameter. Template template parameters are types
18246         for us (since TYPE_P holds true for them) so we handle
18247         them here.  */
18248   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18249       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
18250     return true;
18251   /* -- a qualified-id with a nested-name-specifier which contains a
18252         class-name that names a dependent type or whose unqualified-id
18253         names a dependent type.  */
18254   if (TREE_CODE (type) == TYPENAME_TYPE)
18255     return true;
18256   /* -- a cv-qualified type where the cv-unqualified type is
18257         dependent.  */
18258   type = TYPE_MAIN_VARIANT (type);
18259   /* -- a compound type constructed from any dependent type.  */
18260   if (TYPE_PTR_TO_MEMBER_P (type))
18261     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
18262             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
18263                                            (type)));
18264   else if (TREE_CODE (type) == POINTER_TYPE
18265            || TREE_CODE (type) == REFERENCE_TYPE)
18266     return dependent_type_p (TREE_TYPE (type));
18267   else if (TREE_CODE (type) == FUNCTION_TYPE
18268            || TREE_CODE (type) == METHOD_TYPE)
18269     {
18270       tree arg_type;
18271
18272       if (dependent_type_p (TREE_TYPE (type)))
18273         return true;
18274       for (arg_type = TYPE_ARG_TYPES (type);
18275            arg_type;
18276            arg_type = TREE_CHAIN (arg_type))
18277         if (dependent_type_p (TREE_VALUE (arg_type)))
18278           return true;
18279       return false;
18280     }
18281   /* -- an array type constructed from any dependent type or whose
18282         size is specified by a constant expression that is
18283         value-dependent.
18284
18285         We checked for type- and value-dependence of the bounds in
18286         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
18287   if (TREE_CODE (type) == ARRAY_TYPE)
18288     {
18289       if (TYPE_DOMAIN (type)
18290           && dependent_type_p (TYPE_DOMAIN (type)))
18291         return true;
18292       return dependent_type_p (TREE_TYPE (type));
18293     }
18294
18295   /* -- a template-id in which either the template name is a template
18296      parameter ...  */
18297   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
18298     return true;
18299   /* ... or any of the template arguments is a dependent type or
18300         an expression that is type-dependent or value-dependent.  */
18301   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
18302            && (any_dependent_template_arguments_p
18303                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
18304     return true;
18305
18306   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
18307      dependent; if the argument of the `typeof' expression is not
18308      type-dependent, then it should already been have resolved.  */
18309   if (TREE_CODE (type) == TYPEOF_TYPE
18310       || TREE_CODE (type) == DECLTYPE_TYPE
18311       || TREE_CODE (type) == UNDERLYING_TYPE)
18312     return true;
18313
18314   /* A template argument pack is dependent if any of its packed
18315      arguments are.  */
18316   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
18317     {
18318       tree args = ARGUMENT_PACK_ARGS (type);
18319       int i, len = TREE_VEC_LENGTH (args);
18320       for (i = 0; i < len; ++i)
18321         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18322           return true;
18323     }
18324
18325   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
18326      be template parameters.  */
18327   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
18328     return true;
18329
18330   /* The standard does not specifically mention types that are local
18331      to template functions or local classes, but they should be
18332      considered dependent too.  For example:
18333
18334        template <int I> void f() {
18335          enum E { a = I };
18336          S<sizeof (E)> s;
18337        }
18338
18339      The size of `E' cannot be known until the value of `I' has been
18340      determined.  Therefore, `E' must be considered dependent.  */
18341   scope = TYPE_CONTEXT (type);
18342   if (scope && TYPE_P (scope))
18343     return dependent_type_p (scope);
18344   /* Don't use type_dependent_expression_p here, as it can lead
18345      to infinite recursion trying to determine whether a lambda
18346      nested in a lambda is dependent (c++/47687).  */
18347   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
18348            && DECL_LANG_SPECIFIC (scope)
18349            && DECL_TEMPLATE_INFO (scope)
18350            && (any_dependent_template_arguments_p
18351                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
18352     return true;
18353
18354   /* Other types are non-dependent.  */
18355   return false;
18356 }
18357
18358 /* Returns TRUE if TYPE is dependent, in the sense of
18359    [temp.dep.type].  Note that a NULL type is considered dependent.  */
18360
18361 bool
18362 dependent_type_p (tree type)
18363 {
18364   /* If there are no template parameters in scope, then there can't be
18365      any dependent types.  */
18366   if (!processing_template_decl)
18367     {
18368       /* If we are not processing a template, then nobody should be
18369          providing us with a dependent type.  */
18370       gcc_assert (type);
18371       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
18372       return false;
18373     }
18374
18375   /* If the type is NULL, we have not computed a type for the entity
18376      in question; in that case, the type is dependent.  */
18377   if (!type)
18378     return true;
18379
18380   /* Erroneous types can be considered non-dependent.  */
18381   if (type == error_mark_node)
18382     return false;
18383
18384   /* If we have not already computed the appropriate value for TYPE,
18385      do so now.  */
18386   if (!TYPE_DEPENDENT_P_VALID (type))
18387     {
18388       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
18389       TYPE_DEPENDENT_P_VALID (type) = 1;
18390     }
18391
18392   return TYPE_DEPENDENT_P (type);
18393 }
18394
18395 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
18396    lookup.  In other words, a dependent type that is not the current
18397    instantiation.  */
18398
18399 bool
18400 dependent_scope_p (tree scope)
18401 {
18402   return (scope && TYPE_P (scope) && dependent_type_p (scope)
18403           && !currently_open_class (scope));
18404 }
18405
18406 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
18407    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
18408    expression.  */
18409
18410 /* Note that this predicate is not appropriate for general expressions;
18411    only constant expressions (that satisfy potential_constant_expression)
18412    can be tested for value dependence.
18413
18414    We should really also have a predicate for "instantiation-dependent".
18415
18416    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
18417      (what about instantiation-dependent constant-expressions?)
18418    is_late_template_attribute: defer if instantiation-dependent.
18419    compute_array_index_type: proceed if constant and not t- or v-dependent
18420      if instantiation-dependent, need to remember full expression
18421    uses_template_parms: FIXME - need to audit callers
18422    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
18423    dependent_type_p [array_type]: dependent if index type is dependent
18424      (or non-constant?)
18425    static_assert - instantiation-dependent */
18426
18427 bool
18428 value_dependent_expression_p (tree expression)
18429 {
18430   if (!processing_template_decl)
18431     return false;
18432
18433   /* A name declared with a dependent type.  */
18434   if (DECL_P (expression) && type_dependent_expression_p (expression))
18435     return true;
18436
18437   switch (TREE_CODE (expression))
18438     {
18439     case IDENTIFIER_NODE:
18440       /* A name that has not been looked up -- must be dependent.  */
18441       return true;
18442
18443     case TEMPLATE_PARM_INDEX:
18444       /* A non-type template parm.  */
18445       return true;
18446
18447     case CONST_DECL:
18448       /* A non-type template parm.  */
18449       if (DECL_TEMPLATE_PARM_P (expression))
18450         return true;
18451       return value_dependent_expression_p (DECL_INITIAL (expression));
18452
18453     case VAR_DECL:
18454        /* A constant with literal type and is initialized
18455           with an expression that is value-dependent.  */
18456       if (DECL_INITIAL (expression)
18457           && decl_constant_var_p (expression)
18458           && value_dependent_expression_p (DECL_INITIAL (expression)))
18459         return true;
18460       return false;
18461
18462     case DYNAMIC_CAST_EXPR:
18463     case STATIC_CAST_EXPR:
18464     case CONST_CAST_EXPR:
18465     case REINTERPRET_CAST_EXPR:
18466     case CAST_EXPR:
18467       /* These expressions are value-dependent if the type to which
18468          the cast occurs is dependent or the expression being casted
18469          is value-dependent.  */
18470       {
18471         tree type = TREE_TYPE (expression);
18472
18473         if (dependent_type_p (type))
18474           return true;
18475
18476         /* A functional cast has a list of operands.  */
18477         expression = TREE_OPERAND (expression, 0);
18478         if (!expression)
18479           {
18480             /* If there are no operands, it must be an expression such
18481                as "int()". This should not happen for aggregate types
18482                because it would form non-constant expressions.  */
18483             gcc_assert (cxx_dialect >= cxx0x
18484                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
18485
18486             return false;
18487           }
18488
18489         if (TREE_CODE (expression) == TREE_LIST)
18490           return any_value_dependent_elements_p (expression);
18491
18492         return value_dependent_expression_p (expression);
18493       }
18494
18495     case SIZEOF_EXPR:
18496     case ALIGNOF_EXPR:
18497     case TYPEID_EXPR:
18498       /* A `sizeof' expression is value-dependent if the operand is
18499          type-dependent or is a pack expansion.  */
18500       expression = TREE_OPERAND (expression, 0);
18501       if (PACK_EXPANSION_P (expression))
18502         return true;
18503       else if (TYPE_P (expression))
18504         return dependent_type_p (expression);
18505       return type_dependent_expression_p (expression);
18506
18507     case AT_ENCODE_EXPR:
18508       /* An 'encode' expression is value-dependent if the operand is
18509          type-dependent.  */
18510       expression = TREE_OPERAND (expression, 0);
18511       return dependent_type_p (expression);
18512
18513     case NOEXCEPT_EXPR:
18514       expression = TREE_OPERAND (expression, 0);
18515       return type_dependent_expression_p (expression);
18516
18517     case SCOPE_REF:
18518       {
18519         tree name = TREE_OPERAND (expression, 1);
18520         return value_dependent_expression_p (name);
18521       }
18522
18523     case COMPONENT_REF:
18524       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
18525               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
18526
18527     case NONTYPE_ARGUMENT_PACK:
18528       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
18529          is value-dependent.  */
18530       {
18531         tree values = ARGUMENT_PACK_ARGS (expression);
18532         int i, len = TREE_VEC_LENGTH (values);
18533         
18534         for (i = 0; i < len; ++i)
18535           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
18536             return true;
18537         
18538         return false;
18539       }
18540
18541     case TRAIT_EXPR:
18542       {
18543         tree type2 = TRAIT_EXPR_TYPE2 (expression);
18544         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
18545                 || (type2 ? dependent_type_p (type2) : false));
18546       }
18547
18548     case MODOP_EXPR:
18549       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18550               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
18551
18552     case ARRAY_REF:
18553       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18554               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
18555
18556     case ADDR_EXPR:
18557       {
18558         tree op = TREE_OPERAND (expression, 0);
18559         return (value_dependent_expression_p (op)
18560                 || has_value_dependent_address (op));
18561       }
18562
18563     case CALL_EXPR:
18564       {
18565         tree fn = get_callee_fndecl (expression);
18566         int i, nargs;
18567         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
18568           return true;
18569         nargs = call_expr_nargs (expression);
18570         for (i = 0; i < nargs; ++i)
18571           {
18572             tree op = CALL_EXPR_ARG (expression, i);
18573             /* In a call to a constexpr member function, look through the
18574                implicit ADDR_EXPR on the object argument so that it doesn't
18575                cause the call to be considered value-dependent.  We also
18576                look through it in potential_constant_expression.  */
18577             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
18578                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
18579                 && TREE_CODE (op) == ADDR_EXPR)
18580               op = TREE_OPERAND (op, 0);
18581             if (value_dependent_expression_p (op))
18582               return true;
18583           }
18584         return false;
18585       }
18586
18587     case TEMPLATE_ID_EXPR:
18588       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
18589          type-dependent.  */
18590       return type_dependent_expression_p (expression);
18591
18592     case CONSTRUCTOR:
18593       {
18594         unsigned ix;
18595         tree val;
18596         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
18597           if (value_dependent_expression_p (val))
18598             return true;
18599         return false;
18600       }
18601
18602     default:
18603       /* A constant expression is value-dependent if any subexpression is
18604          value-dependent.  */
18605       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
18606         {
18607         case tcc_reference:
18608         case tcc_unary:
18609         case tcc_comparison:
18610         case tcc_binary:
18611         case tcc_expression:
18612         case tcc_vl_exp:
18613           {
18614             int i, len = cp_tree_operand_length (expression);
18615
18616             for (i = 0; i < len; i++)
18617               {
18618                 tree t = TREE_OPERAND (expression, i);
18619
18620                 /* In some cases, some of the operands may be missing.l
18621                    (For example, in the case of PREDECREMENT_EXPR, the
18622                    amount to increment by may be missing.)  That doesn't
18623                    make the expression dependent.  */
18624                 if (t && value_dependent_expression_p (t))
18625                   return true;
18626               }
18627           }
18628           break;
18629         default:
18630           break;
18631         }
18632       break;
18633     }
18634
18635   /* The expression is not value-dependent.  */
18636   return false;
18637 }
18638
18639 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
18640    [temp.dep.expr].  Note that an expression with no type is
18641    considered dependent.  Other parts of the compiler arrange for an
18642    expression with type-dependent subexpressions to have no type, so
18643    this function doesn't have to be fully recursive.  */
18644
18645 bool
18646 type_dependent_expression_p (tree expression)
18647 {
18648   if (!processing_template_decl)
18649     return false;
18650
18651   if (expression == error_mark_node)
18652     return false;
18653
18654   /* An unresolved name is always dependent.  */
18655   if (TREE_CODE (expression) == IDENTIFIER_NODE
18656       || TREE_CODE (expression) == USING_DECL)
18657     return true;
18658
18659   /* Some expression forms are never type-dependent.  */
18660   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
18661       || TREE_CODE (expression) == SIZEOF_EXPR
18662       || TREE_CODE (expression) == ALIGNOF_EXPR
18663       || TREE_CODE (expression) == AT_ENCODE_EXPR
18664       || TREE_CODE (expression) == NOEXCEPT_EXPR
18665       || TREE_CODE (expression) == TRAIT_EXPR
18666       || TREE_CODE (expression) == TYPEID_EXPR
18667       || TREE_CODE (expression) == DELETE_EXPR
18668       || TREE_CODE (expression) == VEC_DELETE_EXPR
18669       || TREE_CODE (expression) == THROW_EXPR)
18670     return false;
18671
18672   /* The types of these expressions depends only on the type to which
18673      the cast occurs.  */
18674   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
18675       || TREE_CODE (expression) == STATIC_CAST_EXPR
18676       || TREE_CODE (expression) == CONST_CAST_EXPR
18677       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
18678       || TREE_CODE (expression) == CAST_EXPR)
18679     return dependent_type_p (TREE_TYPE (expression));
18680
18681   /* The types of these expressions depends only on the type created
18682      by the expression.  */
18683   if (TREE_CODE (expression) == NEW_EXPR
18684       || TREE_CODE (expression) == VEC_NEW_EXPR)
18685     {
18686       /* For NEW_EXPR tree nodes created inside a template, either
18687          the object type itself or a TREE_LIST may appear as the
18688          operand 1.  */
18689       tree type = TREE_OPERAND (expression, 1);
18690       if (TREE_CODE (type) == TREE_LIST)
18691         /* This is an array type.  We need to check array dimensions
18692            as well.  */
18693         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
18694                || value_dependent_expression_p
18695                     (TREE_OPERAND (TREE_VALUE (type), 1));
18696       else
18697         return dependent_type_p (type);
18698     }
18699
18700   if (TREE_CODE (expression) == SCOPE_REF)
18701     {
18702       tree scope = TREE_OPERAND (expression, 0);
18703       tree name = TREE_OPERAND (expression, 1);
18704
18705       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
18706          contains an identifier associated by name lookup with one or more
18707          declarations declared with a dependent type, or...a
18708          nested-name-specifier or qualified-id that names a member of an
18709          unknown specialization.  */
18710       return (type_dependent_expression_p (name)
18711               || dependent_scope_p (scope));
18712     }
18713
18714   if (TREE_CODE (expression) == FUNCTION_DECL
18715       && DECL_LANG_SPECIFIC (expression)
18716       && DECL_TEMPLATE_INFO (expression)
18717       && (any_dependent_template_arguments_p
18718           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
18719     return true;
18720
18721   if (TREE_CODE (expression) == TEMPLATE_DECL
18722       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
18723     return false;
18724
18725   if (TREE_CODE (expression) == STMT_EXPR)
18726     expression = stmt_expr_value_expr (expression);
18727
18728   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
18729     {
18730       tree elt;
18731       unsigned i;
18732
18733       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
18734         {
18735           if (type_dependent_expression_p (elt))
18736             return true;
18737         }
18738       return false;
18739     }
18740
18741   /* A static data member of the current instantiation with incomplete
18742      array type is type-dependent, as the definition and specializations
18743      can have different bounds.  */
18744   if (TREE_CODE (expression) == VAR_DECL
18745       && DECL_CLASS_SCOPE_P (expression)
18746       && dependent_type_p (DECL_CONTEXT (expression))
18747       && VAR_HAD_UNKNOWN_BOUND (expression))
18748     return true;
18749
18750   if (TREE_TYPE (expression) == unknown_type_node)
18751     {
18752       if (TREE_CODE (expression) == ADDR_EXPR)
18753         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
18754       if (TREE_CODE (expression) == COMPONENT_REF
18755           || TREE_CODE (expression) == OFFSET_REF)
18756         {
18757           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
18758             return true;
18759           expression = TREE_OPERAND (expression, 1);
18760           if (TREE_CODE (expression) == IDENTIFIER_NODE)
18761             return false;
18762         }
18763       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
18764       if (TREE_CODE (expression) == SCOPE_REF)
18765         return false;
18766
18767       if (TREE_CODE (expression) == BASELINK)
18768         expression = BASELINK_FUNCTIONS (expression);
18769
18770       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
18771         {
18772           if (any_dependent_template_arguments_p
18773               (TREE_OPERAND (expression, 1)))
18774             return true;
18775           expression = TREE_OPERAND (expression, 0);
18776         }
18777       gcc_assert (TREE_CODE (expression) == OVERLOAD
18778                   || TREE_CODE (expression) == FUNCTION_DECL);
18779
18780       while (expression)
18781         {
18782           if (type_dependent_expression_p (OVL_CURRENT (expression)))
18783             return true;
18784           expression = OVL_NEXT (expression);
18785         }
18786       return false;
18787     }
18788
18789   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
18790
18791   return (dependent_type_p (TREE_TYPE (expression)));
18792 }
18793
18794 /* Like type_dependent_expression_p, but it also works while not processing
18795    a template definition, i.e. during substitution or mangling.  */
18796
18797 bool
18798 type_dependent_expression_p_push (tree expr)
18799 {
18800   bool b;
18801   ++processing_template_decl;
18802   b = type_dependent_expression_p (expr);
18803   --processing_template_decl;
18804   return b;
18805 }
18806
18807 /* Returns TRUE if ARGS contains a type-dependent expression.  */
18808
18809 bool
18810 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
18811 {
18812   unsigned int i;
18813   tree arg;
18814
18815   FOR_EACH_VEC_ELT (tree, args, i, arg)
18816     {
18817       if (type_dependent_expression_p (arg))
18818         return true;
18819     }
18820   return false;
18821 }
18822
18823 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
18824    expressions) contains any type-dependent expressions.  */
18825
18826 bool
18827 any_type_dependent_elements_p (const_tree list)
18828 {
18829   for (; list; list = TREE_CHAIN (list))
18830     if (value_dependent_expression_p (TREE_VALUE (list)))
18831       return true;
18832
18833   return false;
18834 }
18835
18836 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
18837    expressions) contains any value-dependent expressions.  */
18838
18839 bool
18840 any_value_dependent_elements_p (const_tree list)
18841 {
18842   for (; list; list = TREE_CHAIN (list))
18843     if (value_dependent_expression_p (TREE_VALUE (list)))
18844       return true;
18845
18846   return false;
18847 }
18848
18849 /* Returns TRUE if the ARG (a template argument) is dependent.  */
18850
18851 bool
18852 dependent_template_arg_p (tree arg)
18853 {
18854   if (!processing_template_decl)
18855     return false;
18856
18857   /* Assume a template argument that was wrongly written by the user
18858      is dependent. This is consistent with what
18859      any_dependent_template_arguments_p [that calls this function]
18860      does.  */
18861   if (!arg || arg == error_mark_node)
18862     return true;
18863
18864   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
18865     arg = ARGUMENT_PACK_SELECT_ARG (arg);
18866
18867   if (TREE_CODE (arg) == TEMPLATE_DECL
18868       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18869     return dependent_template_p (arg);
18870   else if (ARGUMENT_PACK_P (arg))
18871     {
18872       tree args = ARGUMENT_PACK_ARGS (arg);
18873       int i, len = TREE_VEC_LENGTH (args);
18874       for (i = 0; i < len; ++i)
18875         {
18876           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18877             return true;
18878         }
18879
18880       return false;
18881     }
18882   else if (TYPE_P (arg))
18883     return dependent_type_p (arg);
18884   else
18885     return (type_dependent_expression_p (arg)
18886             || value_dependent_expression_p (arg));
18887 }
18888
18889 /* Returns true if ARGS (a collection of template arguments) contains
18890    any types that require structural equality testing.  */
18891
18892 bool
18893 any_template_arguments_need_structural_equality_p (tree args)
18894 {
18895   int i;
18896   int j;
18897
18898   if (!args)
18899     return false;
18900   if (args == error_mark_node)
18901     return true;
18902
18903   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18904     {
18905       tree level = TMPL_ARGS_LEVEL (args, i + 1);
18906       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18907         {
18908           tree arg = TREE_VEC_ELT (level, j);
18909           tree packed_args = NULL_TREE;
18910           int k, len = 1;
18911
18912           if (ARGUMENT_PACK_P (arg))
18913             {
18914               /* Look inside the argument pack.  */
18915               packed_args = ARGUMENT_PACK_ARGS (arg);
18916               len = TREE_VEC_LENGTH (packed_args);
18917             }
18918
18919           for (k = 0; k < len; ++k)
18920             {
18921               if (packed_args)
18922                 arg = TREE_VEC_ELT (packed_args, k);
18923
18924               if (error_operand_p (arg))
18925                 return true;
18926               else if (TREE_CODE (arg) == TEMPLATE_DECL
18927                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18928                 continue;
18929               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
18930                 return true;
18931               else if (!TYPE_P (arg) && TREE_TYPE (arg)
18932                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
18933                 return true;
18934             }
18935         }
18936     }
18937
18938   return false;
18939 }
18940
18941 /* Returns true if ARGS (a collection of template arguments) contains
18942    any dependent arguments.  */
18943
18944 bool
18945 any_dependent_template_arguments_p (const_tree args)
18946 {
18947   int i;
18948   int j;
18949
18950   if (!args)
18951     return false;
18952   if (args == error_mark_node)
18953     return true;
18954
18955   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18956     {
18957       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
18958       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18959         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
18960           return true;
18961     }
18962
18963   return false;
18964 }
18965
18966 /* Returns TRUE if the template TMPL is dependent.  */
18967
18968 bool
18969 dependent_template_p (tree tmpl)
18970 {
18971   if (TREE_CODE (tmpl) == OVERLOAD)
18972     {
18973       while (tmpl)
18974         {
18975           if (dependent_template_p (OVL_CURRENT (tmpl)))
18976             return true;
18977           tmpl = OVL_NEXT (tmpl);
18978         }
18979       return false;
18980     }
18981
18982   /* Template template parameters are dependent.  */
18983   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
18984       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
18985     return true;
18986   /* So are names that have not been looked up.  */
18987   if (TREE_CODE (tmpl) == SCOPE_REF
18988       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
18989     return true;
18990   /* So are member templates of dependent classes.  */
18991   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
18992     return dependent_type_p (DECL_CONTEXT (tmpl));
18993   return false;
18994 }
18995
18996 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
18997
18998 bool
18999 dependent_template_id_p (tree tmpl, tree args)
19000 {
19001   return (dependent_template_p (tmpl)
19002           || any_dependent_template_arguments_p (args));
19003 }
19004
19005 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
19006    is dependent.  */
19007
19008 bool
19009 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
19010 {
19011   int i;
19012
19013   if (!processing_template_decl)
19014     return false;
19015
19016   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
19017     {
19018       tree decl = TREE_VEC_ELT (declv, i);
19019       tree init = TREE_VEC_ELT (initv, i);
19020       tree cond = TREE_VEC_ELT (condv, i);
19021       tree incr = TREE_VEC_ELT (incrv, i);
19022
19023       if (type_dependent_expression_p (decl))
19024         return true;
19025
19026       if (init && type_dependent_expression_p (init))
19027         return true;
19028
19029       if (type_dependent_expression_p (cond))
19030         return true;
19031
19032       if (COMPARISON_CLASS_P (cond)
19033           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
19034               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
19035         return true;
19036
19037       if (TREE_CODE (incr) == MODOP_EXPR)
19038         {
19039           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
19040               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
19041             return true;
19042         }
19043       else if (type_dependent_expression_p (incr))
19044         return true;
19045       else if (TREE_CODE (incr) == MODIFY_EXPR)
19046         {
19047           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
19048             return true;
19049           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
19050             {
19051               tree t = TREE_OPERAND (incr, 1);
19052               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
19053                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
19054                 return true;
19055             }
19056         }
19057     }
19058
19059   return false;
19060 }
19061
19062 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
19063    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
19064    no such TYPE can be found.  Note that this function peers inside
19065    uninstantiated templates and therefore should be used only in
19066    extremely limited situations.  ONLY_CURRENT_P restricts this
19067    peering to the currently open classes hierarchy (which is required
19068    when comparing types).  */
19069
19070 tree
19071 resolve_typename_type (tree type, bool only_current_p)
19072 {
19073   tree scope;
19074   tree name;
19075   tree decl;
19076   int quals;
19077   tree pushed_scope;
19078   tree result;
19079
19080   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
19081
19082   scope = TYPE_CONTEXT (type);
19083   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
19084      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
19085      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
19086      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
19087      identifier  of the TYPENAME_TYPE anymore.
19088      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
19089      TYPENAME_TYPE instead, we avoid messing up with a possible
19090      typedef variant case.  */
19091   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
19092
19093   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
19094      it first before we can figure out what NAME refers to.  */
19095   if (TREE_CODE (scope) == TYPENAME_TYPE)
19096     scope = resolve_typename_type (scope, only_current_p);
19097   /* If we don't know what SCOPE refers to, then we cannot resolve the
19098      TYPENAME_TYPE.  */
19099   if (TREE_CODE (scope) == TYPENAME_TYPE)
19100     return type;
19101   /* If the SCOPE is a template type parameter, we have no way of
19102      resolving the name.  */
19103   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
19104     return type;
19105   /* If the SCOPE is not the current instantiation, there's no reason
19106      to look inside it.  */
19107   if (only_current_p && !currently_open_class (scope))
19108     return type;
19109   /* If this is a typedef, we don't want to look inside (c++/11987).  */
19110   if (typedef_variant_p (type))
19111     return type;
19112   /* If SCOPE isn't the template itself, it will not have a valid
19113      TYPE_FIELDS list.  */
19114   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
19115     /* scope is either the template itself or a compatible instantiation
19116        like X<T>, so look up the name in the original template.  */
19117     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
19118   else
19119     /* scope is a partial instantiation, so we can't do the lookup or we
19120        will lose the template arguments.  */
19121     return type;
19122   /* Enter the SCOPE so that name lookup will be resolved as if we
19123      were in the class definition.  In particular, SCOPE will no
19124      longer be considered a dependent type.  */
19125   pushed_scope = push_scope (scope);
19126   /* Look up the declaration.  */
19127   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
19128
19129   result = NULL_TREE;
19130   
19131   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
19132      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
19133   if (!decl)
19134     /*nop*/;
19135   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
19136            && TREE_CODE (decl) == TYPE_DECL)
19137     {
19138       result = TREE_TYPE (decl);
19139       if (result == error_mark_node)
19140         result = NULL_TREE;
19141     }
19142   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
19143            && DECL_CLASS_TEMPLATE_P (decl))
19144     {
19145       tree tmpl;
19146       tree args;
19147       /* Obtain the template and the arguments.  */
19148       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
19149       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
19150       /* Instantiate the template.  */
19151       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
19152                                       /*entering_scope=*/0,
19153                                       tf_error | tf_user);
19154       if (result == error_mark_node)
19155         result = NULL_TREE;
19156     }
19157   
19158   /* Leave the SCOPE.  */
19159   if (pushed_scope)
19160     pop_scope (pushed_scope);
19161
19162   /* If we failed to resolve it, return the original typename.  */
19163   if (!result)
19164     return type;
19165   
19166   /* If lookup found a typename type, resolve that too.  */
19167   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
19168     {
19169       /* Ill-formed programs can cause infinite recursion here, so we
19170          must catch that.  */
19171       TYPENAME_IS_RESOLVING_P (type) = 1;
19172       result = resolve_typename_type (result, only_current_p);
19173       TYPENAME_IS_RESOLVING_P (type) = 0;
19174     }
19175   
19176   /* Qualify the resulting type.  */
19177   quals = cp_type_quals (type);
19178   if (quals)
19179     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
19180
19181   return result;
19182 }
19183
19184 /* EXPR is an expression which is not type-dependent.  Return a proxy
19185    for EXPR that can be used to compute the types of larger
19186    expressions containing EXPR.  */
19187
19188 tree
19189 build_non_dependent_expr (tree expr)
19190 {
19191   tree inner_expr;
19192
19193 #ifdef ENABLE_CHECKING
19194   /* Try to get a constant value for all non-type-dependent expressions in
19195       order to expose bugs in *_dependent_expression_p and constexpr.  */
19196   if (cxx_dialect >= cxx0x)
19197     maybe_constant_value (fold_non_dependent_expr_sfinae (expr, tf_none));
19198 #endif
19199
19200   /* Preserve OVERLOADs; the functions must be available to resolve
19201      types.  */
19202   inner_expr = expr;
19203   if (TREE_CODE (inner_expr) == STMT_EXPR)
19204     inner_expr = stmt_expr_value_expr (inner_expr);
19205   if (TREE_CODE (inner_expr) == ADDR_EXPR)
19206     inner_expr = TREE_OPERAND (inner_expr, 0);
19207   if (TREE_CODE (inner_expr) == COMPONENT_REF)
19208     inner_expr = TREE_OPERAND (inner_expr, 1);
19209   if (is_overloaded_fn (inner_expr)
19210       || TREE_CODE (inner_expr) == OFFSET_REF)
19211     return expr;
19212   /* There is no need to return a proxy for a variable.  */
19213   if (TREE_CODE (expr) == VAR_DECL)
19214     return expr;
19215   /* Preserve string constants; conversions from string constants to
19216      "char *" are allowed, even though normally a "const char *"
19217      cannot be used to initialize a "char *".  */
19218   if (TREE_CODE (expr) == STRING_CST)
19219     return expr;
19220   /* Preserve arithmetic constants, as an optimization -- there is no
19221      reason to create a new node.  */
19222   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
19223     return expr;
19224   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
19225      There is at least one place where we want to know that a
19226      particular expression is a throw-expression: when checking a ?:
19227      expression, there are special rules if the second or third
19228      argument is a throw-expression.  */
19229   if (TREE_CODE (expr) == THROW_EXPR)
19230     return expr;
19231
19232   if (TREE_CODE (expr) == COND_EXPR)
19233     return build3 (COND_EXPR,
19234                    TREE_TYPE (expr),
19235                    TREE_OPERAND (expr, 0),
19236                    (TREE_OPERAND (expr, 1)
19237                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
19238                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
19239                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
19240   if (TREE_CODE (expr) == COMPOUND_EXPR
19241       && !COMPOUND_EXPR_OVERLOADED (expr))
19242     return build2 (COMPOUND_EXPR,
19243                    TREE_TYPE (expr),
19244                    TREE_OPERAND (expr, 0),
19245                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
19246
19247   /* If the type is unknown, it can't really be non-dependent */
19248   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
19249
19250   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
19251   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
19252 }
19253
19254 /* ARGS is a vector of expressions as arguments to a function call.
19255    Replace the arguments with equivalent non-dependent expressions.
19256    This modifies ARGS in place.  */
19257
19258 void
19259 make_args_non_dependent (VEC(tree,gc) *args)
19260 {
19261   unsigned int ix;
19262   tree arg;
19263
19264   FOR_EACH_VEC_ELT (tree, args, ix, arg)
19265     {
19266       tree newarg = build_non_dependent_expr (arg);
19267       if (newarg != arg)
19268         VEC_replace (tree, args, ix, newarg);
19269     }
19270 }
19271
19272 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
19273    with a level one deeper than the actual template parms.  */
19274
19275 tree
19276 make_auto (void)
19277 {
19278   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
19279   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
19280                                TYPE_DECL, get_identifier ("auto"), au);
19281   TYPE_STUB_DECL (au) = TYPE_NAME (au);
19282   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
19283     (0, processing_template_decl + 1, processing_template_decl + 1,
19284      0, TYPE_NAME (au), NULL_TREE);
19285   TYPE_CANONICAL (au) = canonical_type_parameter (au);
19286   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
19287   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
19288
19289   return au;
19290 }
19291
19292 /* Given type ARG, return std::initializer_list<ARG>.  */
19293
19294 static tree
19295 listify (tree arg)
19296 {
19297   tree std_init_list = namespace_binding
19298     (get_identifier ("initializer_list"), std_node);
19299   tree argvec;
19300   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
19301     {    
19302       error ("deducing from brace-enclosed initializer list requires "
19303              "#include <initializer_list>");
19304       return error_mark_node;
19305     }
19306   argvec = make_tree_vec (1);
19307   TREE_VEC_ELT (argvec, 0) = arg;
19308   return lookup_template_class (std_init_list, argvec, NULL_TREE,
19309                                 NULL_TREE, 0, tf_warning_or_error);
19310 }
19311
19312 /* Replace auto in TYPE with std::initializer_list<auto>.  */
19313
19314 static tree
19315 listify_autos (tree type, tree auto_node)
19316 {
19317   tree init_auto = listify (auto_node);
19318   tree argvec = make_tree_vec (1);
19319   TREE_VEC_ELT (argvec, 0) = init_auto;
19320   if (processing_template_decl)
19321     argvec = add_to_template_args (current_template_args (), argvec);
19322   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19323 }
19324
19325 /* walk_tree helper for do_auto_deduction.  */
19326
19327 static tree
19328 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
19329                  void *type)
19330 {
19331   /* Is this a variable with the type we're looking for?  */
19332   if (DECL_P (*tp)
19333       && TREE_TYPE (*tp) == type)
19334     return *tp;
19335   else
19336     return NULL_TREE;
19337 }
19338
19339 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
19340    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
19341
19342 tree
19343 do_auto_deduction (tree type, tree init, tree auto_node)
19344 {
19345   tree parms, tparms, targs;
19346   tree args[1];
19347   tree decl;
19348   int val;
19349
19350   if (processing_template_decl
19351       && (TREE_TYPE (init) == NULL_TREE
19352           || BRACE_ENCLOSED_INITIALIZER_P (init)))
19353     /* Not enough information to try this yet.  */
19354     return type;
19355
19356   /* The name of the object being declared shall not appear in the
19357      initializer expression.  */
19358   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
19359   if (decl)
19360     {
19361       error ("variable %q#D with %<auto%> type used in its own "
19362              "initializer", decl);
19363       return error_mark_node;
19364     }
19365
19366   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
19367      with either a new invented type template parameter U or, if the
19368      initializer is a braced-init-list (8.5.4), with
19369      std::initializer_list<U>.  */
19370   if (BRACE_ENCLOSED_INITIALIZER_P (init))
19371     type = listify_autos (type, auto_node);
19372
19373   init = resolve_nondeduced_context (init);
19374
19375   parms = build_tree_list (NULL_TREE, type);
19376   args[0] = init;
19377   tparms = make_tree_vec (1);
19378   targs = make_tree_vec (1);
19379   TREE_VEC_ELT (tparms, 0)
19380     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
19381   val = type_unification_real (tparms, targs, parms, args, 1, 0,
19382                                DEDUCE_CALL, LOOKUP_NORMAL);
19383   if (val > 0)
19384     {
19385       if (processing_template_decl)
19386         /* Try again at instantiation time.  */
19387         return type;
19388       if (type && type != error_mark_node)
19389         /* If type is error_mark_node a diagnostic must have been
19390            emitted by now.  Also, having a mention to '<type error>'
19391            in the diagnostic is not really useful to the user.  */
19392         error ("unable to deduce %qT from %qE", type, init);
19393       return error_mark_node;
19394     }
19395
19396   /* If the list of declarators contains more than one declarator, the type
19397      of each declared variable is determined as described above. If the
19398      type deduced for the template parameter U is not the same in each
19399      deduction, the program is ill-formed.  */
19400   if (TREE_TYPE (auto_node)
19401       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
19402     {
19403       error ("inconsistent deduction for %qT: %qT and then %qT",
19404              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
19405       return error_mark_node;
19406     }
19407   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
19408
19409   if (processing_template_decl)
19410     targs = add_to_template_args (current_template_args (), targs);
19411   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
19412 }
19413
19414 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
19415    result.  */
19416
19417 tree
19418 splice_late_return_type (tree type, tree late_return_type)
19419 {
19420   tree argvec;
19421
19422   if (late_return_type == NULL_TREE)
19423     return type;
19424   argvec = make_tree_vec (1);
19425   TREE_VEC_ELT (argvec, 0) = late_return_type;
19426   if (processing_template_parmlist)
19427     /* For a late-specified return type in a template type-parameter, we
19428        need to add a dummy argument level for its parmlist.  */
19429     argvec = add_to_template_args
19430       (make_tree_vec (processing_template_parmlist), argvec);
19431   if (current_template_parms)
19432     argvec = add_to_template_args (current_template_args (), argvec);
19433   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19434 }
19435
19436 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
19437
19438 bool
19439 is_auto (const_tree type)
19440 {
19441   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19442       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
19443     return true;
19444   else
19445     return false;
19446 }
19447
19448 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
19449    appear as a type-specifier for the declaration in question, we don't
19450    have to look through the whole type.  */
19451
19452 tree
19453 type_uses_auto (tree type)
19454 {
19455   enum tree_code code;
19456   if (is_auto (type))
19457     return type;
19458
19459   code = TREE_CODE (type);
19460
19461   if (code == POINTER_TYPE || code == REFERENCE_TYPE
19462       || code == OFFSET_TYPE || code == FUNCTION_TYPE
19463       || code == METHOD_TYPE || code == ARRAY_TYPE)
19464     return type_uses_auto (TREE_TYPE (type));
19465
19466   if (TYPE_PTRMEMFUNC_P (type))
19467     return type_uses_auto (TREE_TYPE (TREE_TYPE
19468                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
19469
19470   return NULL_TREE;
19471 }
19472
19473 /* For a given template T, return the vector of typedefs referenced
19474    in T for which access check is needed at T instantiation time.
19475    T is either  a FUNCTION_DECL or a RECORD_TYPE.
19476    Those typedefs were added to T by the function
19477    append_type_to_template_for_access_check.  */
19478
19479 VEC(qualified_typedef_usage_t,gc)*
19480 get_types_needing_access_check (tree t)
19481 {
19482   tree ti;
19483   VEC(qualified_typedef_usage_t,gc) *result = NULL;
19484
19485   if (!t || t == error_mark_node)
19486     return NULL;
19487
19488   if (!(ti = get_template_info (t)))
19489     return NULL;
19490
19491   if (CLASS_TYPE_P (t)
19492       || TREE_CODE (t) == FUNCTION_DECL)
19493     {
19494       if (!TI_TEMPLATE (ti))
19495         return NULL;
19496
19497       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
19498     }
19499
19500   return result;
19501 }
19502
19503 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
19504    tied to T. That list of typedefs will be access checked at
19505    T instantiation time.
19506    T is either a FUNCTION_DECL or a RECORD_TYPE.
19507    TYPE_DECL is a TYPE_DECL node representing a typedef.
19508    SCOPE is the scope through which TYPE_DECL is accessed.
19509    LOCATION is the location of the usage point of TYPE_DECL.
19510
19511    This function is a subroutine of
19512    append_type_to_template_for_access_check.  */
19513
19514 static void
19515 append_type_to_template_for_access_check_1 (tree t,
19516                                             tree type_decl,
19517                                             tree scope,
19518                                             location_t location)
19519 {
19520   qualified_typedef_usage_t typedef_usage;
19521   tree ti;
19522
19523   if (!t || t == error_mark_node)
19524     return;
19525
19526   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
19527                || CLASS_TYPE_P (t))
19528               && type_decl
19529               && TREE_CODE (type_decl) == TYPE_DECL
19530               && scope);
19531
19532   if (!(ti = get_template_info (t)))
19533     return;
19534
19535   gcc_assert (TI_TEMPLATE (ti));
19536
19537   typedef_usage.typedef_decl = type_decl;
19538   typedef_usage.context = scope;
19539   typedef_usage.locus = location;
19540
19541   VEC_safe_push (qualified_typedef_usage_t, gc,
19542                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
19543                  &typedef_usage);
19544 }
19545
19546 /* Append TYPE_DECL to the template TEMPL.
19547    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
19548    At TEMPL instanciation time, TYPE_DECL will be checked to see
19549    if it can be accessed through SCOPE.
19550    LOCATION is the location of the usage point of TYPE_DECL.
19551
19552    e.g. consider the following code snippet:
19553
19554      class C
19555      {
19556        typedef int myint;
19557      };
19558
19559      template<class U> struct S
19560      {
19561        C::myint mi; // <-- usage point of the typedef C::myint
19562      };
19563
19564      S<char> s;
19565
19566    At S<char> instantiation time, we need to check the access of C::myint
19567    In other words, we need to check the access of the myint typedef through
19568    the C scope. For that purpose, this function will add the myint typedef
19569    and the scope C through which its being accessed to a list of typedefs
19570    tied to the template S. That list will be walked at template instantiation
19571    time and access check performed on each typedefs it contains.
19572    Note that this particular code snippet should yield an error because
19573    myint is private to C.  */
19574
19575 void
19576 append_type_to_template_for_access_check (tree templ,
19577                                           tree type_decl,
19578                                           tree scope,
19579                                           location_t location)
19580 {
19581   qualified_typedef_usage_t *iter;
19582   int i;
19583
19584   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
19585
19586   /* Make sure we don't append the type to the template twice.  */
19587   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
19588                     get_types_needing_access_check (templ),
19589                     i, iter)
19590     if (iter->typedef_decl == type_decl && scope == iter->context)
19591       return;
19592
19593   append_type_to_template_for_access_check_1 (templ, type_decl,
19594                                               scope, location);
19595 }
19596
19597 /* Set up the hash tables for template instantiations.  */
19598
19599 void
19600 init_template_processing (void)
19601 {
19602   decl_specializations = htab_create_ggc (37,
19603                                           hash_specialization,
19604                                           eq_specializations,
19605                                           ggc_free);
19606   type_specializations = htab_create_ggc (37,
19607                                           hash_specialization,
19608                                           eq_specializations,
19609                                           ggc_free);
19610 }
19611
19612 /* Print stats about the template hash tables for -fstats.  */
19613
19614 void
19615 print_template_statistics (void)
19616 {
19617   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
19618            "%f collisions\n", (long) htab_size (decl_specializations),
19619            (long) htab_elements (decl_specializations),
19620            htab_collisions (decl_specializations));
19621   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
19622            "%f collisions\n", (long) htab_size (type_specializations),
19623            (long) htab_elements (type_specializations),
19624            htab_collisions (type_specializations));
19625 }
19626
19627 #include "gt-cp-pt.h"