OSDN Git Service

gcc/
[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
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 "cp-objcp-common.h"
40 #include "tree-inline.h"
41 #include "decl.h"
42 #include "output.h"
43 #include "toplev.h"
44 #include "timevar.h"
45 #include "tree-iterator.h"
46 #include "vecprim.h"
47
48 /* The type of functions taking a tree, and some additional data, and
49    returning an int.  */
50 typedef int (*tree_fn_t) (tree, void*);
51
52 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
53    instantiations have been deferred, either because their definitions
54    were not yet available, or because we were putting off doing the work.  */
55 struct GTY (()) pending_template {
56   struct pending_template *next;
57   struct tinst_level *tinst;
58 };
59
60 static GTY(()) struct pending_template *pending_templates;
61 static GTY(()) struct pending_template *last_pending_template;
62
63 int processing_template_parmlist;
64 static int template_header_count;
65
66 static GTY(()) tree saved_trees;
67 static VEC(int,heap) *inline_parm_levels;
68
69 static GTY(()) struct tinst_level *current_tinst_level;
70
71 static GTY(()) tree saved_access_scope;
72
73 /* Live only within one (recursive) call to tsubst_expr.  We use
74    this to pass the statement expression node from the STMT_EXPR
75    to the EXPR_STMT that is its result.  */
76 static tree cur_stmt_expr;
77
78 /* A map from local variable declarations in the body of the template
79    presently being instantiated to the corresponding instantiated
80    local variables.  */
81 static htab_t local_specializations;
82
83 typedef struct GTY(()) spec_entry
84 {
85   tree tmpl;
86   tree args;
87   tree spec;
88 } spec_entry;
89
90 static GTY ((param_is (spec_entry)))
91   htab_t decl_specializations;
92
93 static GTY ((param_is (spec_entry)))
94   htab_t type_specializations;
95
96 /* Contains canonical template parameter types. The vector is indexed by
97    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
98    TREE_LIST, whose TREE_VALUEs contain the canonical template
99    parameters of various types and levels.  */
100 static GTY(()) VEC(tree,gc) *canonical_template_parms;
101
102 #define UNIFY_ALLOW_NONE 0
103 #define UNIFY_ALLOW_MORE_CV_QUAL 1
104 #define UNIFY_ALLOW_LESS_CV_QUAL 2
105 #define UNIFY_ALLOW_DERIVED 4
106 #define UNIFY_ALLOW_INTEGER 8
107 #define UNIFY_ALLOW_OUTER_LEVEL 16
108 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
109 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
110
111 static void push_access_scope (tree);
112 static void pop_access_scope (tree);
113 static bool resolve_overloaded_unification (tree, tree, tree, tree,
114                                             unification_kind_t, int);
115 static int try_one_overload (tree, tree, tree, tree, tree,
116                              unification_kind_t, int, bool);
117 static int unify (tree, tree, tree, tree, int);
118 static void add_pending_template (tree);
119 static tree reopen_tinst_level (struct tinst_level *);
120 static tree tsubst_initializer_list (tree, tree);
121 static tree get_class_bindings (tree, tree, tree);
122 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
123                                    bool, bool);
124 static void tsubst_enum (tree, tree, tree);
125 static tree add_to_template_args (tree, tree);
126 static tree add_outermost_template_args (tree, tree);
127 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
128 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
129                                              tree);
130 static int type_unification_real (tree, tree, tree, const tree *,
131                                   unsigned int, int, unification_kind_t, int);
132 static void note_template_header (int);
133 static tree convert_nontype_argument_function (tree, tree);
134 static tree convert_nontype_argument (tree, tree);
135 static tree convert_template_argument (tree, tree, tree,
136                                        tsubst_flags_t, int, tree);
137 static int for_each_template_parm (tree, tree_fn_t, void*,
138                                    struct pointer_set_t*, bool);
139 static tree expand_template_argument_pack (tree);
140 static tree build_template_parm_index (int, int, int, tree, tree);
141 static bool inline_needs_template_parms (tree);
142 static void push_inline_template_parms_recursive (tree, int);
143 static tree retrieve_local_specialization (tree);
144 static void register_local_specialization (tree, tree);
145 static hashval_t hash_specialization (const void *p);
146 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
147 static int mark_template_parm (tree, void *);
148 static int template_parm_this_level_p (tree, void *);
149 static tree tsubst_friend_function (tree, tree);
150 static tree tsubst_friend_class (tree, tree);
151 static int can_complete_type_without_circularity (tree);
152 static tree get_bindings (tree, tree, tree, bool);
153 static int template_decl_level (tree);
154 static int check_cv_quals_for_unify (int, tree, tree);
155 static void template_parm_level_and_index (tree, int*, int*);
156 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
157 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
158 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
159 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
160 static void regenerate_decl_from_template (tree, tree);
161 static tree most_specialized_class (tree, tree, tsubst_flags_t);
162 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
163 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
164 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
165 static bool check_specialization_scope (void);
166 static tree process_partial_specialization (tree);
167 static void set_current_access_from_decl (tree);
168 static tree get_template_base (tree, tree, tree, tree);
169 static tree try_class_unification (tree, tree, tree, tree);
170 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
171                                            tree, tree);
172 static bool template_template_parm_bindings_ok_p (tree, tree);
173 static int template_args_equal (tree, tree);
174 static void tsubst_default_arguments (tree);
175 static tree for_each_template_parm_r (tree *, int *, void *);
176 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
177 static void copy_default_args_to_explicit_spec (tree);
178 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
179 static int eq_local_specializations (const void *, const void *);
180 static bool dependent_template_arg_p (tree);
181 static bool any_template_arguments_need_structural_equality_p (tree);
182 static bool dependent_type_p_r (tree);
183 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
184 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
185 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
186 static tree tsubst_decl (tree, tree, tsubst_flags_t);
187 static void perform_typedefs_access_check (tree tmpl, tree targs);
188 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
189                                                         location_t);
190 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
191 static tree listify (tree);
192 static tree listify_autos (tree, tree);
193
194 /* Make the current scope suitable for access checking when we are
195    processing T.  T can be FUNCTION_DECL for instantiated function
196    template, or VAR_DECL for static member variable (need by
197    instantiate_decl).  */
198
199 static void
200 push_access_scope (tree t)
201 {
202   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
203               || TREE_CODE (t) == VAR_DECL);
204
205   if (DECL_FRIEND_CONTEXT (t))
206     push_nested_class (DECL_FRIEND_CONTEXT (t));
207   else if (DECL_CLASS_SCOPE_P (t))
208     push_nested_class (DECL_CONTEXT (t));
209   else
210     push_to_top_level ();
211
212   if (TREE_CODE (t) == FUNCTION_DECL)
213     {
214       saved_access_scope = tree_cons
215         (NULL_TREE, current_function_decl, saved_access_scope);
216       current_function_decl = t;
217     }
218 }
219
220 /* Restore the scope set up by push_access_scope.  T is the node we
221    are processing.  */
222
223 static void
224 pop_access_scope (tree t)
225 {
226   if (TREE_CODE (t) == FUNCTION_DECL)
227     {
228       current_function_decl = TREE_VALUE (saved_access_scope);
229       saved_access_scope = TREE_CHAIN (saved_access_scope);
230     }
231
232   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
233     pop_nested_class ();
234   else
235     pop_from_top_level ();
236 }
237
238 /* Do any processing required when DECL (a member template
239    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
240    to DECL, unless it is a specialization, in which case the DECL
241    itself is returned.  */
242
243 tree
244 finish_member_template_decl (tree decl)
245 {
246   if (decl == error_mark_node)
247     return error_mark_node;
248
249   gcc_assert (DECL_P (decl));
250
251   if (TREE_CODE (decl) == TYPE_DECL)
252     {
253       tree type;
254
255       type = TREE_TYPE (decl);
256       if (type == error_mark_node)
257         return error_mark_node;
258       if (MAYBE_CLASS_TYPE_P (type)
259           && CLASSTYPE_TEMPLATE_INFO (type)
260           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
261         {
262           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
263           check_member_template (tmpl);
264           return tmpl;
265         }
266       return NULL_TREE;
267     }
268   else if (TREE_CODE (decl) == FIELD_DECL)
269     error ("data member %qD cannot be a member template", decl);
270   else if (DECL_TEMPLATE_INFO (decl))
271     {
272       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
273         {
274           check_member_template (DECL_TI_TEMPLATE (decl));
275           return DECL_TI_TEMPLATE (decl);
276         }
277       else
278         return decl;
279     }
280   else
281     error ("invalid member template declaration %qD", decl);
282
283   return error_mark_node;
284 }
285
286 /* Create a template info node.  */
287
288 tree
289 build_template_info (tree template_decl, tree template_args)
290 {
291   tree result = make_node (TEMPLATE_INFO);
292   TI_TEMPLATE (result) = template_decl;
293   TI_ARGS (result) = template_args;
294   return result;
295 }
296
297 /* Return the template info node corresponding to T, whatever T is.  */
298
299 tree
300 get_template_info (const_tree t)
301 {
302   tree tinfo = NULL_TREE;
303
304   if (!t || t == error_mark_node)
305     return NULL;
306
307   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
308     tinfo = DECL_TEMPLATE_INFO (t);
309
310   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
311     t = TREE_TYPE (t);
312
313   if (TAGGED_TYPE_P (t))
314     tinfo = TYPE_TEMPLATE_INFO (t);
315   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
316     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
317
318   return tinfo;
319 }
320
321 /* Returns the template nesting level of the indicated class TYPE.
322
323    For example, in:
324      template <class T>
325      struct A
326      {
327        template <class U>
328        struct B {};
329      };
330
331    A<T>::B<U> has depth two, while A<T> has depth one.
332    Both A<T>::B<int> and A<int>::B<U> have depth one, if
333    they are instantiations, not specializations.
334
335    This function is guaranteed to return 0 if passed NULL_TREE so
336    that, for example, `template_class_depth (current_class_type)' is
337    always safe.  */
338
339 int
340 template_class_depth (tree type)
341 {
342   int depth;
343
344   for (depth = 0;
345        type && TREE_CODE (type) != NAMESPACE_DECL;
346        type = (TREE_CODE (type) == FUNCTION_DECL)
347          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
348     {
349       tree tinfo = get_template_info (type);
350
351       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
352           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
353         ++depth;
354     }
355
356   return depth;
357 }
358
359 /* Subroutine of maybe_begin_member_template_processing.
360    Returns true if processing DECL needs us to push template parms.  */
361
362 static bool
363 inline_needs_template_parms (tree decl)
364 {
365   if (! DECL_TEMPLATE_INFO (decl))
366     return false;
367
368   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
369           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
370 }
371
372 /* Subroutine of maybe_begin_member_template_processing.
373    Push the template parms in PARMS, starting from LEVELS steps into the
374    chain, and ending at the beginning, since template parms are listed
375    innermost first.  */
376
377 static void
378 push_inline_template_parms_recursive (tree parmlist, int levels)
379 {
380   tree parms = TREE_VALUE (parmlist);
381   int i;
382
383   if (levels > 1)
384     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
385
386   ++processing_template_decl;
387   current_template_parms
388     = tree_cons (size_int (processing_template_decl),
389                  parms, current_template_parms);
390   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
391
392   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
393                NULL);
394   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
395     {
396       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
397
398       if (parm == error_mark_node)
399         continue;
400
401       gcc_assert (DECL_P (parm));
402
403       switch (TREE_CODE (parm))
404         {
405         case TYPE_DECL:
406         case TEMPLATE_DECL:
407           pushdecl (parm);
408           break;
409
410         case PARM_DECL:
411           {
412             /* Make a CONST_DECL as is done in process_template_parm.
413                It is ugly that we recreate this here; the original
414                version built in process_template_parm is no longer
415                available.  */
416             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
417                                     CONST_DECL, DECL_NAME (parm),
418                                     TREE_TYPE (parm));
419             DECL_ARTIFICIAL (decl) = 1;
420             TREE_CONSTANT (decl) = 1;
421             TREE_READONLY (decl) = 1;
422             DECL_INITIAL (decl) = DECL_INITIAL (parm);
423             SET_DECL_TEMPLATE_PARM_P (decl);
424             pushdecl (decl);
425           }
426           break;
427
428         default:
429           gcc_unreachable ();
430         }
431     }
432 }
433
434 /* Restore the template parameter context for a member template or
435    a friend template defined in a class definition.  */
436
437 void
438 maybe_begin_member_template_processing (tree decl)
439 {
440   tree parms;
441   int levels = 0;
442
443   if (inline_needs_template_parms (decl))
444     {
445       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
446       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
447
448       if (DECL_TEMPLATE_SPECIALIZATION (decl))
449         {
450           --levels;
451           parms = TREE_CHAIN (parms);
452         }
453
454       push_inline_template_parms_recursive (parms, levels);
455     }
456
457   /* Remember how many levels of template parameters we pushed so that
458      we can pop them later.  */
459   VEC_safe_push (int, heap, inline_parm_levels, levels);
460 }
461
462 /* Undo the effects of maybe_begin_member_template_processing.  */
463
464 void
465 maybe_end_member_template_processing (void)
466 {
467   int i;
468   int last;
469
470   if (VEC_length (int, inline_parm_levels) == 0)
471     return;
472
473   last = VEC_pop (int, inline_parm_levels);
474   for (i = 0; i < last; ++i)
475     {
476       --processing_template_decl;
477       current_template_parms = TREE_CHAIN (current_template_parms);
478       poplevel (0, 0, 0);
479     }
480 }
481
482 /* Return a new template argument vector which contains all of ARGS,
483    but has as its innermost set of arguments the EXTRA_ARGS.  */
484
485 static tree
486 add_to_template_args (tree args, tree extra_args)
487 {
488   tree new_args;
489   int extra_depth;
490   int i;
491   int j;
492
493   if (args == NULL_TREE)
494     return extra_args;
495
496   extra_depth = TMPL_ARGS_DEPTH (extra_args);
497   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
498
499   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
500     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
501
502   for (j = 1; j <= extra_depth; ++j, ++i)
503     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
504
505   return new_args;
506 }
507
508 /* Like add_to_template_args, but only the outermost ARGS are added to
509    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
510    (EXTRA_ARGS) levels are added.  This function is used to combine
511    the template arguments from a partial instantiation with the
512    template arguments used to attain the full instantiation from the
513    partial instantiation.  */
514
515 static tree
516 add_outermost_template_args (tree args, tree extra_args)
517 {
518   tree new_args;
519
520   /* If there are more levels of EXTRA_ARGS than there are ARGS,
521      something very fishy is going on.  */
522   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
523
524   /* If *all* the new arguments will be the EXTRA_ARGS, just return
525      them.  */
526   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
527     return extra_args;
528
529   /* For the moment, we make ARGS look like it contains fewer levels.  */
530   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
531
532   new_args = add_to_template_args (args, extra_args);
533
534   /* Now, we restore ARGS to its full dimensions.  */
535   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
536
537   return new_args;
538 }
539
540 /* Return the N levels of innermost template arguments from the ARGS.  */
541
542 tree
543 get_innermost_template_args (tree args, int n)
544 {
545   tree new_args;
546   int extra_levels;
547   int i;
548
549   gcc_assert (n >= 0);
550
551   /* If N is 1, just return the innermost set of template arguments.  */
552   if (n == 1)
553     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
554
555   /* If we're not removing anything, just return the arguments we were
556      given.  */
557   extra_levels = TMPL_ARGS_DEPTH (args) - n;
558   gcc_assert (extra_levels >= 0);
559   if (extra_levels == 0)
560     return args;
561
562   /* Make a new set of arguments, not containing the outer arguments.  */
563   new_args = make_tree_vec (n);
564   for (i = 1; i <= n; ++i)
565     SET_TMPL_ARGS_LEVEL (new_args, i,
566                          TMPL_ARGS_LEVEL (args, i + extra_levels));
567
568   return new_args;
569 }
570
571 /* The inverse of get_innermost_template_args: Return all but the innermost
572    EXTRA_LEVELS levels of template arguments from the ARGS.  */
573
574 static tree
575 strip_innermost_template_args (tree args, int extra_levels)
576 {
577   tree new_args;
578   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
579   int i;
580
581   gcc_assert (n >= 0);
582
583   /* If N is 1, just return the outermost set of template arguments.  */
584   if (n == 1)
585     return TMPL_ARGS_LEVEL (args, 1);
586
587   /* If we're not removing anything, just return the arguments we were
588      given.  */
589   gcc_assert (extra_levels >= 0);
590   if (extra_levels == 0)
591     return args;
592
593   /* Make a new set of arguments, not containing the inner arguments.  */
594   new_args = make_tree_vec (n);
595   for (i = 1; i <= n; ++i)
596     SET_TMPL_ARGS_LEVEL (new_args, i,
597                          TMPL_ARGS_LEVEL (args, i));
598
599   return new_args;
600 }
601
602 /* We've got a template header coming up; push to a new level for storing
603    the parms.  */
604
605 void
606 begin_template_parm_list (void)
607 {
608   /* We use a non-tag-transparent scope here, which causes pushtag to
609      put tags in this scope, rather than in the enclosing class or
610      namespace scope.  This is the right thing, since we want
611      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
612      global template class, push_template_decl handles putting the
613      TEMPLATE_DECL into top-level scope.  For a nested template class,
614      e.g.:
615
616        template <class T> struct S1 {
617          template <class T> struct S2 {};
618        };
619
620      pushtag contains special code to call pushdecl_with_scope on the
621      TEMPLATE_DECL for S2.  */
622   begin_scope (sk_template_parms, NULL);
623   ++processing_template_decl;
624   ++processing_template_parmlist;
625   note_template_header (0);
626 }
627
628 /* This routine is called when a specialization is declared.  If it is
629    invalid to declare a specialization here, an error is reported and
630    false is returned, otherwise this routine will return true.  */
631
632 static bool
633 check_specialization_scope (void)
634 {
635   tree scope = current_scope ();
636
637   /* [temp.expl.spec]
638
639      An explicit specialization shall be declared in the namespace of
640      which the template is a member, or, for member templates, in the
641      namespace of which the enclosing class or enclosing class
642      template is a member.  An explicit specialization of a member
643      function, member class or static data member of a class template
644      shall be declared in the namespace of which the class template
645      is a member.  */
646   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
647     {
648       error ("explicit specialization in non-namespace scope %qD", scope);
649       return false;
650     }
651
652   /* [temp.expl.spec]
653
654      In an explicit specialization declaration for a member of a class
655      template or a member template that appears in namespace scope,
656      the member template and some of its enclosing class templates may
657      remain unspecialized, except that the declaration shall not
658      explicitly specialize a class member template if its enclosing
659      class templates are not explicitly specialized as well.  */
660   if (current_template_parms)
661     {
662       error ("enclosing class templates are not explicitly specialized");
663       return false;
664     }
665
666   return true;
667 }
668
669 /* We've just seen template <>.  */
670
671 bool
672 begin_specialization (void)
673 {
674   begin_scope (sk_template_spec, NULL);
675   note_template_header (1);
676   return check_specialization_scope ();
677 }
678
679 /* Called at then end of processing a declaration preceded by
680    template<>.  */
681
682 void
683 end_specialization (void)
684 {
685   finish_scope ();
686   reset_specialization ();
687 }
688
689 /* Any template <>'s that we have seen thus far are not referring to a
690    function specialization.  */
691
692 void
693 reset_specialization (void)
694 {
695   processing_specialization = 0;
696   template_header_count = 0;
697 }
698
699 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
700    it was of the form template <>.  */
701
702 static void
703 note_template_header (int specialization)
704 {
705   processing_specialization = specialization;
706   template_header_count++;
707 }
708
709 /* We're beginning an explicit instantiation.  */
710
711 void
712 begin_explicit_instantiation (void)
713 {
714   gcc_assert (!processing_explicit_instantiation);
715   processing_explicit_instantiation = true;
716 }
717
718
719 void
720 end_explicit_instantiation (void)
721 {
722   gcc_assert (processing_explicit_instantiation);
723   processing_explicit_instantiation = false;
724 }
725
726 /* An explicit specialization or partial specialization TMPL is being
727    declared.  Check that the namespace in which the specialization is
728    occurring is permissible.  Returns false iff it is invalid to
729    specialize TMPL in the current namespace.  */
730
731 static bool
732 check_specialization_namespace (tree tmpl)
733 {
734   tree tpl_ns = decl_namespace_context (tmpl);
735
736   /* [tmpl.expl.spec]
737
738      An explicit specialization shall be declared in the namespace of
739      which the template is a member, or, for member templates, in the
740      namespace of which the enclosing class or enclosing class
741      template is a member.  An explicit specialization of a member
742      function, member class or static data member of a class template
743      shall be declared in the namespace of which the class template is
744      a member.  */
745   if (current_scope() != DECL_CONTEXT (tmpl)
746       && !at_namespace_scope_p ())
747     {
748       error ("specialization of %qD must appear at namespace scope", tmpl);
749       return false;
750     }
751   if (is_associated_namespace (current_namespace, tpl_ns))
752     /* Same or super-using namespace.  */
753     return true;
754   else
755     {
756       permerror (input_location, "specialization of %qD in different namespace", tmpl);
757       permerror (input_location, "  from definition of %q+#D", tmpl);
758       return false;
759     }
760 }
761
762 /* SPEC is an explicit instantiation.  Check that it is valid to
763    perform this explicit instantiation in the current namespace.  */
764
765 static void
766 check_explicit_instantiation_namespace (tree spec)
767 {
768   tree ns;
769
770   /* DR 275: An explicit instantiation shall appear in an enclosing
771      namespace of its template.  */
772   ns = decl_namespace_context (spec);
773   if (!is_ancestor (current_namespace, ns))
774     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
775                "(which does not enclose namespace %qD)",
776                spec, current_namespace, ns);
777 }
778
779 /* The TYPE is being declared.  If it is a template type, that means it
780    is a partial specialization.  Do appropriate error-checking.  */
781
782 tree
783 maybe_process_partial_specialization (tree type)
784 {
785   tree context;
786
787   if (type == error_mark_node)
788     return error_mark_node;
789
790   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
791     {
792       error ("name of class shadows template template parameter %qD",
793              TYPE_NAME (type));
794       return error_mark_node;
795     }
796
797   context = TYPE_CONTEXT (type);
798
799   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
800     {
801       /* This is for ordinary explicit specialization and partial
802          specialization of a template class such as:
803
804            template <> class C<int>;
805
806          or:
807
808            template <class T> class C<T*>;
809
810          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
811
812       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
813           && !COMPLETE_TYPE_P (type))
814         {
815           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
816           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
817           if (processing_template_decl)
818             {
819               if (push_template_decl (TYPE_MAIN_DECL (type))
820                   == error_mark_node)
821                 return error_mark_node;
822             }
823         }
824       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
825         error ("specialization of %qT after instantiation", type);
826     }
827   else if (CLASS_TYPE_P (type)
828            && !CLASSTYPE_USE_TEMPLATE (type)
829            && CLASSTYPE_TEMPLATE_INFO (type)
830            && context && CLASS_TYPE_P (context)
831            && CLASSTYPE_TEMPLATE_INFO (context))
832     {
833       /* This is for an explicit specialization of member class
834          template according to [temp.expl.spec/18]:
835
836            template <> template <class U> class C<int>::D;
837
838          The context `C<int>' must be an implicit instantiation.
839          Otherwise this is just a member class template declared
840          earlier like:
841
842            template <> class C<int> { template <class U> class D; };
843            template <> template <class U> class C<int>::D;
844
845          In the first case, `C<int>::D' is a specialization of `C<T>::D'
846          while in the second case, `C<int>::D' is a primary template
847          and `C<T>::D' may not exist.  */
848
849       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
850           && !COMPLETE_TYPE_P (type))
851         {
852           tree t;
853           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
854
855           if (current_namespace
856               != decl_namespace_context (tmpl))
857             {
858               permerror (input_location, "specializing %q#T in different namespace", type);
859               permerror (input_location, "  from definition of %q+#D", tmpl);
860             }
861
862           /* Check for invalid specialization after instantiation:
863
864                template <> template <> class C<int>::D<int>;
865                template <> template <class U> class C<int>::D;  */
866
867           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
868                t; t = TREE_CHAIN (t))
869             {
870               tree inst = TREE_VALUE (t);
871               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
872                 {
873                   /* We already have a full specialization of this partial
874                      instantiation.  Reassign it to the new member
875                      specialization template.  */
876                   spec_entry elt;
877                   spec_entry **slot;
878
879                   elt.tmpl = most_general_template (tmpl);
880                   elt.args = CLASSTYPE_TI_ARGS (inst);
881                   elt.spec = inst;
882
883                   htab_remove_elt (type_specializations, &elt);
884
885                   elt.tmpl = tmpl;
886                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
887
888                   slot = (spec_entry **)
889                     htab_find_slot (type_specializations, &elt, INSERT);
890                   *slot = ggc_alloc_spec_entry ();
891                   **slot = elt;
892                 }
893               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
894                 /* But if we've had an implicit instantiation, that's a
895                    problem ([temp.expl.spec]/6).  */
896                 error ("specialization %qT after instantiation %qT",
897                        type, inst);
898             }
899
900           /* Mark TYPE as a specialization.  And as a result, we only
901              have one level of template argument for the innermost
902              class template.  */
903           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
904           CLASSTYPE_TI_ARGS (type)
905             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
906         }
907     }
908   else if (processing_specialization)
909     {
910       error ("explicit specialization of non-template %qT", type);
911       return error_mark_node;
912     }
913
914   return type;
915 }
916
917 /* Returns nonzero if we can optimize the retrieval of specializations
918    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
919    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
920
921 static inline bool
922 optimize_specialization_lookup_p (tree tmpl)
923 {
924   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
925           && DECL_CLASS_SCOPE_P (tmpl)
926           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
927              parameter.  */
928           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
929           /* The optimized lookup depends on the fact that the
930              template arguments for the member function template apply
931              purely to the containing class, which is not true if the
932              containing class is an explicit or partial
933              specialization.  */
934           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
935           && !DECL_MEMBER_TEMPLATE_P (tmpl)
936           && !DECL_CONV_FN_P (tmpl)
937           /* It is possible to have a template that is not a member
938              template and is not a member of a template class:
939
940              template <typename T>
941              struct S { friend A::f(); };
942
943              Here, the friend function is a template, but the context does
944              not have template information.  The optimized lookup relies
945              on having ARGS be the template arguments for both the class
946              and the function template.  */
947           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
948 }
949
950 /* Retrieve the specialization (in the sense of [temp.spec] - a
951    specialization is either an instantiation or an explicit
952    specialization) of TMPL for the given template ARGS.  If there is
953    no such specialization, return NULL_TREE.  The ARGS are a vector of
954    arguments, or a vector of vectors of arguments, in the case of
955    templates with more than one level of parameters.
956
957    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
958    then we search for a partial specialization matching ARGS.  This
959    parameter is ignored if TMPL is not a class template.  */
960
961 static tree
962 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
963 {
964   if (args == error_mark_node)
965     return NULL_TREE;
966
967   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
968
969   /* There should be as many levels of arguments as there are
970      levels of parameters.  */
971   gcc_assert (TMPL_ARGS_DEPTH (args)
972               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
973
974   if (optimize_specialization_lookup_p (tmpl))
975     {
976       tree class_template;
977       tree class_specialization;
978       VEC(tree,gc) *methods;
979       tree fns;
980       int idx;
981
982       /* The template arguments actually apply to the containing
983          class.  Find the class specialization with those
984          arguments.  */
985       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
986       class_specialization
987         = retrieve_specialization (class_template, args, 0);
988       if (!class_specialization)
989         return NULL_TREE;
990       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
991          for the specialization.  */
992       idx = class_method_index_for_fn (class_specialization, tmpl);
993       if (idx == -1)
994         return NULL_TREE;
995       /* Iterate through the methods with the indicated name, looking
996          for the one that has an instance of TMPL.  */
997       methods = CLASSTYPE_METHOD_VEC (class_specialization);
998       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
999         {
1000           tree fn = OVL_CURRENT (fns);
1001           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1002               /* using-declarations can add base methods to the method vec,
1003                  and we don't want those here.  */
1004               && DECL_CONTEXT (fn) == class_specialization)
1005             return fn;
1006         }
1007       return NULL_TREE;
1008     }
1009   else
1010     {
1011       spec_entry *found;
1012       spec_entry elt;
1013       htab_t specializations;
1014
1015       elt.tmpl = tmpl;
1016       elt.args = args;
1017       elt.spec = NULL_TREE;
1018
1019       if (DECL_CLASS_TEMPLATE_P (tmpl))
1020         specializations = type_specializations;
1021       else
1022         specializations = decl_specializations;
1023
1024       if (hash == 0)
1025         hash = hash_specialization (&elt);
1026       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1027       if (found)
1028         return found->spec;
1029     }
1030
1031   return NULL_TREE;
1032 }
1033
1034 /* Like retrieve_specialization, but for local declarations.  */
1035
1036 static tree
1037 retrieve_local_specialization (tree tmpl)
1038 {
1039   tree spec;
1040
1041   if (local_specializations == NULL)
1042     return NULL_TREE;
1043
1044   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1045                                      htab_hash_pointer (tmpl));
1046   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1047 }
1048
1049 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1050
1051 int
1052 is_specialization_of (tree decl, tree tmpl)
1053 {
1054   tree t;
1055
1056   if (TREE_CODE (decl) == FUNCTION_DECL)
1057     {
1058       for (t = decl;
1059            t != NULL_TREE;
1060            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1061         if (t == tmpl)
1062           return 1;
1063     }
1064   else
1065     {
1066       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1067
1068       for (t = TREE_TYPE (decl);
1069            t != NULL_TREE;
1070            t = CLASSTYPE_USE_TEMPLATE (t)
1071              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1072         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1073           return 1;
1074     }
1075
1076   return 0;
1077 }
1078
1079 /* Returns nonzero iff DECL is a specialization of friend declaration
1080    FRIEND_DECL according to [temp.friend].  */
1081
1082 bool
1083 is_specialization_of_friend (tree decl, tree friend_decl)
1084 {
1085   bool need_template = true;
1086   int template_depth;
1087
1088   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1089               || TREE_CODE (decl) == TYPE_DECL);
1090
1091   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1092      of a template class, we want to check if DECL is a specialization
1093      if this.  */
1094   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1095       && DECL_TEMPLATE_INFO (friend_decl)
1096       && !DECL_USE_TEMPLATE (friend_decl))
1097     {
1098       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1099       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1100       need_template = false;
1101     }
1102   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1103            && !PRIMARY_TEMPLATE_P (friend_decl))
1104     need_template = false;
1105
1106   /* There is nothing to do if this is not a template friend.  */
1107   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1108     return false;
1109
1110   if (is_specialization_of (decl, friend_decl))
1111     return true;
1112
1113   /* [temp.friend/6]
1114      A member of a class template may be declared to be a friend of a
1115      non-template class.  In this case, the corresponding member of
1116      every specialization of the class template is a friend of the
1117      class granting friendship.
1118
1119      For example, given a template friend declaration
1120
1121        template <class T> friend void A<T>::f();
1122
1123      the member function below is considered a friend
1124
1125        template <> struct A<int> {
1126          void f();
1127        };
1128
1129      For this type of template friend, TEMPLATE_DEPTH below will be
1130      nonzero.  To determine if DECL is a friend of FRIEND, we first
1131      check if the enclosing class is a specialization of another.  */
1132
1133   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1134   if (template_depth
1135       && DECL_CLASS_SCOPE_P (decl)
1136       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1137                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1138     {
1139       /* Next, we check the members themselves.  In order to handle
1140          a few tricky cases, such as when FRIEND_DECL's are
1141
1142            template <class T> friend void A<T>::g(T t);
1143            template <class T> template <T t> friend void A<T>::h();
1144
1145          and DECL's are
1146
1147            void A<int>::g(int);
1148            template <int> void A<int>::h();
1149
1150          we need to figure out ARGS, the template arguments from
1151          the context of DECL.  This is required for template substitution
1152          of `T' in the function parameter of `g' and template parameter
1153          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1154
1155       tree context = DECL_CONTEXT (decl);
1156       tree args = NULL_TREE;
1157       int current_depth = 0;
1158
1159       while (current_depth < template_depth)
1160         {
1161           if (CLASSTYPE_TEMPLATE_INFO (context))
1162             {
1163               if (current_depth == 0)
1164                 args = TYPE_TI_ARGS (context);
1165               else
1166                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1167               current_depth++;
1168             }
1169           context = TYPE_CONTEXT (context);
1170         }
1171
1172       if (TREE_CODE (decl) == FUNCTION_DECL)
1173         {
1174           bool is_template;
1175           tree friend_type;
1176           tree decl_type;
1177           tree friend_args_type;
1178           tree decl_args_type;
1179
1180           /* Make sure that both DECL and FRIEND_DECL are templates or
1181              non-templates.  */
1182           is_template = DECL_TEMPLATE_INFO (decl)
1183                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1184           if (need_template ^ is_template)
1185             return false;
1186           else if (is_template)
1187             {
1188               /* If both are templates, check template parameter list.  */
1189               tree friend_parms
1190                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1191                                          args, tf_none);
1192               if (!comp_template_parms
1193                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1194                       friend_parms))
1195                 return false;
1196
1197               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1198             }
1199           else
1200             decl_type = TREE_TYPE (decl);
1201
1202           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1203                                               tf_none, NULL_TREE);
1204           if (friend_type == error_mark_node)
1205             return false;
1206
1207           /* Check if return types match.  */
1208           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1209             return false;
1210
1211           /* Check if function parameter types match, ignoring the
1212              `this' parameter.  */
1213           friend_args_type = TYPE_ARG_TYPES (friend_type);
1214           decl_args_type = TYPE_ARG_TYPES (decl_type);
1215           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1216             friend_args_type = TREE_CHAIN (friend_args_type);
1217           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1218             decl_args_type = TREE_CHAIN (decl_args_type);
1219
1220           return compparms (decl_args_type, friend_args_type);
1221         }
1222       else
1223         {
1224           /* DECL is a TYPE_DECL */
1225           bool is_template;
1226           tree decl_type = TREE_TYPE (decl);
1227
1228           /* Make sure that both DECL and FRIEND_DECL are templates or
1229              non-templates.  */
1230           is_template
1231             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1232               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1233
1234           if (need_template ^ is_template)
1235             return false;
1236           else if (is_template)
1237             {
1238               tree friend_parms;
1239               /* If both are templates, check the name of the two
1240                  TEMPLATE_DECL's first because is_friend didn't.  */
1241               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1242                   != DECL_NAME (friend_decl))
1243                 return false;
1244
1245               /* Now check template parameter list.  */
1246               friend_parms
1247                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1248                                          args, tf_none);
1249               return comp_template_parms
1250                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1251                  friend_parms);
1252             }
1253           else
1254             return (DECL_NAME (decl)
1255                     == DECL_NAME (friend_decl));
1256         }
1257     }
1258   return false;
1259 }
1260
1261 /* Register the specialization SPEC as a specialization of TMPL with
1262    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1263    is actually just a friend declaration.  Returns SPEC, or an
1264    equivalent prior declaration, if available.  */
1265
1266 static tree
1267 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1268                          hashval_t hash)
1269 {
1270   tree fn;
1271   spec_entry **slot = NULL;
1272   spec_entry elt;
1273
1274   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1275
1276   if (TREE_CODE (spec) == FUNCTION_DECL
1277       && uses_template_parms (DECL_TI_ARGS (spec)))
1278     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1279        register it; we want the corresponding TEMPLATE_DECL instead.
1280        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1281        the more obvious `uses_template_parms (spec)' to avoid problems
1282        with default function arguments.  In particular, given
1283        something like this:
1284
1285           template <class T> void f(T t1, T t = T())
1286
1287        the default argument expression is not substituted for in an
1288        instantiation unless and until it is actually needed.  */
1289     return spec;
1290
1291   if (optimize_specialization_lookup_p (tmpl))
1292     /* We don't put these specializations in the hash table, but we might
1293        want to give an error about a mismatch.  */
1294     fn = retrieve_specialization (tmpl, args, 0);
1295   else
1296     {
1297       elt.tmpl = tmpl;
1298       elt.args = args;
1299       elt.spec = spec;
1300
1301       if (hash == 0)
1302         hash = hash_specialization (&elt);
1303
1304       slot = (spec_entry **)
1305         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1306       if (*slot)
1307         fn = (*slot)->spec;
1308       else
1309         fn = NULL_TREE;
1310     }
1311
1312   /* We can sometimes try to re-register a specialization that we've
1313      already got.  In particular, regenerate_decl_from_template calls
1314      duplicate_decls which will update the specialization list.  But,
1315      we'll still get called again here anyhow.  It's more convenient
1316      to simply allow this than to try to prevent it.  */
1317   if (fn == spec)
1318     return spec;
1319   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1320     {
1321       if (DECL_TEMPLATE_INSTANTIATION (fn))
1322         {
1323           if (DECL_ODR_USED (fn)
1324               || DECL_EXPLICIT_INSTANTIATION (fn))
1325             {
1326               error ("specialization of %qD after instantiation",
1327                      fn);
1328               return error_mark_node;
1329             }
1330           else
1331             {
1332               tree clone;
1333               /* This situation should occur only if the first
1334                  specialization is an implicit instantiation, the
1335                  second is an explicit specialization, and the
1336                  implicit instantiation has not yet been used.  That
1337                  situation can occur if we have implicitly
1338                  instantiated a member function and then specialized
1339                  it later.
1340
1341                  We can also wind up here if a friend declaration that
1342                  looked like an instantiation turns out to be a
1343                  specialization:
1344
1345                    template <class T> void foo(T);
1346                    class S { friend void foo<>(int) };
1347                    template <> void foo(int);
1348
1349                  We transform the existing DECL in place so that any
1350                  pointers to it become pointers to the updated
1351                  declaration.
1352
1353                  If there was a definition for the template, but not
1354                  for the specialization, we want this to look as if
1355                  there were no definition, and vice versa.  */
1356               DECL_INITIAL (fn) = NULL_TREE;
1357               duplicate_decls (spec, fn, is_friend);
1358               /* The call to duplicate_decls will have applied
1359                  [temp.expl.spec]:
1360
1361                    An explicit specialization of a function template
1362                    is inline only if it is explicitly declared to be,
1363                    and independently of whether its function template
1364                    is.
1365
1366                 to the primary function; now copy the inline bits to
1367                 the various clones.  */
1368               FOR_EACH_CLONE (clone, fn)
1369                 {
1370                   DECL_DECLARED_INLINE_P (clone)
1371                     = DECL_DECLARED_INLINE_P (fn);
1372                   DECL_SOURCE_LOCATION (clone)
1373                     = DECL_SOURCE_LOCATION (fn);
1374                 }
1375               check_specialization_namespace (fn);
1376
1377               return fn;
1378             }
1379         }
1380       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1381         {
1382           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1383             /* Dup decl failed, but this is a new definition. Set the
1384                line number so any errors match this new
1385                definition.  */
1386             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1387
1388           return fn;
1389         }
1390     }
1391   else if (fn)
1392     return duplicate_decls (spec, fn, is_friend);
1393
1394   /* A specialization must be declared in the same namespace as the
1395      template it is specializing.  */
1396   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1397       && !check_specialization_namespace (tmpl))
1398     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1399
1400   if (!optimize_specialization_lookup_p (tmpl))
1401     {
1402       gcc_assert (tmpl && args && spec);
1403       *slot = ggc_alloc_spec_entry ();
1404       **slot = elt;
1405       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1406           && PRIMARY_TEMPLATE_P (tmpl)
1407           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1408         /* TMPL is a forward declaration of a template function; keep a list
1409            of all specializations in case we need to reassign them to a friend
1410            template later in tsubst_friend_function.  */
1411         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1412           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1413     }
1414
1415   return spec;
1416 }
1417
1418 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1419    TMPL and ARGS members, ignores SPEC.  */
1420
1421 static int
1422 eq_specializations (const void *p1, const void *p2)
1423 {
1424   const spec_entry *e1 = (const spec_entry *)p1;
1425   const spec_entry *e2 = (const spec_entry *)p2;
1426
1427   return (e1->tmpl == e2->tmpl
1428           && comp_template_args (e1->args, e2->args));
1429 }
1430
1431 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1432
1433 static hashval_t
1434 hash_tmpl_and_args (tree tmpl, tree args)
1435 {
1436   hashval_t val = DECL_UID (tmpl);
1437   return iterative_hash_template_arg (args, val);
1438 }
1439
1440 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1441    ignoring SPEC.  */
1442
1443 static hashval_t
1444 hash_specialization (const void *p)
1445 {
1446   const spec_entry *e = (const spec_entry *)p;
1447   return hash_tmpl_and_args (e->tmpl, e->args);
1448 }
1449
1450 /* Recursively calculate a hash value for a template argument ARG, for use
1451    in the hash tables of template specializations.  */
1452
1453 static hashval_t
1454 iterative_hash_template_arg (tree arg, hashval_t val)
1455 {
1456   unsigned HOST_WIDE_INT i;
1457   enum tree_code code;
1458   char tclass;
1459
1460   if (arg == NULL_TREE)
1461     return iterative_hash_object (arg, val);
1462
1463   if (!TYPE_P (arg))
1464     STRIP_NOPS (arg);
1465
1466   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1467     /* We can get one of these when re-hashing a previous entry in the middle
1468        of substituting into a pack expansion.  Just look through it.  */
1469     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1470
1471   code = TREE_CODE (arg);
1472   tclass = TREE_CODE_CLASS (code);
1473
1474   val = iterative_hash_object (code, val);
1475
1476   switch (code)
1477     {
1478     case ERROR_MARK:
1479       return val;
1480
1481     case IDENTIFIER_NODE:
1482       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1483
1484     case TREE_VEC:
1485       {
1486         int i, len = TREE_VEC_LENGTH (arg);
1487         for (i = 0; i < len; ++i)
1488           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1489         return val;
1490       }
1491
1492     case TYPE_PACK_EXPANSION:
1493     case EXPR_PACK_EXPANSION:
1494       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1495
1496     case TYPE_ARGUMENT_PACK:
1497     case NONTYPE_ARGUMENT_PACK:
1498       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1499
1500     case TREE_LIST:
1501       for (; arg; arg = TREE_CHAIN (arg))
1502         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1503       return val;
1504
1505     case OVERLOAD:
1506       for (; arg; arg = OVL_CHAIN (arg))
1507         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1508       return val;
1509
1510     case CONSTRUCTOR:
1511       {
1512         tree field, value;
1513         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1514           {
1515             val = iterative_hash_template_arg (field, val);
1516             val = iterative_hash_template_arg (value, val);
1517           }
1518         return val;
1519       }
1520
1521     case PARM_DECL:
1522       if (!DECL_ARTIFICIAL (arg))
1523         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1524       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1525
1526     case TARGET_EXPR:
1527       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1528
1529     case PTRMEM_CST:
1530       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1531       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1532
1533     case TEMPLATE_PARM_INDEX:
1534       val = iterative_hash_template_arg
1535         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1536       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1537       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1538
1539     case TRAIT_EXPR:
1540       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1541       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1542       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1543
1544     case BASELINK:
1545       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1546                                          val);
1547       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1548                                           val);
1549
1550     case MODOP_EXPR:
1551       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1552       code = TREE_CODE (TREE_OPERAND (arg, 1));
1553       val = iterative_hash_object (code, val);
1554       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1555
1556     case ARRAY_TYPE:
1557       /* layout_type sets structural equality for arrays of
1558          incomplete type, so we can't rely on the canonical type
1559          for hashing.  */
1560       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1561       return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
1562
1563     case LAMBDA_EXPR:
1564       /* A lambda can't appear in a template arg, but don't crash on
1565          erroneous input.  */
1566       gcc_assert (seen_error ());
1567       return val;
1568
1569     case CAST_EXPR:
1570     case STATIC_CAST_EXPR:
1571     case REINTERPRET_CAST_EXPR:
1572     case CONST_CAST_EXPR:
1573     case DYNAMIC_CAST_EXPR:
1574     case NEW_EXPR:
1575       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1576       /* Now hash operands as usual.  */
1577       break;
1578
1579     default:
1580       break;
1581     }
1582
1583   switch (tclass)
1584     {
1585     case tcc_type:
1586       if (TYPE_CANONICAL (arg))
1587         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1588                                       val);
1589       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1590         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1591       /* Otherwise just compare the types during lookup.  */
1592       return val;
1593
1594     case tcc_declaration:
1595     case tcc_constant:
1596       return iterative_hash_expr (arg, val);
1597
1598     default:
1599       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1600       {
1601         unsigned n = TREE_OPERAND_LENGTH (arg);
1602         for (i = 0; i < n; ++i)
1603           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1604         return val;
1605       }
1606     }
1607   gcc_unreachable ();
1608   return 0;
1609 }
1610
1611 /* Unregister the specialization SPEC as a specialization of TMPL.
1612    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1613    if the SPEC was listed as a specialization of TMPL.
1614
1615    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1616
1617 bool
1618 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1619 {
1620   spec_entry **slot;
1621   spec_entry elt;
1622
1623   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1624   elt.args = TI_ARGS (tinfo);
1625   elt.spec = NULL_TREE;
1626
1627   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1628   if (*slot)
1629     {
1630       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1631       gcc_assert (new_spec != NULL_TREE);
1632       (*slot)->spec = new_spec;
1633       return 1;
1634     }
1635
1636   return 0;
1637 }
1638
1639 /* Compare an entry in the local specializations hash table P1 (which
1640    is really a pointer to a TREE_LIST) with P2 (which is really a
1641    DECL).  */
1642
1643 static int
1644 eq_local_specializations (const void *p1, const void *p2)
1645 {
1646   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1647 }
1648
1649 /* Hash P1, an entry in the local specializations table.  */
1650
1651 static hashval_t
1652 hash_local_specialization (const void* p1)
1653 {
1654   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1655 }
1656
1657 /* Like register_specialization, but for local declarations.  We are
1658    registering SPEC, an instantiation of TMPL.  */
1659
1660 static void
1661 register_local_specialization (tree spec, tree tmpl)
1662 {
1663   void **slot;
1664
1665   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1666                                    htab_hash_pointer (tmpl), INSERT);
1667   *slot = build_tree_list (spec, tmpl);
1668 }
1669
1670 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1671    specialized class.  */
1672
1673 bool
1674 explicit_class_specialization_p (tree type)
1675 {
1676   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1677     return false;
1678   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1679 }
1680
1681 /* Print the list of functions at FNS, going through all the overloads
1682    for each element of the list.  Alternatively, FNS can not be a
1683    TREE_LIST, in which case it will be printed together with all the
1684    overloads.
1685
1686    MORE and *STR should respectively be FALSE and NULL when the function
1687    is called from the outside.  They are used internally on recursive
1688    calls.  print_candidates manages the two parameters and leaves NULL
1689    in *STR when it ends.  */
1690
1691 static void
1692 print_candidates_1 (tree fns, bool more, const char **str)
1693 {
1694   tree fn, fn2;
1695   char *spaces = NULL;
1696
1697   for (fn = fns; fn; fn = OVL_NEXT (fn))
1698     if (TREE_CODE (fn) == TREE_LIST)
1699       {
1700         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1701         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1702           print_candidates_1 (TREE_VALUE (fn2),
1703                               TREE_CHAIN (fn2) || more, str);
1704       }
1705     else
1706       {
1707         if (!*str)
1708           {
1709             /* Pick the prefix string.  */
1710             if (!more && !OVL_NEXT (fns))
1711               {
1712                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1713                 continue;
1714               }
1715
1716             *str = _("candidates are:");
1717             spaces = get_spaces (*str);
1718           }
1719         error ("%s %+#D", *str, OVL_CURRENT (fn));
1720         *str = spaces ? spaces : *str;
1721       }
1722
1723   if (!more)
1724     {
1725       free (spaces);
1726       *str = NULL;
1727     }
1728 }
1729
1730 /* Print the list of candidate FNS in an error message.  */
1731
1732 void
1733 print_candidates (tree fns)
1734 {
1735   const char *str = NULL;
1736   print_candidates_1 (fns, false, &str);
1737   gcc_assert (str == NULL);
1738 }
1739
1740 /* Returns the template (one of the functions given by TEMPLATE_ID)
1741    which can be specialized to match the indicated DECL with the
1742    explicit template args given in TEMPLATE_ID.  The DECL may be
1743    NULL_TREE if none is available.  In that case, the functions in
1744    TEMPLATE_ID are non-members.
1745
1746    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1747    specialization of a member template.
1748
1749    The TEMPLATE_COUNT is the number of references to qualifying
1750    template classes that appeared in the name of the function. See
1751    check_explicit_specialization for a more accurate description.
1752
1753    TSK indicates what kind of template declaration (if any) is being
1754    declared.  TSK_TEMPLATE indicates that the declaration given by
1755    DECL, though a FUNCTION_DECL, has template parameters, and is
1756    therefore a template function.
1757
1758    The template args (those explicitly specified and those deduced)
1759    are output in a newly created vector *TARGS_OUT.
1760
1761    If it is impossible to determine the result, an error message is
1762    issued.  The error_mark_node is returned to indicate failure.  */
1763
1764 static tree
1765 determine_specialization (tree template_id,
1766                           tree decl,
1767                           tree* targs_out,
1768                           int need_member_template,
1769                           int template_count,
1770                           tmpl_spec_kind tsk)
1771 {
1772   tree fns;
1773   tree targs;
1774   tree explicit_targs;
1775   tree candidates = NULL_TREE;
1776   /* A TREE_LIST of templates of which DECL may be a specialization.
1777      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1778      corresponding TREE_PURPOSE is the set of template arguments that,
1779      when used to instantiate the template, would produce a function
1780      with the signature of DECL.  */
1781   tree templates = NULL_TREE;
1782   int header_count;
1783   struct cp_binding_level *b;
1784
1785   *targs_out = NULL_TREE;
1786
1787   if (template_id == error_mark_node || decl == error_mark_node)
1788     return error_mark_node;
1789
1790   fns = TREE_OPERAND (template_id, 0);
1791   explicit_targs = TREE_OPERAND (template_id, 1);
1792
1793   if (fns == error_mark_node)
1794     return error_mark_node;
1795
1796   /* Check for baselinks.  */
1797   if (BASELINK_P (fns))
1798     fns = BASELINK_FUNCTIONS (fns);
1799
1800   if (!is_overloaded_fn (fns))
1801     {
1802       error ("%qD is not a function template", fns);
1803       return error_mark_node;
1804     }
1805
1806   /* Count the number of template headers specified for this
1807      specialization.  */
1808   header_count = 0;
1809   for (b = current_binding_level;
1810        b->kind == sk_template_parms;
1811        b = b->level_chain)
1812     ++header_count;
1813
1814   for (; fns; fns = OVL_NEXT (fns))
1815     {
1816       tree fn = OVL_CURRENT (fns);
1817
1818       if (TREE_CODE (fn) == TEMPLATE_DECL)
1819         {
1820           tree decl_arg_types;
1821           tree fn_arg_types;
1822
1823           /* In case of explicit specialization, we need to check if
1824              the number of template headers appearing in the specialization
1825              is correct. This is usually done in check_explicit_specialization,
1826              but the check done there cannot be exhaustive when specializing
1827              member functions. Consider the following code:
1828
1829              template <> void A<int>::f(int);
1830              template <> template <> void A<int>::f(int);
1831
1832              Assuming that A<int> is not itself an explicit specialization
1833              already, the first line specializes "f" which is a non-template
1834              member function, whilst the second line specializes "f" which
1835              is a template member function. So both lines are syntactically
1836              correct, and check_explicit_specialization does not reject
1837              them.
1838
1839              Here, we can do better, as we are matching the specialization
1840              against the declarations. We count the number of template
1841              headers, and we check if they match TEMPLATE_COUNT + 1
1842              (TEMPLATE_COUNT is the number of qualifying template classes,
1843              plus there must be another header for the member template
1844              itself).
1845
1846              Notice that if header_count is zero, this is not a
1847              specialization but rather a template instantiation, so there
1848              is no check we can perform here.  */
1849           if (header_count && header_count != template_count + 1)
1850             continue;
1851
1852           /* Check that the number of template arguments at the
1853              innermost level for DECL is the same as for FN.  */
1854           if (current_binding_level->kind == sk_template_parms
1855               && !current_binding_level->explicit_spec_p
1856               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1857                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1858                                       (current_template_parms))))
1859             continue;
1860
1861           /* DECL might be a specialization of FN.  */
1862           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1863           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1864
1865           /* For a non-static member function, we need to make sure
1866              that the const qualification is the same.  Since
1867              get_bindings does not try to merge the "this" parameter,
1868              we must do the comparison explicitly.  */
1869           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1870               && !same_type_p (TREE_VALUE (fn_arg_types),
1871                                TREE_VALUE (decl_arg_types)))
1872             continue;
1873
1874           /* Skip the "this" parameter and, for constructors of
1875              classes with virtual bases, the VTT parameter.  A
1876              full specialization of a constructor will have a VTT
1877              parameter, but a template never will.  */ 
1878           decl_arg_types 
1879             = skip_artificial_parms_for (decl, decl_arg_types);
1880           fn_arg_types 
1881             = skip_artificial_parms_for (fn, fn_arg_types);
1882
1883           /* Check that the number of function parameters matches.
1884              For example,
1885                template <class T> void f(int i = 0);
1886                template <> void f<int>();
1887              The specialization f<int> is invalid but is not caught
1888              by get_bindings below.  */
1889           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1890             continue;
1891
1892           /* Function templates cannot be specializations; there are
1893              no partial specializations of functions.  Therefore, if
1894              the type of DECL does not match FN, there is no
1895              match.  */
1896           if (tsk == tsk_template)
1897             {
1898               if (compparms (fn_arg_types, decl_arg_types))
1899                 candidates = tree_cons (NULL_TREE, fn, candidates);
1900               continue;
1901             }
1902
1903           /* See whether this function might be a specialization of this
1904              template.  */
1905           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1906
1907           if (!targs)
1908             /* We cannot deduce template arguments that when used to
1909                specialize TMPL will produce DECL.  */
1910             continue;
1911
1912           /* Save this template, and the arguments deduced.  */
1913           templates = tree_cons (targs, fn, templates);
1914         }
1915       else if (need_member_template)
1916         /* FN is an ordinary member function, and we need a
1917            specialization of a member template.  */
1918         ;
1919       else if (TREE_CODE (fn) != FUNCTION_DECL)
1920         /* We can get IDENTIFIER_NODEs here in certain erroneous
1921            cases.  */
1922         ;
1923       else if (!DECL_FUNCTION_MEMBER_P (fn))
1924         /* This is just an ordinary non-member function.  Nothing can
1925            be a specialization of that.  */
1926         ;
1927       else if (DECL_ARTIFICIAL (fn))
1928         /* Cannot specialize functions that are created implicitly.  */
1929         ;
1930       else
1931         {
1932           tree decl_arg_types;
1933
1934           /* This is an ordinary member function.  However, since
1935              we're here, we can assume it's enclosing class is a
1936              template class.  For example,
1937
1938                template <typename T> struct S { void f(); };
1939                template <> void S<int>::f() {}
1940
1941              Here, S<int>::f is a non-template, but S<int> is a
1942              template class.  If FN has the same type as DECL, we
1943              might be in business.  */
1944
1945           if (!DECL_TEMPLATE_INFO (fn))
1946             /* Its enclosing class is an explicit specialization
1947                of a template class.  This is not a candidate.  */
1948             continue;
1949
1950           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1951                             TREE_TYPE (TREE_TYPE (fn))))
1952             /* The return types differ.  */
1953             continue;
1954
1955           /* Adjust the type of DECL in case FN is a static member.  */
1956           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1957           if (DECL_STATIC_FUNCTION_P (fn)
1958               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1959             decl_arg_types = TREE_CHAIN (decl_arg_types);
1960
1961           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1962                          decl_arg_types))
1963             /* They match!  */
1964             candidates = tree_cons (NULL_TREE, fn, candidates);
1965         }
1966     }
1967
1968   if (templates && TREE_CHAIN (templates))
1969     {
1970       /* We have:
1971
1972            [temp.expl.spec]
1973
1974            It is possible for a specialization with a given function
1975            signature to be instantiated from more than one function
1976            template.  In such cases, explicit specification of the
1977            template arguments must be used to uniquely identify the
1978            function template specialization being specialized.
1979
1980          Note that here, there's no suggestion that we're supposed to
1981          determine which of the candidate templates is most
1982          specialized.  However, we, also have:
1983
1984            [temp.func.order]
1985
1986            Partial ordering of overloaded function template
1987            declarations is used in the following contexts to select
1988            the function template to which a function template
1989            specialization refers:
1990
1991            -- when an explicit specialization refers to a function
1992               template.
1993
1994          So, we do use the partial ordering rules, at least for now.
1995          This extension can only serve to make invalid programs valid,
1996          so it's safe.  And, there is strong anecdotal evidence that
1997          the committee intended the partial ordering rules to apply;
1998          the EDG front end has that behavior, and John Spicer claims
1999          that the committee simply forgot to delete the wording in
2000          [temp.expl.spec].  */
2001       tree tmpl = most_specialized_instantiation (templates);
2002       if (tmpl != error_mark_node)
2003         {
2004           templates = tmpl;
2005           TREE_CHAIN (templates) = NULL_TREE;
2006         }
2007     }
2008
2009   if (templates == NULL_TREE && candidates == NULL_TREE)
2010     {
2011       error ("template-id %qD for %q+D does not match any template "
2012              "declaration", template_id, decl);
2013       if (header_count && header_count != template_count + 1)
2014         inform (input_location, "saw %d %<template<>%>, need %d for "
2015                 "specializing a member function template",
2016                 header_count, template_count + 1);
2017       return error_mark_node;
2018     }
2019   else if ((templates && TREE_CHAIN (templates))
2020            || (candidates && TREE_CHAIN (candidates))
2021            || (templates && candidates))
2022     {
2023       error ("ambiguous template specialization %qD for %q+D",
2024              template_id, decl);
2025       candidates = chainon (candidates, templates);
2026       print_candidates (candidates);
2027       return error_mark_node;
2028     }
2029
2030   /* We have one, and exactly one, match.  */
2031   if (candidates)
2032     {
2033       tree fn = TREE_VALUE (candidates);
2034       *targs_out = copy_node (DECL_TI_ARGS (fn));
2035       /* DECL is a re-declaration or partial instantiation of a template
2036          function.  */
2037       if (TREE_CODE (fn) == TEMPLATE_DECL)
2038         return fn;
2039       /* It was a specialization of an ordinary member function in a
2040          template class.  */
2041       return DECL_TI_TEMPLATE (fn);
2042     }
2043
2044   /* It was a specialization of a template.  */
2045   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2046   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2047     {
2048       *targs_out = copy_node (targs);
2049       SET_TMPL_ARGS_LEVEL (*targs_out,
2050                            TMPL_ARGS_DEPTH (*targs_out),
2051                            TREE_PURPOSE (templates));
2052     }
2053   else
2054     *targs_out = TREE_PURPOSE (templates);
2055   return TREE_VALUE (templates);
2056 }
2057
2058 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2059    but with the default argument values filled in from those in the
2060    TMPL_TYPES.  */
2061
2062 static tree
2063 copy_default_args_to_explicit_spec_1 (tree spec_types,
2064                                       tree tmpl_types)
2065 {
2066   tree new_spec_types;
2067
2068   if (!spec_types)
2069     return NULL_TREE;
2070
2071   if (spec_types == void_list_node)
2072     return void_list_node;
2073
2074   /* Substitute into the rest of the list.  */
2075   new_spec_types =
2076     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2077                                           TREE_CHAIN (tmpl_types));
2078
2079   /* Add the default argument for this parameter.  */
2080   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2081                          TREE_VALUE (spec_types),
2082                          new_spec_types);
2083 }
2084
2085 /* DECL is an explicit specialization.  Replicate default arguments
2086    from the template it specializes.  (That way, code like:
2087
2088      template <class T> void f(T = 3);
2089      template <> void f(double);
2090      void g () { f (); }
2091
2092    works, as required.)  An alternative approach would be to look up
2093    the correct default arguments at the call-site, but this approach
2094    is consistent with how implicit instantiations are handled.  */
2095
2096 static void
2097 copy_default_args_to_explicit_spec (tree decl)
2098 {
2099   tree tmpl;
2100   tree spec_types;
2101   tree tmpl_types;
2102   tree new_spec_types;
2103   tree old_type;
2104   tree new_type;
2105   tree t;
2106   tree object_type = NULL_TREE;
2107   tree in_charge = NULL_TREE;
2108   tree vtt = NULL_TREE;
2109
2110   /* See if there's anything we need to do.  */
2111   tmpl = DECL_TI_TEMPLATE (decl);
2112   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2113   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2114     if (TREE_PURPOSE (t))
2115       break;
2116   if (!t)
2117     return;
2118
2119   old_type = TREE_TYPE (decl);
2120   spec_types = TYPE_ARG_TYPES (old_type);
2121
2122   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2123     {
2124       /* Remove the this pointer, but remember the object's type for
2125          CV quals.  */
2126       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2127       spec_types = TREE_CHAIN (spec_types);
2128       tmpl_types = TREE_CHAIN (tmpl_types);
2129
2130       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2131         {
2132           /* DECL may contain more parameters than TMPL due to the extra
2133              in-charge parameter in constructors and destructors.  */
2134           in_charge = spec_types;
2135           spec_types = TREE_CHAIN (spec_types);
2136         }
2137       if (DECL_HAS_VTT_PARM_P (decl))
2138         {
2139           vtt = spec_types;
2140           spec_types = TREE_CHAIN (spec_types);
2141         }
2142     }
2143
2144   /* Compute the merged default arguments.  */
2145   new_spec_types =
2146     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2147
2148   /* Compute the new FUNCTION_TYPE.  */
2149   if (object_type)
2150     {
2151       if (vtt)
2152         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2153                                          TREE_VALUE (vtt),
2154                                          new_spec_types);
2155
2156       if (in_charge)
2157         /* Put the in-charge parameter back.  */
2158         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2159                                          TREE_VALUE (in_charge),
2160                                          new_spec_types);
2161
2162       new_type = build_method_type_directly (object_type,
2163                                              TREE_TYPE (old_type),
2164                                              new_spec_types);
2165     }
2166   else
2167     new_type = build_function_type (TREE_TYPE (old_type),
2168                                     new_spec_types);
2169   new_type = cp_build_type_attribute_variant (new_type,
2170                                               TYPE_ATTRIBUTES (old_type));
2171   new_type = build_exception_variant (new_type,
2172                                       TYPE_RAISES_EXCEPTIONS (old_type));
2173   TREE_TYPE (decl) = new_type;
2174 }
2175
2176 /* Check to see if the function just declared, as indicated in
2177    DECLARATOR, and in DECL, is a specialization of a function
2178    template.  We may also discover that the declaration is an explicit
2179    instantiation at this point.
2180
2181    Returns DECL, or an equivalent declaration that should be used
2182    instead if all goes well.  Issues an error message if something is
2183    amiss.  Returns error_mark_node if the error is not easily
2184    recoverable.
2185
2186    FLAGS is a bitmask consisting of the following flags:
2187
2188    2: The function has a definition.
2189    4: The function is a friend.
2190
2191    The TEMPLATE_COUNT is the number of references to qualifying
2192    template classes that appeared in the name of the function.  For
2193    example, in
2194
2195      template <class T> struct S { void f(); };
2196      void S<int>::f();
2197
2198    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2199    classes are not counted in the TEMPLATE_COUNT, so that in
2200
2201      template <class T> struct S {};
2202      template <> struct S<int> { void f(); }
2203      template <> void S<int>::f();
2204
2205    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2206    invalid; there should be no template <>.)
2207
2208    If the function is a specialization, it is marked as such via
2209    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2210    is set up correctly, and it is added to the list of specializations
2211    for that template.  */
2212
2213 tree
2214 check_explicit_specialization (tree declarator,
2215                                tree decl,
2216                                int template_count,
2217                                int flags)
2218 {
2219   int have_def = flags & 2;
2220   int is_friend = flags & 4;
2221   int specialization = 0;
2222   int explicit_instantiation = 0;
2223   int member_specialization = 0;
2224   tree ctype = DECL_CLASS_CONTEXT (decl);
2225   tree dname = DECL_NAME (decl);
2226   tmpl_spec_kind tsk;
2227
2228   if (is_friend)
2229     {
2230       if (!processing_specialization)
2231         tsk = tsk_none;
2232       else
2233         tsk = tsk_excessive_parms;
2234     }
2235   else
2236     tsk = current_tmpl_spec_kind (template_count);
2237
2238   switch (tsk)
2239     {
2240     case tsk_none:
2241       if (processing_specialization)
2242         {
2243           specialization = 1;
2244           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2245         }
2246       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2247         {
2248           if (is_friend)
2249             /* This could be something like:
2250
2251                template <class T> void f(T);
2252                class S { friend void f<>(int); }  */
2253             specialization = 1;
2254           else
2255             {
2256               /* This case handles bogus declarations like template <>
2257                  template <class T> void f<int>(); */
2258
2259               error ("template-id %qD in declaration of primary template",
2260                      declarator);
2261               return decl;
2262             }
2263         }
2264       break;
2265
2266     case tsk_invalid_member_spec:
2267       /* The error has already been reported in
2268          check_specialization_scope.  */
2269       return error_mark_node;
2270
2271     case tsk_invalid_expl_inst:
2272       error ("template parameter list used in explicit instantiation");
2273
2274       /* Fall through.  */
2275
2276     case tsk_expl_inst:
2277       if (have_def)
2278         error ("definition provided for explicit instantiation");
2279
2280       explicit_instantiation = 1;
2281       break;
2282
2283     case tsk_excessive_parms:
2284     case tsk_insufficient_parms:
2285       if (tsk == tsk_excessive_parms)
2286         error ("too many template parameter lists in declaration of %qD",
2287                decl);
2288       else if (template_header_count)
2289         error("too few template parameter lists in declaration of %qD", decl);
2290       else
2291         error("explicit specialization of %qD must be introduced by "
2292               "%<template <>%>", decl);
2293
2294       /* Fall through.  */
2295     case tsk_expl_spec:
2296       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2297       if (ctype)
2298         member_specialization = 1;
2299       else
2300         specialization = 1;
2301       break;
2302
2303     case tsk_template:
2304       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2305         {
2306           /* This case handles bogus declarations like template <>
2307              template <class T> void f<int>(); */
2308
2309           if (uses_template_parms (declarator))
2310             error ("function template partial specialization %qD "
2311                    "is not allowed", declarator);
2312           else
2313             error ("template-id %qD in declaration of primary template",
2314                    declarator);
2315           return decl;
2316         }
2317
2318       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2319         /* This is a specialization of a member template, without
2320            specialization the containing class.  Something like:
2321
2322              template <class T> struct S {
2323                template <class U> void f (U);
2324              };
2325              template <> template <class U> void S<int>::f(U) {}
2326
2327            That's a specialization -- but of the entire template.  */
2328         specialization = 1;
2329       break;
2330
2331     default:
2332       gcc_unreachable ();
2333     }
2334
2335   if (specialization || member_specialization)
2336     {
2337       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2338       for (; t; t = TREE_CHAIN (t))
2339         if (TREE_PURPOSE (t))
2340           {
2341             permerror (input_location, 
2342                        "default argument specified in explicit specialization");
2343             break;
2344           }
2345     }
2346
2347   if (specialization || member_specialization || explicit_instantiation)
2348     {
2349       tree tmpl = NULL_TREE;
2350       tree targs = NULL_TREE;
2351
2352       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2353       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2354         {
2355           tree fns;
2356
2357           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2358           if (ctype)
2359             fns = dname;
2360           else
2361             {
2362               /* If there is no class context, the explicit instantiation
2363                  must be at namespace scope.  */
2364               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2365
2366               /* Find the namespace binding, using the declaration
2367                  context.  */
2368               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2369                                            false, true);
2370               if (fns == error_mark_node || !is_overloaded_fn (fns))
2371                 {
2372                   error ("%qD is not a template function", dname);
2373                   fns = error_mark_node;
2374                 }
2375               else
2376                 {
2377                   tree fn = OVL_CURRENT (fns);
2378                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2379                                                 CP_DECL_CONTEXT (fn)))
2380                     error ("%qD is not declared in %qD",
2381                            decl, current_namespace);
2382                 }
2383             }
2384
2385           declarator = lookup_template_function (fns, NULL_TREE);
2386         }
2387
2388       if (declarator == error_mark_node)
2389         return error_mark_node;
2390
2391       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2392         {
2393           if (!explicit_instantiation)
2394             /* A specialization in class scope.  This is invalid,
2395                but the error will already have been flagged by
2396                check_specialization_scope.  */
2397             return error_mark_node;
2398           else
2399             {
2400               /* It's not valid to write an explicit instantiation in
2401                  class scope, e.g.:
2402
2403                    class C { template void f(); }
2404
2405                    This case is caught by the parser.  However, on
2406                    something like:
2407
2408                    template class C { void f(); };
2409
2410                    (which is invalid) we can get here.  The error will be
2411                    issued later.  */
2412               ;
2413             }
2414
2415           return decl;
2416         }
2417       else if (ctype != NULL_TREE
2418                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2419                    IDENTIFIER_NODE))
2420         {
2421           /* Find the list of functions in ctype that have the same
2422              name as the declared function.  */
2423           tree name = TREE_OPERAND (declarator, 0);
2424           tree fns = NULL_TREE;
2425           int idx;
2426
2427           if (constructor_name_p (name, ctype))
2428             {
2429               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2430
2431               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2432                   : !CLASSTYPE_DESTRUCTORS (ctype))
2433                 {
2434                   /* From [temp.expl.spec]:
2435
2436                      If such an explicit specialization for the member
2437                      of a class template names an implicitly-declared
2438                      special member function (clause _special_), the
2439                      program is ill-formed.
2440
2441                      Similar language is found in [temp.explicit].  */
2442                   error ("specialization of implicitly-declared special member function");
2443                   return error_mark_node;
2444                 }
2445
2446               name = is_constructor ? ctor_identifier : dtor_identifier;
2447             }
2448
2449           if (!DECL_CONV_FN_P (decl))
2450             {
2451               idx = lookup_fnfields_1 (ctype, name);
2452               if (idx >= 0)
2453                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2454             }
2455           else
2456             {
2457               VEC(tree,gc) *methods;
2458               tree ovl;
2459
2460               /* For a type-conversion operator, we cannot do a
2461                  name-based lookup.  We might be looking for `operator
2462                  int' which will be a specialization of `operator T'.
2463                  So, we find *all* the conversion operators, and then
2464                  select from them.  */
2465               fns = NULL_TREE;
2466
2467               methods = CLASSTYPE_METHOD_VEC (ctype);
2468               if (methods)
2469                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2470                      VEC_iterate (tree, methods, idx, ovl);
2471                      ++idx)
2472                   {
2473                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2474                       /* There are no more conversion functions.  */
2475                       break;
2476
2477                     /* Glue all these conversion functions together
2478                        with those we already have.  */
2479                     for (; ovl; ovl = OVL_NEXT (ovl))
2480                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2481                   }
2482             }
2483
2484           if (fns == NULL_TREE)
2485             {
2486               error ("no member function %qD declared in %qT", name, ctype);
2487               return error_mark_node;
2488             }
2489           else
2490             TREE_OPERAND (declarator, 0) = fns;
2491         }
2492
2493       /* Figure out what exactly is being specialized at this point.
2494          Note that for an explicit instantiation, even one for a
2495          member function, we cannot tell apriori whether the
2496          instantiation is for a member template, or just a member
2497          function of a template class.  Even if a member template is
2498          being instantiated, the member template arguments may be
2499          elided if they can be deduced from the rest of the
2500          declaration.  */
2501       tmpl = determine_specialization (declarator, decl,
2502                                        &targs,
2503                                        member_specialization,
2504                                        template_count,
2505                                        tsk);
2506
2507       if (!tmpl || tmpl == error_mark_node)
2508         /* We couldn't figure out what this declaration was
2509            specializing.  */
2510         return error_mark_node;
2511       else
2512         {
2513           tree gen_tmpl = most_general_template (tmpl);
2514
2515           if (explicit_instantiation)
2516             {
2517               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2518                  is done by do_decl_instantiation later.  */
2519
2520               int arg_depth = TMPL_ARGS_DEPTH (targs);
2521               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2522
2523               if (arg_depth > parm_depth)
2524                 {
2525                   /* If TMPL is not the most general template (for
2526                      example, if TMPL is a friend template that is
2527                      injected into namespace scope), then there will
2528                      be too many levels of TARGS.  Remove some of them
2529                      here.  */
2530                   int i;
2531                   tree new_targs;
2532
2533                   new_targs = make_tree_vec (parm_depth);
2534                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2535                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2536                       = TREE_VEC_ELT (targs, i);
2537                   targs = new_targs;
2538                 }
2539
2540               return instantiate_template (tmpl, targs, tf_error);
2541             }
2542
2543           /* If we thought that the DECL was a member function, but it
2544              turns out to be specializing a static member function,
2545              make DECL a static member function as well.  */
2546           if (DECL_STATIC_FUNCTION_P (tmpl)
2547               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2548             revert_static_member_fn (decl);
2549
2550           /* If this is a specialization of a member template of a
2551              template class, we want to return the TEMPLATE_DECL, not
2552              the specialization of it.  */
2553           if (tsk == tsk_template)
2554             {
2555               tree result = DECL_TEMPLATE_RESULT (tmpl);
2556               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2557               DECL_INITIAL (result) = NULL_TREE;
2558               if (have_def)
2559                 {
2560                   tree parm;
2561                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2562                   DECL_SOURCE_LOCATION (result)
2563                     = DECL_SOURCE_LOCATION (decl);
2564                   /* We want to use the argument list specified in the
2565                      definition, not in the original declaration.  */
2566                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2567                   for (parm = DECL_ARGUMENTS (result); parm;
2568                        parm = DECL_CHAIN (parm))
2569                     DECL_CONTEXT (parm) = result;
2570                 }
2571               return register_specialization (tmpl, gen_tmpl, targs,
2572                                               is_friend, 0);
2573             }
2574
2575           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2576           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2577
2578           /* Inherit default function arguments from the template
2579              DECL is specializing.  */
2580           copy_default_args_to_explicit_spec (decl);
2581
2582           /* This specialization has the same protection as the
2583              template it specializes.  */
2584           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2585           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2586
2587           /* 7.1.1-1 [dcl.stc]
2588
2589              A storage-class-specifier shall not be specified in an
2590              explicit specialization...
2591
2592              The parser rejects these, so unless action is taken here,
2593              explicit function specializations will always appear with
2594              global linkage.
2595
2596              The action recommended by the C++ CWG in response to C++
2597              defect report 605 is to make the storage class and linkage
2598              of the explicit specialization match the templated function:
2599
2600              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2601            */
2602           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2603             {
2604               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2605               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2606
2607               /* This specialization has the same linkage and visibility as
2608                  the function template it specializes.  */
2609               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2610               if (! TREE_PUBLIC (decl))
2611                 {
2612                   DECL_INTERFACE_KNOWN (decl) = 1;
2613                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2614                 }
2615               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2616               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2617                 {
2618                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2619                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2620                 }
2621             }
2622
2623           /* If DECL is a friend declaration, declared using an
2624              unqualified name, the namespace associated with DECL may
2625              have been set incorrectly.  For example, in:
2626
2627                template <typename T> void f(T);
2628                namespace N {
2629                  struct S { friend void f<int>(int); }
2630                }
2631
2632              we will have set the DECL_CONTEXT for the friend
2633              declaration to N, rather than to the global namespace.  */
2634           if (DECL_NAMESPACE_SCOPE_P (decl))
2635             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2636
2637           if (is_friend && !have_def)
2638             /* This is not really a declaration of a specialization.
2639                It's just the name of an instantiation.  But, it's not
2640                a request for an instantiation, either.  */
2641             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2642           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2643             /* This is indeed a specialization.  In case of constructors
2644                and destructors, we need in-charge and not-in-charge
2645                versions in V3 ABI.  */
2646             clone_function_decl (decl, /*update_method_vec_p=*/0);
2647
2648           /* Register this specialization so that we can find it
2649              again.  */
2650           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2651         }
2652     }
2653
2654   return decl;
2655 }
2656
2657 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2658    parameters.  These are represented in the same format used for
2659    DECL_TEMPLATE_PARMS.  */
2660
2661 int
2662 comp_template_parms (const_tree parms1, const_tree parms2)
2663 {
2664   const_tree p1;
2665   const_tree p2;
2666
2667   if (parms1 == parms2)
2668     return 1;
2669
2670   for (p1 = parms1, p2 = parms2;
2671        p1 != NULL_TREE && p2 != NULL_TREE;
2672        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2673     {
2674       tree t1 = TREE_VALUE (p1);
2675       tree t2 = TREE_VALUE (p2);
2676       int i;
2677
2678       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2679       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2680
2681       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2682         return 0;
2683
2684       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2685         {
2686           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2687           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2688
2689           /* If either of the template parameters are invalid, assume
2690              they match for the sake of error recovery. */
2691           if (parm1 == error_mark_node || parm2 == error_mark_node)
2692             return 1;
2693
2694           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2695             return 0;
2696
2697           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2698               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2699                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2700             continue;
2701           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2702             return 0;
2703         }
2704     }
2705
2706   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2707     /* One set of parameters has more parameters lists than the
2708        other.  */
2709     return 0;
2710
2711   return 1;
2712 }
2713
2714 /* Determine whether PARM is a parameter pack.  */
2715
2716 bool 
2717 template_parameter_pack_p (const_tree parm)
2718 {
2719   /* Determine if we have a non-type template parameter pack.  */
2720   if (TREE_CODE (parm) == PARM_DECL)
2721     return (DECL_TEMPLATE_PARM_P (parm) 
2722             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2723
2724   /* If this is a list of template parameters, we could get a
2725      TYPE_DECL or a TEMPLATE_DECL.  */ 
2726   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2727     parm = TREE_TYPE (parm);
2728
2729   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2730            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2731           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2732 }
2733
2734 /* Determine if T is a function parameter pack.  */
2735
2736 bool
2737 function_parameter_pack_p (const_tree t)
2738 {
2739   if (t && TREE_CODE (t) == PARM_DECL)
2740     return FUNCTION_PARAMETER_PACK_P (t);
2741   return false;
2742 }
2743
2744 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2745    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2746
2747 tree
2748 get_function_template_decl (const_tree primary_func_tmpl_inst)
2749 {
2750   if (! primary_func_tmpl_inst
2751       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2752       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2753     return NULL;
2754
2755   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2756 }
2757
2758 /* Return true iff the function parameter PARAM_DECL was expanded
2759    from the function parameter pack PACK.  */
2760
2761 bool
2762 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2763 {
2764   if (DECL_ARTIFICIAL (param_decl)
2765       || !function_parameter_pack_p (pack))
2766     return false;
2767
2768   /* The parameter pack and its pack arguments have the same
2769      DECL_PARM_INDEX.  */
2770   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2771 }
2772
2773 /* Determine whether ARGS describes a variadic template args list,
2774    i.e., one that is terminated by a template argument pack.  */
2775
2776 static bool 
2777 template_args_variadic_p (tree args)
2778 {
2779   int nargs;
2780   tree last_parm;
2781
2782   if (args == NULL_TREE)
2783     return false;
2784
2785   args = INNERMOST_TEMPLATE_ARGS (args);
2786   nargs = TREE_VEC_LENGTH (args);
2787
2788   if (nargs == 0)
2789     return false;
2790
2791   last_parm = TREE_VEC_ELT (args, nargs - 1);
2792
2793   return ARGUMENT_PACK_P (last_parm);
2794 }
2795
2796 /* Generate a new name for the parameter pack name NAME (an
2797    IDENTIFIER_NODE) that incorporates its */
2798
2799 static tree
2800 make_ith_pack_parameter_name (tree name, int i)
2801 {
2802   /* Munge the name to include the parameter index.  */
2803 #define NUMBUF_LEN 128
2804   char numbuf[NUMBUF_LEN];
2805   char* newname;
2806   int newname_len;
2807
2808   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2809   newname_len = IDENTIFIER_LENGTH (name)
2810                 + strlen (numbuf) + 2;
2811   newname = (char*)alloca (newname_len);
2812   snprintf (newname, newname_len,
2813             "%s#%i", IDENTIFIER_POINTER (name), i);
2814   return get_identifier (newname);
2815 }
2816
2817 /* Return true if T is a primary function
2818    or class template instantiation.  */
2819
2820 bool
2821 primary_template_instantiation_p (const_tree t)
2822 {
2823   if (!t)
2824     return false;
2825
2826   if (TREE_CODE (t) == FUNCTION_DECL)
2827     return DECL_LANG_SPECIFIC (t)
2828            && DECL_TEMPLATE_INSTANTIATION (t)
2829            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2830   else if (CLASS_TYPE_P (t))
2831     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2832            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2833   return false;
2834 }
2835
2836 /* Return true if PARM is a template template parameter.  */
2837
2838 bool
2839 template_template_parameter_p (const_tree parm)
2840 {
2841   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2842 }
2843
2844 /* Return the template parameters of T if T is a
2845    primary template instantiation, NULL otherwise.  */
2846
2847 tree
2848 get_primary_template_innermost_parameters (const_tree t)
2849 {
2850   tree parms = NULL, template_info = NULL;
2851
2852   if ((template_info = get_template_info (t))
2853       && primary_template_instantiation_p (t))
2854     parms = INNERMOST_TEMPLATE_PARMS
2855         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2856
2857   return parms;
2858 }
2859
2860 /* Return the template parameters of the LEVELth level from the full list
2861    of template parameters PARMS.  */
2862
2863 tree
2864 get_template_parms_at_level (tree parms, int level)
2865 {
2866   tree p;
2867   if (!parms
2868       || TREE_CODE (parms) != TREE_LIST
2869       || level > TMPL_PARMS_DEPTH (parms))
2870     return NULL_TREE;
2871
2872   for (p = parms; p; p = TREE_CHAIN (p))
2873     if (TMPL_PARMS_DEPTH (p) == level)
2874       return p;
2875
2876   return NULL_TREE;
2877 }
2878
2879 /* Returns the template arguments of T if T is a template instantiation,
2880    NULL otherwise.  */
2881
2882 tree
2883 get_template_innermost_arguments (const_tree t)
2884 {
2885   tree args = NULL, template_info = NULL;
2886
2887   if ((template_info = get_template_info (t))
2888       && TI_ARGS (template_info))
2889     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2890
2891   return args;
2892 }
2893
2894 /* Return the argument pack elements of T if T is a template argument pack,
2895    NULL otherwise.  */
2896
2897 tree
2898 get_template_argument_pack_elems (const_tree t)
2899 {
2900   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2901       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2902     return NULL;
2903
2904   return ARGUMENT_PACK_ARGS (t);
2905 }
2906
2907 /* Structure used to track the progress of find_parameter_packs_r.  */
2908 struct find_parameter_pack_data 
2909 {
2910   /* TREE_LIST that will contain all of the parameter packs found by
2911      the traversal.  */
2912   tree* parameter_packs;
2913
2914   /* Set of AST nodes that have been visited by the traversal.  */
2915   struct pointer_set_t *visited;
2916 };
2917
2918 /* Identifies all of the argument packs that occur in a template
2919    argument and appends them to the TREE_LIST inside DATA, which is a
2920    find_parameter_pack_data structure. This is a subroutine of
2921    make_pack_expansion and uses_parameter_packs.  */
2922 static tree
2923 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2924 {
2925   tree t = *tp;
2926   struct find_parameter_pack_data* ppd = 
2927     (struct find_parameter_pack_data*)data;
2928   bool parameter_pack_p = false;
2929
2930   /* Identify whether this is a parameter pack or not.  */
2931   switch (TREE_CODE (t))
2932     {
2933     case TEMPLATE_PARM_INDEX:
2934       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2935         parameter_pack_p = true;
2936       break;
2937
2938     case TEMPLATE_TYPE_PARM:
2939     case TEMPLATE_TEMPLATE_PARM:
2940       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2941         parameter_pack_p = true;
2942       break;
2943
2944     case PARM_DECL:
2945       if (FUNCTION_PARAMETER_PACK_P (t))
2946         {
2947           /* We don't want to walk into the type of a PARM_DECL,
2948              because we don't want to see the type parameter pack.  */
2949           *walk_subtrees = 0;
2950           parameter_pack_p = true;
2951         }
2952       break;
2953
2954     default:
2955       /* Not a parameter pack.  */
2956       break;
2957     }
2958
2959   if (parameter_pack_p)
2960     {
2961       /* Add this parameter pack to the list.  */
2962       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2963     }
2964
2965   if (TYPE_P (t))
2966     cp_walk_tree (&TYPE_CONTEXT (t), 
2967                   &find_parameter_packs_r, ppd, ppd->visited);
2968
2969   /* This switch statement will return immediately if we don't find a
2970      parameter pack.  */
2971   switch (TREE_CODE (t)) 
2972     {
2973     case TEMPLATE_PARM_INDEX:
2974       return NULL_TREE;
2975
2976     case BOUND_TEMPLATE_TEMPLATE_PARM:
2977       /* Check the template itself.  */
2978       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2979                     &find_parameter_packs_r, ppd, ppd->visited);
2980       /* Check the template arguments.  */
2981       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2982                     ppd->visited);
2983       *walk_subtrees = 0;
2984       return NULL_TREE;
2985
2986     case TEMPLATE_TYPE_PARM:
2987     case TEMPLATE_TEMPLATE_PARM:
2988       return NULL_TREE;
2989
2990     case PARM_DECL:
2991       return NULL_TREE;
2992
2993     case RECORD_TYPE:
2994       if (TYPE_PTRMEMFUNC_P (t))
2995         return NULL_TREE;
2996       /* Fall through.  */
2997
2998     case UNION_TYPE:
2999     case ENUMERAL_TYPE:
3000       if (TYPE_TEMPLATE_INFO (t))
3001         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3002                       &find_parameter_packs_r, ppd, ppd->visited);
3003
3004       *walk_subtrees = 0;
3005       return NULL_TREE;
3006
3007     case TEMPLATE_DECL:
3008       cp_walk_tree (&TREE_TYPE (t),
3009                     &find_parameter_packs_r, ppd, ppd->visited);
3010       return NULL_TREE;
3011  
3012     case TYPENAME_TYPE:
3013       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3014                    ppd, ppd->visited);
3015       *walk_subtrees = 0;
3016       return NULL_TREE;
3017       
3018     case TYPE_PACK_EXPANSION:
3019     case EXPR_PACK_EXPANSION:
3020       *walk_subtrees = 0;
3021       return NULL_TREE;
3022
3023     case INTEGER_TYPE:
3024       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3025                     ppd, ppd->visited);
3026       *walk_subtrees = 0;
3027       return NULL_TREE;
3028
3029     case IDENTIFIER_NODE:
3030       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3031                     ppd->visited);
3032       *walk_subtrees = 0;
3033       return NULL_TREE;
3034
3035     default:
3036       return NULL_TREE;
3037     }
3038
3039   return NULL_TREE;
3040 }
3041
3042 /* Determines if the expression or type T uses any parameter packs.  */
3043 bool
3044 uses_parameter_packs (tree t)
3045 {
3046   tree parameter_packs = NULL_TREE;
3047   struct find_parameter_pack_data ppd;
3048   ppd.parameter_packs = &parameter_packs;
3049   ppd.visited = pointer_set_create ();
3050   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3051   pointer_set_destroy (ppd.visited);
3052   return parameter_packs != NULL_TREE;
3053 }
3054
3055 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3056    representation a base-class initializer into a parameter pack
3057    expansion. If all goes well, the resulting node will be an
3058    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3059    respectively.  */
3060 tree 
3061 make_pack_expansion (tree arg)
3062 {
3063   tree result;
3064   tree parameter_packs = NULL_TREE;
3065   bool for_types = false;
3066   struct find_parameter_pack_data ppd;
3067
3068   if (!arg || arg == error_mark_node)
3069     return arg;
3070
3071   if (TREE_CODE (arg) == TREE_LIST)
3072     {
3073       /* The only time we will see a TREE_LIST here is for a base
3074          class initializer.  In this case, the TREE_PURPOSE will be a
3075          _TYPE node (representing the base class expansion we're
3076          initializing) and the TREE_VALUE will be a TREE_LIST
3077          containing the initialization arguments. 
3078
3079          The resulting expansion looks somewhat different from most
3080          expansions. Rather than returning just one _EXPANSION, we
3081          return a TREE_LIST whose TREE_PURPOSE is a
3082          TYPE_PACK_EXPANSION containing the bases that will be
3083          initialized.  The TREE_VALUE will be identical to the
3084          original TREE_VALUE, which is a list of arguments that will
3085          be passed to each base.  We do not introduce any new pack
3086          expansion nodes into the TREE_VALUE (although it is possible
3087          that some already exist), because the TREE_PURPOSE and
3088          TREE_VALUE all need to be expanded together with the same
3089          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3090          resulting TREE_PURPOSE will mention the parameter packs in
3091          both the bases and the arguments to the bases.  */
3092       tree purpose;
3093       tree value;
3094       tree parameter_packs = NULL_TREE;
3095
3096       /* Determine which parameter packs will be used by the base
3097          class expansion.  */
3098       ppd.visited = pointer_set_create ();
3099       ppd.parameter_packs = &parameter_packs;
3100       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3101                     &ppd, ppd.visited);
3102
3103       if (parameter_packs == NULL_TREE)
3104         {
3105           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3106           pointer_set_destroy (ppd.visited);
3107           return error_mark_node;
3108         }
3109
3110       if (TREE_VALUE (arg) != void_type_node)
3111         {
3112           /* Collect the sets of parameter packs used in each of the
3113              initialization arguments.  */
3114           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3115             {
3116               /* Determine which parameter packs will be expanded in this
3117                  argument.  */
3118               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3119                             &ppd, ppd.visited);
3120             }
3121         }
3122
3123       pointer_set_destroy (ppd.visited);
3124
3125       /* Create the pack expansion type for the base type.  */
3126       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3127       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3128       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3129
3130       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3131          they will rarely be compared to anything.  */
3132       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3133
3134       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3135     }
3136
3137   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3138     for_types = true;
3139
3140   /* Build the PACK_EXPANSION_* node.  */
3141   result = for_types
3142      ? cxx_make_type (TYPE_PACK_EXPANSION)
3143      : make_node (EXPR_PACK_EXPANSION);
3144   SET_PACK_EXPANSION_PATTERN (result, arg);
3145   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3146     {
3147       /* Propagate type and const-expression information.  */
3148       TREE_TYPE (result) = TREE_TYPE (arg);
3149       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3150     }
3151   else
3152     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3153        they will rarely be compared to anything.  */
3154     SET_TYPE_STRUCTURAL_EQUALITY (result);
3155
3156   /* Determine which parameter packs will be expanded.  */
3157   ppd.parameter_packs = &parameter_packs;
3158   ppd.visited = pointer_set_create ();
3159   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3160   pointer_set_destroy (ppd.visited);
3161
3162   /* Make sure we found some parameter packs.  */
3163   if (parameter_packs == NULL_TREE)
3164     {
3165       if (TYPE_P (arg))
3166         error ("expansion pattern %<%T%> contains no argument packs", arg);
3167       else
3168         error ("expansion pattern %<%E%> contains no argument packs", arg);
3169       return error_mark_node;
3170     }
3171   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3172
3173   return result;
3174 }
3175
3176 /* Checks T for any "bare" parameter packs, which have not yet been
3177    expanded, and issues an error if any are found. This operation can
3178    only be done on full expressions or types (e.g., an expression
3179    statement, "if" condition, etc.), because we could have expressions like:
3180
3181      foo(f(g(h(args)))...)
3182
3183    where "args" is a parameter pack. check_for_bare_parameter_packs
3184    should not be called for the subexpressions args, h(args),
3185    g(h(args)), or f(g(h(args))), because we would produce erroneous
3186    error messages. 
3187
3188    Returns TRUE and emits an error if there were bare parameter packs,
3189    returns FALSE otherwise.  */
3190 bool 
3191 check_for_bare_parameter_packs (tree t)
3192 {
3193   tree parameter_packs = NULL_TREE;
3194   struct find_parameter_pack_data ppd;
3195
3196   if (!processing_template_decl || !t || t == error_mark_node)
3197     return false;
3198
3199   if (TREE_CODE (t) == TYPE_DECL)
3200     t = TREE_TYPE (t);
3201
3202   ppd.parameter_packs = &parameter_packs;
3203   ppd.visited = pointer_set_create ();
3204   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3205   pointer_set_destroy (ppd.visited);
3206
3207   if (parameter_packs) 
3208     {
3209       error ("parameter packs not expanded with %<...%>:");
3210       while (parameter_packs)
3211         {
3212           tree pack = TREE_VALUE (parameter_packs);
3213           tree name = NULL_TREE;
3214
3215           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3216               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3217             name = TYPE_NAME (pack);
3218           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3219             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3220           else
3221             name = DECL_NAME (pack);
3222
3223           if (name)
3224             inform (input_location, "        %qD", name);
3225           else
3226             inform (input_location, "        <anonymous>");
3227
3228           parameter_packs = TREE_CHAIN (parameter_packs);
3229         }
3230
3231       return true;
3232     }
3233
3234   return false;
3235 }
3236
3237 /* Expand any parameter packs that occur in the template arguments in
3238    ARGS.  */
3239 tree
3240 expand_template_argument_pack (tree args)
3241 {
3242   tree result_args = NULL_TREE;
3243   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3244   int num_result_args = -1;
3245   int non_default_args_count = -1;
3246
3247   /* First, determine if we need to expand anything, and the number of
3248      slots we'll need.  */
3249   for (in_arg = 0; in_arg < nargs; ++in_arg)
3250     {
3251       tree arg = TREE_VEC_ELT (args, in_arg);
3252       if (arg == NULL_TREE)
3253         return args;
3254       if (ARGUMENT_PACK_P (arg))
3255         {
3256           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3257           if (num_result_args < 0)
3258             num_result_args = in_arg + num_packed;
3259           else
3260             num_result_args += num_packed;
3261         }
3262       else
3263         {
3264           if (num_result_args >= 0)
3265             num_result_args++;
3266         }
3267     }
3268
3269   /* If no expansion is necessary, we're done.  */
3270   if (num_result_args < 0)
3271     return args;
3272
3273   /* Expand arguments.  */
3274   result_args = make_tree_vec (num_result_args);
3275   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3276     non_default_args_count =
3277       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3278   for (in_arg = 0; in_arg < nargs; ++in_arg)
3279     {
3280       tree arg = TREE_VEC_ELT (args, in_arg);
3281       if (ARGUMENT_PACK_P (arg))
3282         {
3283           tree packed = ARGUMENT_PACK_ARGS (arg);
3284           int i, num_packed = TREE_VEC_LENGTH (packed);
3285           for (i = 0; i < num_packed; ++i, ++out_arg)
3286             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3287           if (non_default_args_count > 0)
3288             non_default_args_count += num_packed;
3289         }
3290       else
3291         {
3292           TREE_VEC_ELT (result_args, out_arg) = arg;
3293           ++out_arg;
3294         }
3295     }
3296   if (non_default_args_count >= 0)
3297     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3298   return result_args;
3299 }
3300
3301 /* Checks if DECL shadows a template parameter.
3302
3303    [temp.local]: A template-parameter shall not be redeclared within its
3304    scope (including nested scopes).
3305
3306    Emits an error and returns TRUE if the DECL shadows a parameter,
3307    returns FALSE otherwise.  */
3308
3309 bool
3310 check_template_shadow (tree decl)
3311 {
3312   tree olddecl;
3313
3314   /* If we're not in a template, we can't possibly shadow a template
3315      parameter.  */
3316   if (!current_template_parms)
3317     return true;
3318
3319   /* Figure out what we're shadowing.  */
3320   if (TREE_CODE (decl) == OVERLOAD)
3321     decl = OVL_CURRENT (decl);
3322   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3323
3324   /* If there's no previous binding for this name, we're not shadowing
3325      anything, let alone a template parameter.  */
3326   if (!olddecl)
3327     return true;
3328
3329   /* If we're not shadowing a template parameter, we're done.  Note
3330      that OLDDECL might be an OVERLOAD (or perhaps even an
3331      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3332      node.  */
3333   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3334     return true;
3335
3336   /* We check for decl != olddecl to avoid bogus errors for using a
3337      name inside a class.  We check TPFI to avoid duplicate errors for
3338      inline member templates.  */
3339   if (decl == olddecl
3340       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3341     return true;
3342
3343   error ("declaration of %q+#D", decl);
3344   error (" shadows template parm %q+#D", olddecl);
3345   return false;
3346 }
3347
3348 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3349    ORIG_LEVEL, DECL, and TYPE.  */
3350
3351 static tree
3352 build_template_parm_index (int index,
3353                            int level,
3354                            int orig_level,
3355                            tree decl,
3356                            tree type)
3357 {
3358   tree t = make_node (TEMPLATE_PARM_INDEX);
3359   TEMPLATE_PARM_IDX (t) = index;
3360   TEMPLATE_PARM_LEVEL (t) = level;
3361   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3362   TEMPLATE_PARM_DECL (t) = decl;
3363   TREE_TYPE (t) = type;
3364   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3365   TREE_READONLY (t) = TREE_READONLY (decl);
3366
3367   return t;
3368 }
3369
3370 /* Find the canonical type parameter for the given template type
3371    parameter.  Returns the canonical type parameter, which may be TYPE
3372    if no such parameter existed.  */
3373 static tree
3374 canonical_type_parameter (tree type)
3375 {
3376   tree list;
3377   int idx = TEMPLATE_TYPE_IDX (type);
3378   if (!canonical_template_parms)
3379     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3380
3381   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3382     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3383
3384   list = VEC_index (tree, canonical_template_parms, idx);
3385   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3386     list = TREE_CHAIN (list);
3387
3388   if (list)
3389     return TREE_VALUE (list);
3390   else
3391     {
3392       VEC_replace(tree, canonical_template_parms, idx,
3393                   tree_cons (NULL_TREE, type, 
3394                              VEC_index (tree, canonical_template_parms, idx)));
3395       return type;
3396     }
3397 }
3398
3399 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3400    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3401    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3402    new one is created.  */
3403
3404 static tree
3405 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3406                             tsubst_flags_t complain)
3407 {
3408   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3409       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3410           != TEMPLATE_PARM_LEVEL (index) - levels)
3411       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3412     {
3413       tree orig_decl = TEMPLATE_PARM_DECL (index);
3414       tree decl, t;
3415
3416       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3417                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3418       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3419       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3420       DECL_ARTIFICIAL (decl) = 1;
3421       SET_DECL_TEMPLATE_PARM_P (decl);
3422
3423       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3424                                      TEMPLATE_PARM_LEVEL (index) - levels,
3425                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3426                                      decl, type);
3427       TEMPLATE_PARM_DESCENDANTS (index) = t;
3428       TEMPLATE_PARM_PARAMETER_PACK (t) 
3429         = TEMPLATE_PARM_PARAMETER_PACK (index);
3430
3431         /* Template template parameters need this.  */
3432       if (TREE_CODE (decl) == TEMPLATE_DECL)
3433         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3434           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3435            args, complain);
3436     }
3437
3438   return TEMPLATE_PARM_DESCENDANTS (index);
3439 }
3440
3441 /* Process information from new template parameter PARM and append it to the
3442    LIST being built.  This new parameter is a non-type parameter iff
3443    IS_NON_TYPE is true. This new parameter is a parameter
3444    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3445    PARM_LOC.  */
3446
3447 tree
3448 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3449                        bool is_parameter_pack)
3450 {
3451   tree decl = 0;
3452   tree defval;
3453   tree err_parm_list;
3454   int idx = 0;
3455
3456   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3457   defval = TREE_PURPOSE (parm);
3458
3459   if (list)
3460     {
3461       tree p = tree_last (list);
3462
3463       if (p && TREE_VALUE (p) != error_mark_node)
3464         {
3465           p = TREE_VALUE (p);
3466           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3467             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3468           else
3469             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3470         }
3471
3472       ++idx;
3473     }
3474   else
3475     idx = 0;
3476
3477   if (is_non_type)
3478     {
3479       parm = TREE_VALUE (parm);
3480
3481       SET_DECL_TEMPLATE_PARM_P (parm);
3482
3483       if (TREE_TYPE (parm) == error_mark_node)
3484         {
3485           err_parm_list = build_tree_list (defval, parm);
3486           TREE_VALUE (err_parm_list) = error_mark_node;
3487            return chainon (list, err_parm_list);
3488         }
3489       else
3490       {
3491         /* [temp.param]
3492
3493            The top-level cv-qualifiers on the template-parameter are
3494            ignored when determining its type.  */
3495         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3496         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3497           {
3498             err_parm_list = build_tree_list (defval, parm);
3499             TREE_VALUE (err_parm_list) = error_mark_node;
3500              return chainon (list, err_parm_list);
3501           }
3502
3503         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3504           {
3505             /* This template parameter is not a parameter pack, but it
3506                should be. Complain about "bare" parameter packs.  */
3507             check_for_bare_parameter_packs (TREE_TYPE (parm));
3508             
3509             /* Recover by calling this a parameter pack.  */
3510             is_parameter_pack = true;
3511           }
3512       }
3513
3514       /* A template parameter is not modifiable.  */
3515       TREE_CONSTANT (parm) = 1;
3516       TREE_READONLY (parm) = 1;
3517       decl = build_decl (parm_loc,
3518                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3519       TREE_CONSTANT (decl) = 1;
3520       TREE_READONLY (decl) = 1;
3521       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3522         = build_template_parm_index (idx, processing_template_decl,
3523                                      processing_template_decl,
3524                                      decl, TREE_TYPE (parm));
3525
3526       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3527         = is_parameter_pack;
3528     }
3529   else
3530     {
3531       tree t;
3532       parm = TREE_VALUE (TREE_VALUE (parm));
3533
3534       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3535         {
3536           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3537           /* This is for distinguishing between real templates and template
3538              template parameters */
3539           TREE_TYPE (parm) = t;
3540           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3541           decl = parm;
3542         }
3543       else
3544         {
3545           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3546           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3547           decl = build_decl (parm_loc,
3548                              TYPE_DECL, parm, t);
3549         }
3550
3551       TYPE_NAME (t) = decl;
3552       TYPE_STUB_DECL (t) = decl;
3553       parm = decl;
3554       TEMPLATE_TYPE_PARM_INDEX (t)
3555         = build_template_parm_index (idx, processing_template_decl,
3556                                      processing_template_decl,
3557                                      decl, TREE_TYPE (parm));
3558       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3559       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3560     }
3561   DECL_ARTIFICIAL (decl) = 1;
3562   SET_DECL_TEMPLATE_PARM_P (decl);
3563   pushdecl (decl);
3564   parm = build_tree_list (defval, parm);
3565   return chainon (list, parm);
3566 }
3567
3568 /* The end of a template parameter list has been reached.  Process the
3569    tree list into a parameter vector, converting each parameter into a more
3570    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3571    as PARM_DECLs.  */
3572
3573 tree
3574 end_template_parm_list (tree parms)
3575 {
3576   int nparms;
3577   tree parm, next;
3578   tree saved_parmlist = make_tree_vec (list_length (parms));
3579
3580   current_template_parms
3581     = tree_cons (size_int (processing_template_decl),
3582                  saved_parmlist, current_template_parms);
3583
3584   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3585     {
3586       next = TREE_CHAIN (parm);
3587       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3588       TREE_CHAIN (parm) = NULL_TREE;
3589       if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
3590         TEMPLATE_TYPE_PARM_SIBLING_PARMS (TREE_TYPE (TREE_VALUE (parm))) =
3591               current_template_parms;
3592     }
3593
3594   --processing_template_parmlist;
3595
3596   return saved_parmlist;
3597 }
3598
3599 /* end_template_decl is called after a template declaration is seen.  */
3600
3601 void
3602 end_template_decl (void)
3603 {
3604   reset_specialization ();
3605
3606   if (! processing_template_decl)
3607     return;
3608
3609   /* This matches the pushlevel in begin_template_parm_list.  */
3610   finish_scope ();
3611
3612   --processing_template_decl;
3613   current_template_parms = TREE_CHAIN (current_template_parms);
3614 }
3615
3616 /* Within the declaration of a template, return all levels of template
3617    parameters that apply.  The template parameters are represented as
3618    a TREE_VEC, in the form documented in cp-tree.h for template
3619    arguments.  */
3620
3621 static tree
3622 current_template_args (void)
3623 {
3624   tree header;
3625   tree args = NULL_TREE;
3626   int length = TMPL_PARMS_DEPTH (current_template_parms);
3627   int l = length;
3628
3629   /* If there is only one level of template parameters, we do not
3630      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3631      TREE_VEC containing the arguments.  */
3632   if (length > 1)
3633     args = make_tree_vec (length);
3634
3635   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3636     {
3637       tree a = copy_node (TREE_VALUE (header));
3638       int i;
3639
3640       TREE_TYPE (a) = NULL_TREE;
3641       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3642         {
3643           tree t = TREE_VEC_ELT (a, i);
3644
3645           /* T will be a list if we are called from within a
3646              begin/end_template_parm_list pair, but a vector directly
3647              if within a begin/end_member_template_processing pair.  */
3648           if (TREE_CODE (t) == TREE_LIST)
3649             {
3650               t = TREE_VALUE (t);
3651
3652               if (!error_operand_p (t))
3653                 {
3654                   if (TREE_CODE (t) == TYPE_DECL
3655                       || TREE_CODE (t) == TEMPLATE_DECL)
3656                     {
3657                       t = TREE_TYPE (t);
3658                       
3659                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3660                         {
3661                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3662                              with a single element, which expands T.  */
3663                           tree vec = make_tree_vec (1);
3664 #ifdef ENABLE_CHECKING
3665                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3666                                 (vec, TREE_VEC_LENGTH (vec));
3667 #endif
3668                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3669                           
3670                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3671                           SET_ARGUMENT_PACK_ARGS (t, vec);
3672                         }
3673                     }
3674                   else
3675                     {
3676                       t = DECL_INITIAL (t);
3677                       
3678                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3679                         {
3680                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3681                              with a single element, which expands T.  */
3682                           tree vec = make_tree_vec (1);
3683                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3684 #ifdef ENABLE_CHECKING
3685                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3686                                 (vec, TREE_VEC_LENGTH (vec));
3687 #endif
3688                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3689                           
3690                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3691                           SET_ARGUMENT_PACK_ARGS (t, vec);
3692                           TREE_TYPE (t) = type;
3693                         }
3694                     }
3695                   TREE_VEC_ELT (a, i) = t;
3696                 }
3697             }
3698         }
3699
3700 #ifdef ENABLE_CHECKING
3701       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3702 #endif
3703
3704       if (length > 1)
3705         TREE_VEC_ELT (args, --l) = a;
3706       else
3707         args = a;
3708     }
3709
3710   return args;
3711 }
3712
3713 /* Update the declared TYPE by doing any lookups which were thought to be
3714    dependent, but are not now that we know the SCOPE of the declarator.  */
3715
3716 tree
3717 maybe_update_decl_type (tree orig_type, tree scope)
3718 {
3719   tree type = orig_type;
3720
3721   if (type == NULL_TREE)
3722     return type;
3723
3724   if (TREE_CODE (orig_type) == TYPE_DECL)
3725     type = TREE_TYPE (type);
3726
3727   if (scope && TYPE_P (scope) && dependent_type_p (scope)
3728       && dependent_type_p (type)
3729       /* Don't bother building up the args in this case.  */
3730       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3731     {
3732       /* tsubst in the args corresponding to the template parameters,
3733          including auto if present.  Most things will be unchanged, but
3734          make_typename_type and tsubst_qualified_id will resolve
3735          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3736       tree args = current_template_args ();
3737       tree auto_node = type_uses_auto (type);
3738       tree pushed;
3739       if (auto_node)
3740         {
3741           tree auto_vec = make_tree_vec (1);
3742           TREE_VEC_ELT (auto_vec, 0) = auto_node;
3743           args = add_to_template_args (args, auto_vec);
3744         }
3745       pushed = push_scope (scope);
3746       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3747       if (pushed)
3748         pop_scope (scope);
3749     }
3750
3751   if (type == error_mark_node)
3752     return orig_type;
3753
3754   if (TREE_CODE (orig_type) == TYPE_DECL)
3755     {
3756       if (same_type_p (type, TREE_TYPE (orig_type)))
3757         type = orig_type;
3758       else
3759         type = TYPE_NAME (type);
3760     }
3761   return type;
3762 }
3763
3764 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3765    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3766    a member template.  Used by push_template_decl below.  */
3767
3768 static tree
3769 build_template_decl (tree decl, tree parms, bool member_template_p)
3770 {
3771   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3772   DECL_TEMPLATE_PARMS (tmpl) = parms;
3773   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3774   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3775
3776   return tmpl;
3777 }
3778
3779 struct template_parm_data
3780 {
3781   /* The level of the template parameters we are currently
3782      processing.  */
3783   int level;
3784
3785   /* The index of the specialization argument we are currently
3786      processing.  */
3787   int current_arg;
3788
3789   /* An array whose size is the number of template parameters.  The
3790      elements are nonzero if the parameter has been used in any one
3791      of the arguments processed so far.  */
3792   int* parms;
3793
3794   /* An array whose size is the number of template arguments.  The
3795      elements are nonzero if the argument makes use of template
3796      parameters of this level.  */
3797   int* arg_uses_template_parms;
3798 };
3799
3800 /* Subroutine of push_template_decl used to see if each template
3801    parameter in a partial specialization is used in the explicit
3802    argument list.  If T is of the LEVEL given in DATA (which is
3803    treated as a template_parm_data*), then DATA->PARMS is marked
3804    appropriately.  */
3805
3806 static int
3807 mark_template_parm (tree t, void* data)
3808 {
3809   int level;
3810   int idx;
3811   struct template_parm_data* tpd = (struct template_parm_data*) data;
3812
3813   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3814     {
3815       level = TEMPLATE_PARM_LEVEL (t);
3816       idx = TEMPLATE_PARM_IDX (t);
3817     }
3818   else
3819     {
3820       level = TEMPLATE_TYPE_LEVEL (t);
3821       idx = TEMPLATE_TYPE_IDX (t);
3822     }
3823
3824   if (level == tpd->level)
3825     {
3826       tpd->parms[idx] = 1;
3827       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3828     }
3829
3830   /* Return zero so that for_each_template_parm will continue the
3831      traversal of the tree; we want to mark *every* template parm.  */
3832   return 0;
3833 }
3834
3835 /* Process the partial specialization DECL.  */
3836
3837 static tree
3838 process_partial_specialization (tree decl)
3839 {
3840   tree type = TREE_TYPE (decl);
3841   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3842   tree specargs = CLASSTYPE_TI_ARGS (type);
3843   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3844   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3845   tree inner_parms;
3846   tree inst;
3847   int nargs = TREE_VEC_LENGTH (inner_args);
3848   int ntparms;
3849   int  i;
3850   bool did_error_intro = false;
3851   struct template_parm_data tpd;
3852   struct template_parm_data tpd2;
3853
3854   gcc_assert (current_template_parms);
3855
3856   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3857   ntparms = TREE_VEC_LENGTH (inner_parms);
3858
3859   /* We check that each of the template parameters given in the
3860      partial specialization is used in the argument list to the
3861      specialization.  For example:
3862
3863        template <class T> struct S;
3864        template <class T> struct S<T*>;
3865
3866      The second declaration is OK because `T*' uses the template
3867      parameter T, whereas
3868
3869        template <class T> struct S<int>;
3870
3871      is no good.  Even trickier is:
3872
3873        template <class T>
3874        struct S1
3875        {
3876           template <class U>
3877           struct S2;
3878           template <class U>
3879           struct S2<T>;
3880        };
3881
3882      The S2<T> declaration is actually invalid; it is a
3883      full-specialization.  Of course,
3884
3885           template <class U>
3886           struct S2<T (*)(U)>;
3887
3888      or some such would have been OK.  */
3889   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3890   tpd.parms = XALLOCAVEC (int, ntparms);
3891   memset (tpd.parms, 0, sizeof (int) * ntparms);
3892
3893   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
3894   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3895   for (i = 0; i < nargs; ++i)
3896     {
3897       tpd.current_arg = i;
3898       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3899                               &mark_template_parm,
3900                               &tpd,
3901                               NULL,
3902                               /*include_nondeduced_p=*/false);
3903     }
3904   for (i = 0; i < ntparms; ++i)
3905     if (tpd.parms[i] == 0)
3906       {
3907         /* One of the template parms was not used in the
3908            specialization.  */
3909         if (!did_error_intro)
3910           {
3911             error ("template parameters not used in partial specialization:");
3912             did_error_intro = true;
3913           }
3914
3915         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3916       }
3917
3918   if (did_error_intro)
3919     return error_mark_node;
3920
3921   /* [temp.class.spec]
3922
3923      The argument list of the specialization shall not be identical to
3924      the implicit argument list of the primary template.  */
3925   if (comp_template_args
3926       (inner_args,
3927        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3928                                                    (maintmpl)))))
3929     error ("partial specialization %qT does not specialize any template arguments", type);
3930
3931   /* [temp.class.spec]
3932
3933      A partially specialized non-type argument expression shall not
3934      involve template parameters of the partial specialization except
3935      when the argument expression is a simple identifier.
3936
3937      The type of a template parameter corresponding to a specialized
3938      non-type argument shall not be dependent on a parameter of the
3939      specialization. 
3940
3941      Also, we verify that pack expansions only occur at the
3942      end of the argument list.  */
3943   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3944   tpd2.parms = 0;
3945   for (i = 0; i < nargs; ++i)
3946     {
3947       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3948       tree arg = TREE_VEC_ELT (inner_args, i);
3949       tree packed_args = NULL_TREE;
3950       int j, len = 1;
3951
3952       if (ARGUMENT_PACK_P (arg))
3953         {
3954           /* Extract the arguments from the argument pack. We'll be
3955              iterating over these in the following loop.  */
3956           packed_args = ARGUMENT_PACK_ARGS (arg);
3957           len = TREE_VEC_LENGTH (packed_args);
3958         }
3959
3960       for (j = 0; j < len; j++)
3961         {
3962           if (packed_args)
3963             /* Get the Jth argument in the parameter pack.  */
3964             arg = TREE_VEC_ELT (packed_args, j);
3965
3966           if (PACK_EXPANSION_P (arg))
3967             {
3968               /* Pack expansions must come at the end of the
3969                  argument list.  */
3970               if ((packed_args && j < len - 1)
3971                   || (!packed_args && i < nargs - 1))
3972                 {
3973                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3974                     error ("parameter pack argument %qE must be at the "
3975                            "end of the template argument list", arg);
3976                   else
3977                     error ("parameter pack argument %qT must be at the "
3978                            "end of the template argument list", arg);
3979                 }
3980             }
3981
3982           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3983             /* We only care about the pattern.  */
3984             arg = PACK_EXPANSION_PATTERN (arg);
3985
3986           if (/* These first two lines are the `non-type' bit.  */
3987               !TYPE_P (arg)
3988               && TREE_CODE (arg) != TEMPLATE_DECL
3989               /* This next line is the `argument expression is not just a
3990                  simple identifier' condition and also the `specialized
3991                  non-type argument' bit.  */
3992               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3993             {
3994               if ((!packed_args && tpd.arg_uses_template_parms[i])
3995                   || (packed_args && uses_template_parms (arg)))
3996                 error ("template argument %qE involves template parameter(s)",
3997                        arg);
3998               else 
3999                 {
4000                   /* Look at the corresponding template parameter,
4001                      marking which template parameters its type depends
4002                      upon.  */
4003                   tree type = TREE_TYPE (parm);
4004
4005                   if (!tpd2.parms)
4006                     {
4007                       /* We haven't yet initialized TPD2.  Do so now.  */
4008                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4009                       /* The number of parameters here is the number in the
4010                          main template, which, as checked in the assertion
4011                          above, is NARGS.  */
4012                       tpd2.parms = XALLOCAVEC (int, nargs);
4013                       tpd2.level = 
4014                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4015                     }
4016
4017                   /* Mark the template parameters.  But this time, we're
4018                      looking for the template parameters of the main
4019                      template, not in the specialization.  */
4020                   tpd2.current_arg = i;
4021                   tpd2.arg_uses_template_parms[i] = 0;
4022                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4023                   for_each_template_parm (type,
4024                                           &mark_template_parm,
4025                                           &tpd2,
4026                                           NULL,
4027                                           /*include_nondeduced_p=*/false);
4028
4029                   if (tpd2.arg_uses_template_parms [i])
4030                     {
4031                       /* The type depended on some template parameters.
4032                          If they are fully specialized in the
4033                          specialization, that's OK.  */
4034                       int j;
4035                       int count = 0;
4036                       for (j = 0; j < nargs; ++j)
4037                         if (tpd2.parms[j] != 0
4038                             && tpd.arg_uses_template_parms [j])
4039                           ++count;
4040                       if (count != 0)
4041                         error_n (input_location, count,
4042                                  "type %qT of template argument %qE depends "
4043                                  "on a template parameter",
4044                                  "type %qT of template argument %qE depends "
4045                                  "on template parameters",
4046                                  type,
4047                                  arg);
4048                     }
4049                 }
4050             }
4051         }
4052     }
4053
4054   /* We should only get here once.  */
4055   gcc_assert (!COMPLETE_TYPE_P (type));
4056
4057   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4058     = tree_cons (specargs, inner_parms,
4059                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4060   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4061
4062   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4063        inst = TREE_CHAIN (inst))
4064     {
4065       tree inst_type = TREE_VALUE (inst);
4066       if (COMPLETE_TYPE_P (inst_type)
4067           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4068         {
4069           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4070           if (spec && TREE_TYPE (spec) == type)
4071             permerror (input_location,
4072                        "partial specialization of %qT after instantiation "
4073                        "of %qT", type, inst_type);
4074         }
4075     }
4076
4077   return decl;
4078 }
4079
4080 /* Check that a template declaration's use of default arguments and
4081    parameter packs is not invalid.  Here, PARMS are the template
4082    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4083    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4084    specialization.
4085    
4086
4087    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4088    declaration (but not a definition); 1 indicates a declaration, 2
4089    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4090    emitted for extraneous default arguments.
4091
4092    Returns TRUE if there were no errors found, FALSE otherwise. */
4093
4094 bool
4095 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4096                          int is_partial, int is_friend_decl)
4097 {
4098   const char *msg;
4099   int last_level_to_check;
4100   tree parm_level;
4101   bool no_errors = true;
4102
4103   /* [temp.param]
4104
4105      A default template-argument shall not be specified in a
4106      function template declaration or a function template definition, nor
4107      in the template-parameter-list of the definition of a member of a
4108      class template.  */
4109
4110   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4111     /* You can't have a function template declaration in a local
4112        scope, nor you can you define a member of a class template in a
4113        local scope.  */
4114     return true;
4115
4116   if (current_class_type
4117       && !TYPE_BEING_DEFINED (current_class_type)
4118       && DECL_LANG_SPECIFIC (decl)
4119       && DECL_DECLARES_FUNCTION_P (decl)
4120       /* If this is either a friend defined in the scope of the class
4121          or a member function.  */
4122       && (DECL_FUNCTION_MEMBER_P (decl)
4123           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4124           : DECL_FRIEND_CONTEXT (decl)
4125           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4126           : false)
4127       /* And, if it was a member function, it really was defined in
4128          the scope of the class.  */
4129       && (!DECL_FUNCTION_MEMBER_P (decl)
4130           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4131     /* We already checked these parameters when the template was
4132        declared, so there's no need to do it again now.  This function
4133        was defined in class scope, but we're processing it's body now
4134        that the class is complete.  */
4135     return true;
4136
4137   /* Core issue 226 (C++0x only): the following only applies to class
4138      templates.  */
4139   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4140     {
4141       /* [temp.param]
4142
4143          If a template-parameter has a default template-argument, all
4144          subsequent template-parameters shall have a default
4145          template-argument supplied.  */
4146       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4147         {
4148           tree inner_parms = TREE_VALUE (parm_level);
4149           int ntparms = TREE_VEC_LENGTH (inner_parms);
4150           int seen_def_arg_p = 0;
4151           int i;
4152
4153           for (i = 0; i < ntparms; ++i)
4154             {
4155               tree parm = TREE_VEC_ELT (inner_parms, i);
4156
4157               if (parm == error_mark_node)
4158                 continue;
4159
4160               if (TREE_PURPOSE (parm))
4161                 seen_def_arg_p = 1;
4162               else if (seen_def_arg_p
4163                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4164                 {
4165                   error ("no default argument for %qD", TREE_VALUE (parm));
4166                   /* For better subsequent error-recovery, we indicate that
4167                      there should have been a default argument.  */
4168                   TREE_PURPOSE (parm) = error_mark_node;
4169                   no_errors = false;
4170                 }
4171               else if (is_primary
4172                        && !is_partial
4173                        && !is_friend_decl
4174                        /* Don't complain about an enclosing partial
4175                           specialization.  */
4176                        && parm_level == parms
4177                        && TREE_CODE (decl) == TYPE_DECL
4178                        && i < ntparms - 1
4179                        && template_parameter_pack_p (TREE_VALUE (parm)))
4180                 {
4181                   /* A primary class template can only have one
4182                      parameter pack, at the end of the template
4183                      parameter list.  */
4184
4185                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4186                     error ("parameter pack %qE must be at the end of the"
4187                            " template parameter list", TREE_VALUE (parm));
4188                   else
4189                     error ("parameter pack %qT must be at the end of the"
4190                            " template parameter list", 
4191                            TREE_TYPE (TREE_VALUE (parm)));
4192
4193                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4194                     = error_mark_node;
4195                   no_errors = false;
4196                 }
4197             }
4198         }
4199     }
4200
4201   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4202       || is_partial 
4203       || !is_primary
4204       || is_friend_decl)
4205     /* For an ordinary class template, default template arguments are
4206        allowed at the innermost level, e.g.:
4207          template <class T = int>
4208          struct S {};
4209        but, in a partial specialization, they're not allowed even
4210        there, as we have in [temp.class.spec]:
4211
4212          The template parameter list of a specialization shall not
4213          contain default template argument values.
4214
4215        So, for a partial specialization, or for a function template
4216        (in C++98/C++03), we look at all of them.  */
4217     ;
4218   else
4219     /* But, for a primary class template that is not a partial
4220        specialization we look at all template parameters except the
4221        innermost ones.  */
4222     parms = TREE_CHAIN (parms);
4223
4224   /* Figure out what error message to issue.  */
4225   if (is_friend_decl == 2)
4226     msg = G_("default template arguments may not be used in function template "
4227              "friend re-declaration");
4228   else if (is_friend_decl)
4229     msg = G_("default template arguments may not be used in function template "
4230              "friend declarations");
4231   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4232     msg = G_("default template arguments may not be used in function templates "
4233              "without -std=c++0x or -std=gnu++0x");
4234   else if (is_partial)
4235     msg = G_("default template arguments may not be used in "
4236              "partial specializations");
4237   else
4238     msg = G_("default argument for template parameter for class enclosing %qD");
4239
4240   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4241     /* If we're inside a class definition, there's no need to
4242        examine the parameters to the class itself.  On the one
4243        hand, they will be checked when the class is defined, and,
4244        on the other, default arguments are valid in things like:
4245          template <class T = double>
4246          struct S { template <class U> void f(U); };
4247        Here the default argument for `S' has no bearing on the
4248        declaration of `f'.  */
4249     last_level_to_check = template_class_depth (current_class_type) + 1;
4250   else
4251     /* Check everything.  */
4252     last_level_to_check = 0;
4253
4254   for (parm_level = parms;
4255        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4256        parm_level = TREE_CHAIN (parm_level))
4257     {
4258       tree inner_parms = TREE_VALUE (parm_level);
4259       int i;
4260       int ntparms;
4261
4262       ntparms = TREE_VEC_LENGTH (inner_parms);
4263       for (i = 0; i < ntparms; ++i)
4264         {
4265           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4266             continue;
4267
4268           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4269             {
4270               if (msg)
4271                 {
4272                   no_errors = false;
4273                   if (is_friend_decl == 2)
4274                     return no_errors;
4275
4276                   error (msg, decl);
4277                   msg = 0;
4278                 }
4279
4280               /* Clear out the default argument so that we are not
4281                  confused later.  */
4282               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4283             }
4284         }
4285
4286       /* At this point, if we're still interested in issuing messages,
4287          they must apply to classes surrounding the object declared.  */
4288       if (msg)
4289         msg = G_("default argument for template parameter for class "
4290                  "enclosing %qD");
4291     }
4292
4293   return no_errors;
4294 }
4295
4296 /* Worker for push_template_decl_real, called via
4297    for_each_template_parm.  DATA is really an int, indicating the
4298    level of the parameters we are interested in.  If T is a template
4299    parameter of that level, return nonzero.  */
4300
4301 static int
4302 template_parm_this_level_p (tree t, void* data)
4303 {
4304   int this_level = *(int *)data;
4305   int level;
4306
4307   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4308     level = TEMPLATE_PARM_LEVEL (t);
4309   else
4310     level = TEMPLATE_TYPE_LEVEL (t);
4311   return level == this_level;
4312 }
4313
4314 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4315    parameters given by current_template_args, or reuses a
4316    previously existing one, if appropriate.  Returns the DECL, or an
4317    equivalent one, if it is replaced via a call to duplicate_decls.
4318
4319    If IS_FRIEND is true, DECL is a friend declaration.  */
4320
4321 tree
4322 push_template_decl_real (tree decl, bool is_friend)
4323 {
4324   tree tmpl;
4325   tree args;
4326   tree info;
4327   tree ctx;
4328   int primary;
4329   int is_partial;
4330   int new_template_p = 0;
4331   /* True if the template is a member template, in the sense of
4332      [temp.mem].  */
4333   bool member_template_p = false;
4334
4335   if (decl == error_mark_node || !current_template_parms)
4336     return error_mark_node;
4337
4338   /* See if this is a partial specialization.  */
4339   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4340                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4341                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4342
4343   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4344     is_friend = true;
4345
4346   if (is_friend)
4347     /* For a friend, we want the context of the friend function, not
4348        the type of which it is a friend.  */
4349     ctx = DECL_CONTEXT (decl);
4350   else if (CP_DECL_CONTEXT (decl)
4351            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4352     /* In the case of a virtual function, we want the class in which
4353        it is defined.  */
4354     ctx = CP_DECL_CONTEXT (decl);
4355   else
4356     /* Otherwise, if we're currently defining some class, the DECL
4357        is assumed to be a member of the class.  */
4358     ctx = current_scope ();
4359
4360   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4361     ctx = NULL_TREE;
4362
4363   if (!DECL_CONTEXT (decl))
4364     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4365
4366   /* See if this is a primary template.  */
4367   if (is_friend && ctx)
4368     /* A friend template that specifies a class context, i.e.
4369          template <typename T> friend void A<T>::f();
4370        is not primary.  */
4371     primary = 0;
4372   else
4373     primary = template_parm_scope_p ();
4374
4375   if (primary)
4376     {
4377       if (DECL_CLASS_SCOPE_P (decl))
4378         member_template_p = true;
4379       if (TREE_CODE (decl) == TYPE_DECL
4380           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4381         {
4382           error ("template class without a name");
4383           return error_mark_node;
4384         }
4385       else if (TREE_CODE (decl) == FUNCTION_DECL)
4386         {
4387           if (DECL_DESTRUCTOR_P (decl))
4388             {
4389               /* [temp.mem]
4390
4391                  A destructor shall not be a member template.  */
4392               error ("destructor %qD declared as member template", decl);
4393               return error_mark_node;
4394             }
4395           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4396               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4397                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4398                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4399                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4400                       == void_list_node)))
4401             {
4402               /* [basic.stc.dynamic.allocation]
4403
4404                  An allocation function can be a function
4405                  template. ... Template allocation functions shall
4406                  have two or more parameters.  */
4407               error ("invalid template declaration of %qD", decl);
4408               return error_mark_node;
4409             }
4410         }
4411       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4412                && CLASS_TYPE_P (TREE_TYPE (decl)))
4413         /* OK */;
4414       else
4415         {
4416           error ("template declaration of %q#D", decl);
4417           return error_mark_node;
4418         }
4419     }
4420
4421   /* Check to see that the rules regarding the use of default
4422      arguments are not being violated.  */
4423   check_default_tmpl_args (decl, current_template_parms,
4424                            primary, is_partial, /*is_friend_decl=*/0);
4425
4426   /* Ensure that there are no parameter packs in the type of this
4427      declaration that have not been expanded.  */
4428   if (TREE_CODE (decl) == FUNCTION_DECL)
4429     {
4430       /* Check each of the arguments individually to see if there are
4431          any bare parameter packs.  */
4432       tree type = TREE_TYPE (decl);
4433       tree arg = DECL_ARGUMENTS (decl);
4434       tree argtype = TYPE_ARG_TYPES (type);
4435
4436       while (arg && argtype)
4437         {
4438           if (!FUNCTION_PARAMETER_PACK_P (arg)
4439               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4440             {
4441             /* This is a PARM_DECL that contains unexpanded parameter
4442                packs. We have already complained about this in the
4443                check_for_bare_parameter_packs call, so just replace
4444                these types with ERROR_MARK_NODE.  */
4445               TREE_TYPE (arg) = error_mark_node;
4446               TREE_VALUE (argtype) = error_mark_node;
4447             }
4448
4449           arg = DECL_CHAIN (arg);
4450           argtype = TREE_CHAIN (argtype);
4451         }
4452
4453       /* Check for bare parameter packs in the return type and the
4454          exception specifiers.  */
4455       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4456         /* Errors were already issued, set return type to int
4457            as the frontend doesn't expect error_mark_node as
4458            the return type.  */
4459         TREE_TYPE (type) = integer_type_node;
4460       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4461         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4462     }
4463   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4464     {
4465       TREE_TYPE (decl) = error_mark_node;
4466       return error_mark_node;
4467     }
4468
4469   if (is_partial)
4470     return process_partial_specialization (decl);
4471
4472   args = current_template_args ();
4473
4474   if (!ctx
4475       || TREE_CODE (ctx) == FUNCTION_DECL
4476       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4477       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4478     {
4479       if (DECL_LANG_SPECIFIC (decl)
4480           && DECL_TEMPLATE_INFO (decl)
4481           && DECL_TI_TEMPLATE (decl))
4482         tmpl = DECL_TI_TEMPLATE (decl);
4483       /* If DECL is a TYPE_DECL for a class-template, then there won't
4484          be DECL_LANG_SPECIFIC.  The information equivalent to
4485          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4486       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4487                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4488                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4489         {
4490           /* Since a template declaration already existed for this
4491              class-type, we must be redeclaring it here.  Make sure
4492              that the redeclaration is valid.  */
4493           redeclare_class_template (TREE_TYPE (decl),
4494                                     current_template_parms);
4495           /* We don't need to create a new TEMPLATE_DECL; just use the
4496              one we already had.  */
4497           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4498         }
4499       else
4500         {
4501           tmpl = build_template_decl (decl, current_template_parms,
4502                                       member_template_p);
4503           new_template_p = 1;
4504
4505           if (DECL_LANG_SPECIFIC (decl)
4506               && DECL_TEMPLATE_SPECIALIZATION (decl))
4507             {
4508               /* A specialization of a member template of a template
4509                  class.  */
4510               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4511               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4512               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4513             }
4514         }
4515     }
4516   else
4517     {
4518       tree a, t, current, parms;
4519       int i;
4520       tree tinfo = get_template_info (decl);
4521
4522       if (!tinfo)
4523         {
4524           error ("template definition of non-template %q#D", decl);
4525           return error_mark_node;
4526         }
4527
4528       tmpl = TI_TEMPLATE (tinfo);
4529
4530       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4531           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4532           && DECL_TEMPLATE_SPECIALIZATION (decl)
4533           && DECL_MEMBER_TEMPLATE_P (tmpl))
4534         {
4535           tree new_tmpl;
4536
4537           /* The declaration is a specialization of a member
4538              template, declared outside the class.  Therefore, the
4539              innermost template arguments will be NULL, so we
4540              replace them with the arguments determined by the
4541              earlier call to check_explicit_specialization.  */
4542           args = DECL_TI_ARGS (decl);
4543
4544           new_tmpl
4545             = build_template_decl (decl, current_template_parms,
4546                                    member_template_p);
4547           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4548           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4549           DECL_TI_TEMPLATE (decl) = new_tmpl;
4550           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4551           DECL_TEMPLATE_INFO (new_tmpl)
4552             = build_template_info (tmpl, args);
4553
4554           register_specialization (new_tmpl,
4555                                    most_general_template (tmpl),
4556                                    args,
4557                                    is_friend, 0);
4558           return decl;
4559         }
4560
4561       /* Make sure the template headers we got make sense.  */
4562
4563       parms = DECL_TEMPLATE_PARMS (tmpl);
4564       i = TMPL_PARMS_DEPTH (parms);
4565       if (TMPL_ARGS_DEPTH (args) != i)
4566         {
4567           error ("expected %d levels of template parms for %q#D, got %d",
4568                  i, decl, TMPL_ARGS_DEPTH (args));
4569         }
4570       else
4571         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4572           {
4573             a = TMPL_ARGS_LEVEL (args, i);
4574             t = INNERMOST_TEMPLATE_PARMS (parms);
4575
4576             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4577               {
4578                 if (current == decl)
4579                   error ("got %d template parameters for %q#D",
4580                          TREE_VEC_LENGTH (a), decl);
4581                 else
4582                   error ("got %d template parameters for %q#T",
4583                          TREE_VEC_LENGTH (a), current);
4584                 error ("  but %d required", TREE_VEC_LENGTH (t));
4585                 return error_mark_node;
4586               }
4587
4588             if (current == decl)
4589               current = ctx;
4590             else if (current == NULL_TREE)
4591               /* Can happen in erroneous input.  */
4592               break;
4593             else
4594               current = (TYPE_P (current)
4595                          ? TYPE_CONTEXT (current)
4596                          : DECL_CONTEXT (current));
4597           }
4598
4599       /* Check that the parms are used in the appropriate qualifying scopes
4600          in the declarator.  */
4601       if (!comp_template_args
4602           (TI_ARGS (tinfo),
4603            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4604         {
4605           error ("\
4606 template arguments to %qD do not match original template %qD",
4607                  decl, DECL_TEMPLATE_RESULT (tmpl));
4608           if (!uses_template_parms (TI_ARGS (tinfo)))
4609             inform (input_location, "use template<> for an explicit specialization");
4610           /* Avoid crash in import_export_decl.  */
4611           DECL_INTERFACE_KNOWN (decl) = 1;
4612           return error_mark_node;
4613         }
4614     }
4615
4616   DECL_TEMPLATE_RESULT (tmpl) = decl;
4617   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4618
4619   /* Push template declarations for global functions and types.  Note
4620      that we do not try to push a global template friend declared in a
4621      template class; such a thing may well depend on the template
4622      parameters of the class.  */
4623   if (new_template_p && !ctx
4624       && !(is_friend && template_class_depth (current_class_type) > 0))
4625     {
4626       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4627       if (tmpl == error_mark_node)
4628         return error_mark_node;
4629
4630       /* Hide template friend classes that haven't been declared yet.  */
4631       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4632         {
4633           DECL_ANTICIPATED (tmpl) = 1;
4634           DECL_FRIEND_P (tmpl) = 1;
4635         }
4636     }
4637
4638   if (primary)
4639     {
4640       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4641       int i;
4642
4643       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4644       if (DECL_CONV_FN_P (tmpl))
4645         {
4646           int depth = TMPL_PARMS_DEPTH (parms);
4647
4648           /* It is a conversion operator. See if the type converted to
4649              depends on innermost template operands.  */
4650
4651           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4652                                          depth))
4653             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4654         }
4655
4656       /* Give template template parms a DECL_CONTEXT of the template
4657          for which they are a parameter.  */
4658       parms = INNERMOST_TEMPLATE_PARMS (parms);
4659       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4660         {
4661           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4662           if (TREE_CODE (parm) == TEMPLATE_DECL)
4663             DECL_CONTEXT (parm) = tmpl;
4664         }
4665     }
4666
4667   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4668      back to its most general template.  If TMPL is a specialization,
4669      ARGS may only have the innermost set of arguments.  Add the missing
4670      argument levels if necessary.  */
4671   if (DECL_TEMPLATE_INFO (tmpl))
4672     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4673
4674   info = build_template_info (tmpl, args);
4675
4676   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4677     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4678   else if (DECL_LANG_SPECIFIC (decl))
4679     DECL_TEMPLATE_INFO (decl) = info;
4680
4681   return DECL_TEMPLATE_RESULT (tmpl);
4682 }
4683
4684 tree
4685 push_template_decl (tree decl)
4686 {
4687   return push_template_decl_real (decl, false);
4688 }
4689
4690 /* Called when a class template TYPE is redeclared with the indicated
4691    template PARMS, e.g.:
4692
4693      template <class T> struct S;
4694      template <class T> struct S {};  */
4695
4696 bool
4697 redeclare_class_template (tree type, tree parms)
4698 {
4699   tree tmpl;
4700   tree tmpl_parms;
4701   int i;
4702
4703   if (!TYPE_TEMPLATE_INFO (type))
4704     {
4705       error ("%qT is not a template type", type);
4706       return false;
4707     }
4708
4709   tmpl = TYPE_TI_TEMPLATE (type);
4710   if (!PRIMARY_TEMPLATE_P (tmpl))
4711     /* The type is nested in some template class.  Nothing to worry
4712        about here; there are no new template parameters for the nested
4713        type.  */
4714     return true;
4715
4716   if (!parms)
4717     {
4718       error ("template specifiers not specified in declaration of %qD",
4719              tmpl);
4720       return false;
4721     }
4722
4723   parms = INNERMOST_TEMPLATE_PARMS (parms);
4724   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4725
4726   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4727     {
4728       error_n (input_location, TREE_VEC_LENGTH (parms),
4729                "redeclared with %d template parameter",
4730                "redeclared with %d template parameters",
4731                TREE_VEC_LENGTH (parms));
4732       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
4733                 "previous declaration %q+D used %d template parameter",
4734                 "previous declaration %q+D used %d template parameters",
4735                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
4736       return false;
4737     }
4738
4739   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4740     {
4741       tree tmpl_parm;
4742       tree parm;
4743       tree tmpl_default;
4744       tree parm_default;
4745
4746       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4747           || TREE_VEC_ELT (parms, i) == error_mark_node)
4748         continue;
4749
4750       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4751       if (tmpl_parm == error_mark_node)
4752         return false;
4753
4754       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4755       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4756       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4757
4758       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4759          TEMPLATE_DECL.  */
4760       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4761           || (TREE_CODE (tmpl_parm) != TYPE_DECL
4762               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4763           || (TREE_CODE (tmpl_parm) != PARM_DECL
4764               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4765                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4766           || (TREE_CODE (tmpl_parm) == PARM_DECL
4767               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4768                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
4769         {
4770           error ("template parameter %q+#D", tmpl_parm);
4771           error ("redeclared here as %q#D", parm);
4772           return false;
4773         }
4774
4775       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4776         {
4777           /* We have in [temp.param]:
4778
4779              A template-parameter may not be given default arguments
4780              by two different declarations in the same scope.  */
4781           error_at (input_location, "redefinition of default argument for %q#D", parm);
4782           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4783                   "original definition appeared here");
4784           return false;
4785         }
4786
4787       if (parm_default != NULL_TREE)
4788         /* Update the previous template parameters (which are the ones
4789            that will really count) with the new default value.  */
4790         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4791       else if (tmpl_default != NULL_TREE)
4792         /* Update the new parameters, too; they'll be used as the
4793            parameters for any members.  */
4794         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4795     }
4796
4797     return true;
4798 }
4799
4800 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4801    (possibly simplified) expression.  */
4802
4803 tree
4804 fold_non_dependent_expr (tree expr)
4805 {
4806   if (expr == NULL_TREE)
4807     return NULL_TREE;
4808
4809   /* If we're in a template, but EXPR isn't value dependent, simplify
4810      it.  We're supposed to treat:
4811
4812        template <typename T> void f(T[1 + 1]);
4813        template <typename T> void f(T[2]);
4814
4815      as two declarations of the same function, for example.  */
4816   if (processing_template_decl
4817       && !type_dependent_expression_p (expr)
4818       && !value_dependent_expression_p (expr))
4819     {
4820       HOST_WIDE_INT saved_processing_template_decl;
4821
4822       saved_processing_template_decl = processing_template_decl;
4823       processing_template_decl = 0;
4824       expr = tsubst_copy_and_build (expr,
4825                                     /*args=*/NULL_TREE,
4826                                     tf_error,
4827                                     /*in_decl=*/NULL_TREE,
4828                                     /*function_p=*/false,
4829                                     /*integral_constant_expression_p=*/true);
4830       processing_template_decl = saved_processing_template_decl;
4831     }
4832   return expr;
4833 }
4834
4835 /* EXPR is an expression which is used in a constant-expression context.
4836    For instance, it could be a VAR_DECL with a constant initializer.
4837    Extract the innermost constant expression.
4838
4839    This is basically a more powerful version of
4840    integral_constant_value, which can be used also in templates where
4841    initializers can maintain a syntactic rather than semantic form
4842    (even if they are non-dependent, for access-checking purposes).  */
4843
4844 static tree
4845 fold_decl_constant_value (tree expr)
4846 {
4847   tree const_expr = expr;
4848   do
4849     {
4850       expr = fold_non_dependent_expr (const_expr);
4851       const_expr = integral_constant_value (expr);
4852     }
4853   while (expr != const_expr);
4854
4855   return expr;
4856 }
4857
4858 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4859    must be a function or a pointer-to-function type, as specified
4860    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4861    and check that the resulting function has external linkage.  */
4862
4863 static tree
4864 convert_nontype_argument_function (tree type, tree expr)
4865 {
4866   tree fns = expr;
4867   tree fn, fn_no_ptr;
4868
4869   fn = instantiate_type (type, fns, tf_none);
4870   if (fn == error_mark_node)
4871     return error_mark_node;
4872
4873   fn_no_ptr = fn;
4874   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4875     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4876   if (TREE_CODE (fn_no_ptr) == BASELINK)
4877     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4878  
4879   /* [temp.arg.nontype]/1
4880
4881      A template-argument for a non-type, non-template template-parameter
4882      shall be one of:
4883      [...]
4884      -- the address of an object or function with external linkage.  */
4885   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4886     {
4887       error ("%qE is not a valid template argument for type %qT "
4888              "because function %qD has not external linkage",
4889              expr, type, fn_no_ptr);
4890       return NULL_TREE;
4891     }
4892
4893   return fn;
4894 }
4895
4896 /* Subroutine of convert_nontype_argument.
4897    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4898    Emit an error otherwise.  */
4899
4900 static bool
4901 check_valid_ptrmem_cst_expr (tree type, tree expr)
4902 {
4903   STRIP_NOPS (expr);
4904   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4905     return true;
4906   error ("%qE is not a valid template argument for type %qT",
4907          expr, type);
4908   error ("it must be a pointer-to-member of the form `&X::Y'");
4909   return false;
4910 }
4911
4912 /* Returns TRUE iff the address of OP is value-dependent.
4913
4914    14.6.2.4 [temp.dep.temp]:
4915    A non-integral non-type template-argument is dependent if its type is
4916    dependent or it has either of the following forms
4917      qualified-id
4918      & qualified-id
4919    and contains a nested-name-specifier which specifies a class-name that
4920    names a dependent type.
4921
4922    We generalize this to just say that the address of a member of a
4923    dependent class is value-dependent; the above doesn't cover the
4924    address of a static data member named with an unqualified-id.  */
4925
4926 static bool
4927 has_value_dependent_address (tree op)
4928 {
4929   /* We could use get_inner_reference here, but there's no need;
4930      this is only relevant for template non-type arguments, which
4931      can only be expressed as &id-expression.  */
4932   if (DECL_P (op))
4933     {
4934       tree ctx = CP_DECL_CONTEXT (op);
4935       if (TYPE_P (ctx) && dependent_type_p (ctx))
4936         return true;
4937     }
4938
4939   return false;
4940 }
4941
4942 /* Attempt to convert the non-type template parameter EXPR to the
4943    indicated TYPE.  If the conversion is successful, return the
4944    converted value.  If the conversion is unsuccessful, return
4945    NULL_TREE if we issued an error message, or error_mark_node if we
4946    did not.  We issue error messages for out-and-out bad template
4947    parameters, but not simply because the conversion failed, since we
4948    might be just trying to do argument deduction.  Both TYPE and EXPR
4949    must be non-dependent.
4950
4951    The conversion follows the special rules described in
4952    [temp.arg.nontype], and it is much more strict than an implicit
4953    conversion.
4954
4955    This function is called twice for each template argument (see
4956    lookup_template_class for a more accurate description of this
4957    problem). This means that we need to handle expressions which
4958    are not valid in a C++ source, but can be created from the
4959    first call (for instance, casts to perform conversions). These
4960    hacks can go away after we fix the double coercion problem.  */
4961
4962 static tree
4963 convert_nontype_argument (tree type, tree expr)
4964 {
4965   tree expr_type;
4966
4967   /* Detect immediately string literals as invalid non-type argument.
4968      This special-case is not needed for correctness (we would easily
4969      catch this later), but only to provide better diagnostic for this
4970      common user mistake. As suggested by DR 100, we do not mention
4971      linkage issues in the diagnostic as this is not the point.  */
4972   if (TREE_CODE (expr) == STRING_CST)
4973     {
4974       error ("%qE is not a valid template argument for type %qT "
4975              "because string literals can never be used in this context",
4976              expr, type);
4977       return NULL_TREE;
4978     }
4979
4980   /* Add the ADDR_EXPR now for the benefit of
4981      value_dependent_expression_p.  */
4982   if (TYPE_PTROBV_P (type))
4983     expr = decay_conversion (expr);
4984
4985   /* If we are in a template, EXPR may be non-dependent, but still
4986      have a syntactic, rather than semantic, form.  For example, EXPR
4987      might be a SCOPE_REF, rather than the VAR_DECL to which the
4988      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4989      so that access checking can be performed when the template is
4990      instantiated -- but here we need the resolved form so that we can
4991      convert the argument.  */
4992   if (TYPE_REF_OBJ_P (type)
4993       && has_value_dependent_address (expr))
4994     /* If we want the address and it's value-dependent, don't fold.  */;
4995   else
4996     expr = fold_non_dependent_expr (expr);
4997   if (error_operand_p (expr))
4998     return error_mark_node;
4999   expr_type = TREE_TYPE (expr);
5000   if (TREE_CODE (type) == REFERENCE_TYPE)
5001     expr = mark_lvalue_use (expr);
5002   else
5003     expr = mark_rvalue_use (expr);
5004
5005   /* HACK: Due to double coercion, we can get a
5006      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5007      which is the tree that we built on the first call (see
5008      below when coercing to reference to object or to reference to
5009      function). We just strip everything and get to the arg.
5010      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5011      for examples.  */
5012   if (TREE_CODE (expr) == NOP_EXPR)
5013     {
5014       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5015         {
5016           /* ??? Maybe we could use convert_from_reference here, but we
5017              would need to relax its constraints because the NOP_EXPR
5018              could actually change the type to something more cv-qualified,
5019              and this is not folded by convert_from_reference.  */
5020           tree addr = TREE_OPERAND (expr, 0);
5021           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
5022           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5023           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5024           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5025                       (TREE_TYPE (expr_type),
5026                        TREE_TYPE (TREE_TYPE (addr))));
5027
5028           expr = TREE_OPERAND (addr, 0);
5029           expr_type = TREE_TYPE (expr);
5030         }
5031
5032       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5033          parameter is a pointer to object, through decay and
5034          qualification conversion. Let's strip everything.  */
5035       else if (TYPE_PTROBV_P (type))
5036         {
5037           STRIP_NOPS (expr);
5038           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5039           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5040           /* Skip the ADDR_EXPR only if it is part of the decay for
5041              an array. Otherwise, it is part of the original argument
5042              in the source code.  */
5043           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5044             expr = TREE_OPERAND (expr, 0);
5045           expr_type = TREE_TYPE (expr);
5046         }
5047     }
5048
5049   /* [temp.arg.nontype]/5, bullet 1
5050
5051      For a non-type template-parameter of integral or enumeration type,
5052      integral promotions (_conv.prom_) and integral conversions
5053      (_conv.integral_) are applied.  */
5054   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5055     {
5056       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
5057         return error_mark_node;
5058
5059       expr = fold_decl_constant_value (expr);
5060       /* Notice that there are constant expressions like '4 % 0' which
5061          do not fold into integer constants.  */
5062       if (TREE_CODE (expr) != INTEGER_CST)
5063         {
5064           error ("%qE is not a valid template argument for type %qT "
5065                  "because it is a non-constant expression", expr, type);
5066           return NULL_TREE;
5067         }
5068
5069       /* At this point, an implicit conversion does what we want,
5070          because we already know that the expression is of integral
5071          type.  */
5072       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
5073       if (expr == error_mark_node)
5074         return error_mark_node;
5075
5076       /* Conversion was allowed: fold it to a bare integer constant.  */
5077       expr = fold (expr);
5078     }
5079   /* [temp.arg.nontype]/5, bullet 2
5080
5081      For a non-type template-parameter of type pointer to object,
5082      qualification conversions (_conv.qual_) and the array-to-pointer
5083      conversion (_conv.array_) are applied.  */
5084   else if (TYPE_PTROBV_P (type))
5085     {
5086       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5087
5088          A template-argument for a non-type, non-template template-parameter
5089          shall be one of: [...]
5090
5091          -- the name of a non-type template-parameter;
5092          -- the address of an object or function with external linkage, [...]
5093             expressed as "& id-expression" where the & is optional if the name
5094             refers to a function or array, or if the corresponding
5095             template-parameter is a reference.
5096
5097         Here, we do not care about functions, as they are invalid anyway
5098         for a parameter of type pointer-to-object.  */
5099
5100       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5101         /* Non-type template parameters are OK.  */
5102         ;
5103       else if (TREE_CODE (expr) != ADDR_EXPR
5104                && TREE_CODE (expr_type) != ARRAY_TYPE)
5105         {
5106           if (TREE_CODE (expr) == VAR_DECL)
5107             {
5108               error ("%qD is not a valid template argument "
5109                      "because %qD is a variable, not the address of "
5110                      "a variable",
5111                      expr, expr);
5112               return NULL_TREE;
5113             }
5114           /* Other values, like integer constants, might be valid
5115              non-type arguments of some other type.  */
5116           return error_mark_node;
5117         }
5118       else
5119         {
5120           tree decl;
5121
5122           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5123                   ? TREE_OPERAND (expr, 0) : expr);
5124           if (TREE_CODE (decl) != VAR_DECL)
5125             {
5126               error ("%qE is not a valid template argument of type %qT "
5127                      "because %qE is not a variable",
5128                      expr, type, decl);
5129               return NULL_TREE;
5130             }
5131           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5132             {
5133               error ("%qE is not a valid template argument of type %qT "
5134                      "because %qD does not have external linkage",
5135                      expr, type, decl);
5136               return NULL_TREE;
5137             }
5138         }
5139
5140       expr = decay_conversion (expr);
5141       if (expr == error_mark_node)
5142         return error_mark_node;
5143
5144       expr = perform_qualification_conversions (type, expr);
5145       if (expr == error_mark_node)
5146         return error_mark_node;
5147     }
5148   /* [temp.arg.nontype]/5, bullet 3
5149
5150      For a non-type template-parameter of type reference to object, no
5151      conversions apply. The type referred to by the reference may be more
5152      cv-qualified than the (otherwise identical) type of the
5153      template-argument. The template-parameter is bound directly to the
5154      template-argument, which must be an lvalue.  */
5155   else if (TYPE_REF_OBJ_P (type))
5156     {
5157       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5158                                                       expr_type))
5159         return error_mark_node;
5160
5161       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5162         {
5163           error ("%qE is not a valid template argument for type %qT "
5164                  "because of conflicts in cv-qualification", expr, type);
5165           return NULL_TREE;
5166         }
5167
5168       if (!real_lvalue_p (expr))
5169         {
5170           error ("%qE is not a valid template argument for type %qT "
5171                  "because it is not an lvalue", expr, type);
5172           return NULL_TREE;
5173         }
5174
5175       /* [temp.arg.nontype]/1
5176
5177          A template-argument for a non-type, non-template template-parameter
5178          shall be one of: [...]
5179
5180          -- the address of an object or function with external linkage.  */
5181       if (TREE_CODE (expr) == INDIRECT_REF
5182           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5183         {
5184           expr = TREE_OPERAND (expr, 0);
5185           if (DECL_P (expr))
5186             {
5187               error ("%q#D is not a valid template argument for type %qT "
5188                      "because a reference variable does not have a constant "
5189                      "address", expr, type);
5190               return NULL_TREE;
5191             }
5192         }
5193
5194       if (!DECL_P (expr))
5195         {
5196           error ("%qE is not a valid template argument for type %qT "
5197                  "because it is not an object with external linkage",
5198                  expr, type);
5199           return NULL_TREE;
5200         }
5201
5202       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5203         {
5204           error ("%qE is not a valid template argument for type %qT "
5205                  "because object %qD has not external linkage",
5206                  expr, type, expr);
5207           return NULL_TREE;
5208         }
5209
5210       expr = build_nop (type, build_address (expr));
5211     }
5212   /* [temp.arg.nontype]/5, bullet 4
5213
5214      For a non-type template-parameter of type pointer to function, only
5215      the function-to-pointer conversion (_conv.func_) is applied. If the
5216      template-argument represents a set of overloaded functions (or a
5217      pointer to such), the matching function is selected from the set
5218      (_over.over_).  */
5219   else if (TYPE_PTRFN_P (type))
5220     {
5221       /* If the argument is a template-id, we might not have enough
5222          context information to decay the pointer.  */
5223       if (!type_unknown_p (expr_type))
5224         {
5225           expr = decay_conversion (expr);
5226           if (expr == error_mark_node)
5227             return error_mark_node;
5228         }
5229
5230       expr = convert_nontype_argument_function (type, expr);
5231       if (!expr || expr == error_mark_node)
5232         return expr;
5233
5234       if (TREE_CODE (expr) != ADDR_EXPR)
5235         {
5236           error ("%qE is not a valid template argument for type %qT", expr, type);
5237           error ("it must be the address of a function with external linkage");
5238           return NULL_TREE;
5239         }
5240     }
5241   /* [temp.arg.nontype]/5, bullet 5
5242
5243      For a non-type template-parameter of type reference to function, no
5244      conversions apply. If the template-argument represents a set of
5245      overloaded functions, the matching function is selected from the set
5246      (_over.over_).  */
5247   else if (TYPE_REFFN_P (type))
5248     {
5249       if (TREE_CODE (expr) == ADDR_EXPR)
5250         {
5251           error ("%qE is not a valid template argument for type %qT "
5252                  "because it is a pointer", expr, type);
5253           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5254           return NULL_TREE;
5255         }
5256
5257       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5258       if (!expr || expr == error_mark_node)
5259         return expr;
5260
5261       expr = build_nop (type, build_address (expr));
5262     }
5263   /* [temp.arg.nontype]/5, bullet 6
5264
5265      For a non-type template-parameter of type pointer to member function,
5266      no conversions apply. If the template-argument represents a set of
5267      overloaded member functions, the matching member function is selected
5268      from the set (_over.over_).  */
5269   else if (TYPE_PTRMEMFUNC_P (type))
5270     {
5271       expr = instantiate_type (type, expr, tf_none);
5272       if (expr == error_mark_node)
5273         return error_mark_node;
5274
5275       /* [temp.arg.nontype] bullet 1 says the pointer to member
5276          expression must be a pointer-to-member constant.  */
5277       if (!check_valid_ptrmem_cst_expr (type, expr))
5278         return error_mark_node;
5279
5280       /* There is no way to disable standard conversions in
5281          resolve_address_of_overloaded_function (called by
5282          instantiate_type). It is possible that the call succeeded by
5283          converting &B::I to &D::I (where B is a base of D), so we need
5284          to reject this conversion here.
5285
5286          Actually, even if there was a way to disable standard conversions,
5287          it would still be better to reject them here so that we can
5288          provide a superior diagnostic.  */
5289       if (!same_type_p (TREE_TYPE (expr), type))
5290         {
5291           error ("%qE is not a valid template argument for type %qT "
5292                  "because it is of type %qT", expr, type,
5293                  TREE_TYPE (expr));
5294           /* If we are just one standard conversion off, explain.  */
5295           if (can_convert (type, TREE_TYPE (expr)))
5296             inform (input_location,
5297                     "standard conversions are not allowed in this context");
5298           return NULL_TREE;
5299         }
5300     }
5301   /* [temp.arg.nontype]/5, bullet 7
5302
5303      For a non-type template-parameter of type pointer to data member,
5304      qualification conversions (_conv.qual_) are applied.  */
5305   else if (TYPE_PTRMEM_P (type))
5306     {
5307       /* [temp.arg.nontype] bullet 1 says the pointer to member
5308          expression must be a pointer-to-member constant.  */
5309       if (!check_valid_ptrmem_cst_expr (type, expr))
5310         return error_mark_node;
5311
5312       expr = perform_qualification_conversions (type, expr);
5313       if (expr == error_mark_node)
5314         return expr;
5315     }
5316   /* A template non-type parameter must be one of the above.  */
5317   else
5318     gcc_unreachable ();
5319
5320   /* Sanity check: did we actually convert the argument to the
5321      right type?  */
5322   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5323   return expr;
5324 }
5325
5326 /* Subroutine of coerce_template_template_parms, which returns 1 if
5327    PARM_PARM and ARG_PARM match using the rule for the template
5328    parameters of template template parameters. Both PARM and ARG are
5329    template parameters; the rest of the arguments are the same as for
5330    coerce_template_template_parms.
5331  */
5332 static int
5333 coerce_template_template_parm (tree parm,
5334                               tree arg,
5335                               tsubst_flags_t complain,
5336                               tree in_decl,
5337                               tree outer_args)
5338 {
5339   if (arg == NULL_TREE || arg == error_mark_node
5340       || parm == NULL_TREE || parm == error_mark_node)
5341     return 0;
5342   
5343   if (TREE_CODE (arg) != TREE_CODE (parm))
5344     return 0;
5345   
5346   switch (TREE_CODE (parm))
5347     {
5348     case TEMPLATE_DECL:
5349       /* We encounter instantiations of templates like
5350          template <template <template <class> class> class TT>
5351          class C;  */
5352       {
5353         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5354         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5355         
5356         if (!coerce_template_template_parms
5357             (parmparm, argparm, complain, in_decl, outer_args))
5358           return 0;
5359       }
5360       /* Fall through.  */
5361       
5362     case TYPE_DECL:
5363       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5364           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5365         /* Argument is a parameter pack but parameter is not.  */
5366         return 0;
5367       break;
5368       
5369     case PARM_DECL:
5370       /* The tsubst call is used to handle cases such as
5371          
5372            template <int> class C {};
5373            template <class T, template <T> class TT> class D {};
5374            D<int, C> d;
5375
5376          i.e. the parameter list of TT depends on earlier parameters.  */
5377       if (!uses_template_parms (TREE_TYPE (arg))
5378           && !same_type_p
5379                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5380                  TREE_TYPE (arg)))
5381         return 0;
5382       
5383       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5384           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5385         /* Argument is a parameter pack but parameter is not.  */
5386         return 0;
5387       
5388       break;
5389
5390     default:
5391       gcc_unreachable ();
5392     }
5393
5394   return 1;
5395 }
5396
5397
5398 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5399    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5400    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5401    or PARM_DECL.
5402
5403    Consider the example:
5404      template <class T> class A;
5405      template<template <class U> class TT> class B;
5406
5407    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5408    the parameters to A, and OUTER_ARGS contains A.  */
5409
5410 static int
5411 coerce_template_template_parms (tree parm_parms,
5412                                 tree arg_parms,
5413                                 tsubst_flags_t complain,
5414                                 tree in_decl,
5415                                 tree outer_args)
5416 {
5417   int nparms, nargs, i;
5418   tree parm, arg;
5419   int variadic_p = 0;
5420
5421   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5422   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5423
5424   nparms = TREE_VEC_LENGTH (parm_parms);
5425   nargs = TREE_VEC_LENGTH (arg_parms);
5426
5427   /* Determine whether we have a parameter pack at the end of the
5428      template template parameter's template parameter list.  */
5429   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5430     {
5431       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5432       
5433       if (parm == error_mark_node)
5434         return 0;
5435
5436       switch (TREE_CODE (parm))
5437         {
5438         case TEMPLATE_DECL:
5439         case TYPE_DECL:
5440           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5441             variadic_p = 1;
5442           break;
5443           
5444         case PARM_DECL:
5445           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5446             variadic_p = 1;
5447           break;
5448           
5449         default:
5450           gcc_unreachable ();
5451         }
5452     }
5453  
5454   if (nargs != nparms
5455       && !(variadic_p && nargs >= nparms - 1))
5456     return 0;
5457
5458   /* Check all of the template parameters except the parameter pack at
5459      the end (if any).  */
5460   for (i = 0; i < nparms - variadic_p; ++i)
5461     {
5462       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5463           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5464         continue;
5465
5466       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5467       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5468
5469       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5470                                           outer_args))
5471         return 0;
5472
5473     }
5474
5475   if (variadic_p)
5476     {
5477       /* Check each of the template parameters in the template
5478          argument against the template parameter pack at the end of
5479          the template template parameter.  */
5480       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5481         return 0;
5482
5483       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5484
5485       for (; i < nargs; ++i)
5486         {
5487           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5488             continue;
5489  
5490           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5491  
5492           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5493                                               outer_args))
5494             return 0;
5495         }
5496     }
5497
5498   return 1;
5499 }
5500
5501 /* Verifies that the deduced template arguments (in TARGS) for the
5502    template template parameters (in TPARMS) represent valid bindings,
5503    by comparing the template parameter list of each template argument
5504    to the template parameter list of its corresponding template
5505    template parameter, in accordance with DR150. This
5506    routine can only be called after all template arguments have been
5507    deduced. It will return TRUE if all of the template template
5508    parameter bindings are okay, FALSE otherwise.  */
5509 bool 
5510 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5511 {
5512   int i, ntparms = TREE_VEC_LENGTH (tparms);
5513   bool ret = true;
5514
5515   /* We're dealing with template parms in this process.  */
5516   ++processing_template_decl;
5517
5518   targs = INNERMOST_TEMPLATE_ARGS (targs);
5519
5520   for (i = 0; i < ntparms; ++i)
5521     {
5522       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5523       tree targ = TREE_VEC_ELT (targs, i);
5524
5525       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5526         {
5527           tree packed_args = NULL_TREE;
5528           int idx, len = 1;
5529
5530           if (ARGUMENT_PACK_P (targ))
5531             {
5532               /* Look inside the argument pack.  */
5533               packed_args = ARGUMENT_PACK_ARGS (targ);
5534               len = TREE_VEC_LENGTH (packed_args);
5535             }
5536
5537           for (idx = 0; idx < len; ++idx)
5538             {
5539               tree targ_parms = NULL_TREE;
5540
5541               if (packed_args)
5542                 /* Extract the next argument from the argument
5543                    pack.  */
5544                 targ = TREE_VEC_ELT (packed_args, idx);
5545
5546               if (PACK_EXPANSION_P (targ))
5547                 /* Look at the pattern of the pack expansion.  */
5548                 targ = PACK_EXPANSION_PATTERN (targ);
5549
5550               /* Extract the template parameters from the template
5551                  argument.  */
5552               if (TREE_CODE (targ) == TEMPLATE_DECL)
5553                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5554               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5555                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5556
5557               /* Verify that we can coerce the template template
5558                  parameters from the template argument to the template
5559                  parameter.  This requires an exact match.  */
5560               if (targ_parms
5561                   && !coerce_template_template_parms
5562                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5563                         targ_parms,
5564                         tf_none,
5565                         tparm,
5566                         targs))
5567                 {
5568                   ret = false;
5569                   goto out;
5570                 }
5571             }
5572         }
5573     }
5574
5575  out:
5576
5577   --processing_template_decl;
5578   return ret;
5579 }
5580
5581 /* Convert the indicated template ARG as necessary to match the
5582    indicated template PARM.  Returns the converted ARG, or
5583    error_mark_node if the conversion was unsuccessful.  Error and
5584    warning messages are issued under control of COMPLAIN.  This
5585    conversion is for the Ith parameter in the parameter list.  ARGS is
5586    the full set of template arguments deduced so far.  */
5587
5588 static tree
5589 convert_template_argument (tree parm,
5590                            tree arg,
5591                            tree args,
5592                            tsubst_flags_t complain,
5593                            int i,
5594                            tree in_decl)
5595 {
5596   tree orig_arg;
5597   tree val;
5598   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5599
5600   if (TREE_CODE (arg) == TREE_LIST
5601       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5602     {
5603       /* The template argument was the name of some
5604          member function.  That's usually
5605          invalid, but static members are OK.  In any
5606          case, grab the underlying fields/functions
5607          and issue an error later if required.  */
5608       orig_arg = TREE_VALUE (arg);
5609       TREE_TYPE (arg) = unknown_type_node;
5610     }
5611
5612   orig_arg = arg;
5613
5614   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5615   requires_type = (TREE_CODE (parm) == TYPE_DECL
5616                    || requires_tmpl_type);
5617
5618   /* When determining whether an argument pack expansion is a template,
5619      look at the pattern.  */
5620   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5621     arg = PACK_EXPANSION_PATTERN (arg);
5622
5623   /* Deal with an injected-class-name used as a template template arg.  */
5624   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5625     {
5626       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5627       if (TREE_CODE (t) == TEMPLATE_DECL)
5628         {
5629           if (complain & tf_warning_or_error)
5630             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5631                      " used as template template argument", TYPE_NAME (arg));
5632           else if (flag_pedantic_errors)
5633             t = arg;
5634
5635           arg = t;
5636         }
5637     }
5638
5639   is_tmpl_type = 
5640     ((TREE_CODE (arg) == TEMPLATE_DECL
5641       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5642      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5643      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5644
5645   if (is_tmpl_type
5646       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5647           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5648     arg = TYPE_STUB_DECL (arg);
5649
5650   is_type = TYPE_P (arg) || is_tmpl_type;
5651
5652   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5653       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5654     {
5655       permerror (input_location, "to refer to a type member of a template parameter, "
5656                  "use %<typename %E%>", orig_arg);
5657
5658       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5659                                      TREE_OPERAND (arg, 1),
5660                                      typename_type,
5661                                      complain & tf_error);
5662       arg = orig_arg;
5663       is_type = 1;
5664     }
5665   if (is_type != requires_type)
5666     {
5667       if (in_decl)
5668         {
5669           if (complain & tf_error)
5670             {
5671               error ("type/value mismatch at argument %d in template "
5672                      "parameter list for %qD",
5673                      i + 1, in_decl);
5674               if (is_type)
5675                 error ("  expected a constant of type %qT, got %qT",
5676                        TREE_TYPE (parm),
5677                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5678               else if (requires_tmpl_type)
5679                 error ("  expected a class template, got %qE", orig_arg);
5680               else
5681                 error ("  expected a type, got %qE", orig_arg);
5682             }
5683         }
5684       return error_mark_node;
5685     }
5686   if (is_tmpl_type ^ requires_tmpl_type)
5687     {
5688       if (in_decl && (complain & tf_error))
5689         {
5690           error ("type/value mismatch at argument %d in template "
5691                  "parameter list for %qD",
5692                  i + 1, in_decl);
5693           if (is_tmpl_type)
5694             error ("  expected a type, got %qT", DECL_NAME (arg));
5695           else
5696             error ("  expected a class template, got %qT", orig_arg);
5697         }
5698       return error_mark_node;
5699     }
5700
5701   if (is_type)
5702     {
5703       if (requires_tmpl_type)
5704         {
5705           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5706             /* The number of argument required is not known yet.
5707                Just accept it for now.  */
5708             val = TREE_TYPE (arg);
5709           else
5710             {
5711               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5712               tree argparm;
5713
5714               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5715
5716               if (coerce_template_template_parms (parmparm, argparm,
5717                                                   complain, in_decl,
5718                                                   args))
5719                 {
5720                   val = arg;
5721
5722                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5723                      TEMPLATE_DECL.  */
5724                   if (val != error_mark_node)
5725                     {
5726                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5727                         val = TREE_TYPE (val);
5728                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5729                         val = make_pack_expansion (val);
5730                     }
5731                 }
5732               else
5733                 {
5734                   if (in_decl && (complain & tf_error))
5735                     {
5736                       error ("type/value mismatch at argument %d in "
5737                              "template parameter list for %qD",
5738                              i + 1, in_decl);
5739                       error ("  expected a template of type %qD, got %qT",
5740                              parm, orig_arg);
5741                     }
5742
5743                   val = error_mark_node;
5744                 }
5745             }
5746         }
5747       else
5748         val = orig_arg;
5749       /* We only form one instance of each template specialization.
5750          Therefore, if we use a non-canonical variant (i.e., a
5751          typedef), any future messages referring to the type will use
5752          the typedef, which is confusing if those future uses do not
5753          themselves also use the typedef.  */
5754       if (TYPE_P (val))
5755         val = strip_typedefs (val);
5756     }
5757   else
5758     {
5759       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5760
5761       if (invalid_nontype_parm_type_p (t, complain))
5762         return error_mark_node;
5763
5764       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5765         {
5766           if (same_type_p (t, TREE_TYPE (orig_arg)))
5767             val = orig_arg;
5768           else
5769             {
5770               /* Not sure if this is reachable, but it doesn't hurt
5771                  to be robust.  */
5772               error ("type mismatch in nontype parameter pack");
5773               val = error_mark_node;
5774             }
5775         }
5776       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5777         /* We used to call digest_init here.  However, digest_init
5778            will report errors, which we don't want when complain
5779            is zero.  More importantly, digest_init will try too
5780            hard to convert things: for example, `0' should not be
5781            converted to pointer type at this point according to
5782            the standard.  Accepting this is not merely an
5783            extension, since deciding whether or not these
5784            conversions can occur is part of determining which
5785            function template to call, or whether a given explicit
5786            argument specification is valid.  */
5787         val = convert_nontype_argument (t, orig_arg);
5788       else
5789         val = orig_arg;
5790
5791       if (val == NULL_TREE)
5792         val = error_mark_node;
5793       else if (val == error_mark_node && (complain & tf_error))
5794         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5795
5796       if (TREE_CODE (val) == SCOPE_REF)
5797         {
5798           /* Strip typedefs from the SCOPE_REF.  */
5799           tree type = strip_typedefs (TREE_TYPE (val));
5800           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
5801           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
5802                                       QUALIFIED_NAME_IS_TEMPLATE (val));
5803         }
5804     }
5805
5806   return val;
5807 }
5808
5809 /* Coerces the remaining template arguments in INNER_ARGS (from
5810    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5811    Returns the coerced argument pack. PARM_IDX is the position of this
5812    parameter in the template parameter list. ARGS is the original
5813    template argument list.  */
5814 static tree
5815 coerce_template_parameter_pack (tree parms,
5816                                 int parm_idx,
5817                                 tree args,
5818                                 tree inner_args,
5819                                 int arg_idx,
5820                                 tree new_args,
5821                                 int* lost,
5822                                 tree in_decl,
5823                                 tsubst_flags_t complain)
5824 {
5825   tree parm = TREE_VEC_ELT (parms, parm_idx);
5826   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5827   tree packed_args;
5828   tree argument_pack;
5829   tree packed_types = NULL_TREE;
5830
5831   if (arg_idx > nargs)
5832     arg_idx = nargs;
5833
5834   packed_args = make_tree_vec (nargs - arg_idx);
5835
5836   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5837       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5838     {
5839       /* When the template parameter is a non-type template
5840          parameter pack whose type uses parameter packs, we need
5841          to look at each of the template arguments
5842          separately. Build a vector of the types for these
5843          non-type template parameters in PACKED_TYPES.  */
5844       tree expansion 
5845         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5846       packed_types = tsubst_pack_expansion (expansion, args,
5847                                             complain, in_decl);
5848
5849       if (packed_types == error_mark_node)
5850         return error_mark_node;
5851
5852       /* Check that we have the right number of arguments.  */
5853       if (arg_idx < nargs
5854           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5855           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5856         {
5857           int needed_parms 
5858             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5859           error ("wrong number of template arguments (%d, should be %d)",
5860                  nargs, needed_parms);
5861           return error_mark_node;
5862         }
5863
5864       /* If we aren't able to check the actual arguments now
5865          (because they haven't been expanded yet), we can at least
5866          verify that all of the types used for the non-type
5867          template parameter pack are, in fact, valid for non-type
5868          template parameters.  */
5869       if (arg_idx < nargs 
5870           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5871         {
5872           int j, len = TREE_VEC_LENGTH (packed_types);
5873           for (j = 0; j < len; ++j)
5874             {
5875               tree t = TREE_VEC_ELT (packed_types, j);
5876               if (invalid_nontype_parm_type_p (t, complain))
5877                 return error_mark_node;
5878             }
5879         }
5880     }
5881
5882   /* Convert the remaining arguments, which will be a part of the
5883      parameter pack "parm".  */
5884   for (; arg_idx < nargs; ++arg_idx)
5885     {
5886       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5887       tree actual_parm = TREE_VALUE (parm);
5888
5889       if (packed_types && !PACK_EXPANSION_P (arg))
5890         {
5891           /* When we have a vector of types (corresponding to the
5892              non-type template parameter pack that uses parameter
5893              packs in its type, as mention above), and the
5894              argument is not an expansion (which expands to a
5895              currently unknown number of arguments), clone the
5896              parm and give it the next type in PACKED_TYPES.  */
5897           actual_parm = copy_node (actual_parm);
5898           TREE_TYPE (actual_parm) = 
5899             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5900         }
5901
5902       if (arg != error_mark_node)
5903         arg = convert_template_argument (actual_parm, 
5904                                          arg, new_args, complain, parm_idx,
5905                                          in_decl);
5906       if (arg == error_mark_node)
5907         (*lost)++;
5908       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5909     }
5910
5911   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5912       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5913     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5914   else
5915     {
5916       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5917       TREE_TYPE (argument_pack) 
5918         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5919       TREE_CONSTANT (argument_pack) = 1;
5920     }
5921
5922   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5923 #ifdef ENABLE_CHECKING
5924   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
5925                                        TREE_VEC_LENGTH (packed_args));
5926 #endif
5927   return argument_pack;
5928 }
5929
5930 /* Convert all template arguments to their appropriate types, and
5931    return a vector containing the innermost resulting template
5932    arguments.  If any error occurs, return error_mark_node. Error and
5933    warning messages are issued under control of COMPLAIN.
5934
5935    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5936    for arguments not specified in ARGS.  Otherwise, if
5937    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5938    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5939    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5940    ARGS.  */
5941
5942 static tree
5943 coerce_template_parms (tree parms,
5944                        tree args,
5945                        tree in_decl,
5946                        tsubst_flags_t complain,
5947                        bool require_all_args,
5948                        bool use_default_args)
5949 {
5950   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5951   tree inner_args;
5952   tree new_args;
5953   tree new_inner_args;
5954   int saved_unevaluated_operand;
5955   int saved_inhibit_evaluation_warnings;
5956
5957   /* When used as a boolean value, indicates whether this is a
5958      variadic template parameter list. Since it's an int, we can also
5959      subtract it from nparms to get the number of non-variadic
5960      parameters.  */
5961   int variadic_p = 0;
5962
5963   nparms = TREE_VEC_LENGTH (parms);
5964
5965   /* Determine if there are any parameter packs.  */
5966   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5967     {
5968       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5969       if (template_parameter_pack_p (tparm))
5970         ++variadic_p;
5971     }
5972
5973   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5974   /* If there are 0 or 1 parameter packs, we need to expand any argument
5975      packs so that we can deduce a parameter pack from some non-packed args
5976      followed by an argument pack, as in variadic85.C.  If there are more
5977      than that, we need to leave argument packs intact so the arguments are
5978      assigned to the right parameter packs.  This should only happen when
5979      dealing with a nested class inside a partial specialization of a class
5980      template, as in variadic92.C.  */
5981   if (variadic_p <= 1)
5982     inner_args = expand_template_argument_pack (inner_args);
5983
5984   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5985   if ((nargs > nparms && !variadic_p)
5986       || (nargs < nparms - variadic_p
5987           && require_all_args
5988           && (!use_default_args
5989               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5990                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5991     {
5992       if (complain & tf_error)
5993         {
5994           if (variadic_p)
5995             {
5996               --nparms;
5997               error ("wrong number of template arguments "
5998                      "(%d, should be %d or more)", nargs, nparms);
5999             }
6000           else
6001              error ("wrong number of template arguments "
6002                     "(%d, should be %d)", nargs, nparms);
6003
6004           if (in_decl)
6005             error ("provided for %q+D", in_decl);
6006         }
6007
6008       return error_mark_node;
6009     }
6010
6011   /* We need to evaluate the template arguments, even though this
6012      template-id may be nested within a "sizeof".  */
6013   saved_unevaluated_operand = cp_unevaluated_operand;
6014   cp_unevaluated_operand = 0;
6015   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6016   c_inhibit_evaluation_warnings = 0;
6017   new_inner_args = make_tree_vec (nparms);
6018   new_args = add_outermost_template_args (args, new_inner_args);
6019   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6020     {
6021       tree arg;
6022       tree parm;
6023
6024       /* Get the Ith template parameter.  */
6025       parm = TREE_VEC_ELT (parms, parm_idx);
6026  
6027       if (parm == error_mark_node)
6028       {
6029         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6030         continue;
6031       }
6032
6033       /* Calculate the next argument.  */
6034       if (arg_idx < nargs)
6035         arg = TREE_VEC_ELT (inner_args, arg_idx);
6036       else
6037         arg = NULL_TREE;
6038
6039       if (template_parameter_pack_p (TREE_VALUE (parm))
6040           && !(arg && ARGUMENT_PACK_P (arg)))
6041         {
6042           /* All remaining arguments will be placed in the
6043              template parameter pack PARM.  */
6044           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6045                                                 inner_args, arg_idx,
6046                                                 new_args, &lost,
6047                                                 in_decl, complain);
6048
6049           /* Store this argument.  */
6050           if (arg == error_mark_node)
6051             lost++;
6052           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6053
6054           /* We are done with all of the arguments.  */
6055           arg_idx = nargs;
6056           
6057           continue;
6058         }
6059       else if (arg)
6060         {
6061           if (PACK_EXPANSION_P (arg))
6062             {
6063               if (complain & tf_error)
6064                 {
6065                   /* FIXME this restriction was removed by N2555; see
6066                      bug 35722.  */
6067                   /* If ARG is a pack expansion, but PARM is not a
6068                      template parameter pack (if it were, we would have
6069                      handled it above), we're trying to expand into a
6070                      fixed-length argument list.  */
6071                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6072                     sorry ("cannot expand %<%E%> into a fixed-length "
6073                            "argument list", arg);
6074                   else
6075                     sorry ("cannot expand %<%T%> into a fixed-length "
6076                            "argument list", arg);
6077                 }
6078               return error_mark_node;
6079             }
6080         }
6081       else if (require_all_args)
6082         {
6083           /* There must be a default arg in this case.  */
6084           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6085                                      complain, in_decl);
6086           /* The position of the first default template argument,
6087              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6088              Record that.  */
6089           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6090             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6091         }
6092       else
6093         break;
6094
6095       if (arg == error_mark_node)
6096         {
6097           if (complain & tf_error)
6098             error ("template argument %d is invalid", arg_idx + 1);
6099         }
6100       else if (!arg)
6101         /* This only occurs if there was an error in the template
6102            parameter list itself (which we would already have
6103            reported) that we are trying to recover from, e.g., a class
6104            template with a parameter list such as
6105            template<typename..., typename>.  */
6106         return error_mark_node;
6107       else
6108         arg = convert_template_argument (TREE_VALUE (parm),
6109                                          arg, new_args, complain, 
6110                                          parm_idx, in_decl);
6111
6112       if (arg == error_mark_node)
6113         lost++;
6114       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6115     }
6116   cp_unevaluated_operand = saved_unevaluated_operand;
6117   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6118
6119   if (lost)
6120     return error_mark_node;
6121
6122 #ifdef ENABLE_CHECKING
6123   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6124     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6125                                          TREE_VEC_LENGTH (new_inner_args));
6126 #endif
6127
6128   return new_inner_args;
6129 }
6130
6131 /* Returns 1 if template args OT and NT are equivalent.  */
6132
6133 static int
6134 template_args_equal (tree ot, tree nt)
6135 {
6136   if (nt == ot)
6137     return 1;
6138
6139   if (TREE_CODE (nt) == TREE_VEC)
6140     /* For member templates */
6141     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6142   else if (PACK_EXPANSION_P (ot))
6143     return PACK_EXPANSION_P (nt) 
6144       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6145                               PACK_EXPANSION_PATTERN (nt));
6146   else if (ARGUMENT_PACK_P (ot))
6147     {
6148       int i, len;
6149       tree opack, npack;
6150
6151       if (!ARGUMENT_PACK_P (nt))
6152         return 0;
6153
6154       opack = ARGUMENT_PACK_ARGS (ot);
6155       npack = ARGUMENT_PACK_ARGS (nt);
6156       len = TREE_VEC_LENGTH (opack);
6157       if (TREE_VEC_LENGTH (npack) != len)
6158         return 0;
6159       for (i = 0; i < len; ++i)
6160         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6161                                   TREE_VEC_ELT (npack, i)))
6162           return 0;
6163       return 1;
6164     }
6165   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6166     {
6167       /* We get here probably because we are in the middle of substituting
6168          into the pattern of a pack expansion. In that case the
6169          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6170          interested in. So we want to use the initial pack argument for
6171          the comparison.  */
6172       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6173       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6174         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6175       return template_args_equal (ot, nt);
6176     }
6177   else if (TYPE_P (nt))
6178     return TYPE_P (ot) && same_type_p (ot, nt);
6179   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6180     return 0;
6181   else
6182     return cp_tree_equal (ot, nt);
6183 }
6184
6185 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6186    of template arguments.  Returns 0 otherwise.  */
6187
6188 int
6189 comp_template_args (tree oldargs, tree newargs)
6190 {
6191   int i;
6192
6193   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6194     return 0;
6195
6196   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6197     {
6198       tree nt = TREE_VEC_ELT (newargs, i);
6199       tree ot = TREE_VEC_ELT (oldargs, i);
6200
6201       if (! template_args_equal (ot, nt))
6202         return 0;
6203     }
6204   return 1;
6205 }
6206
6207 static void
6208 add_pending_template (tree d)
6209 {
6210   tree ti = (TYPE_P (d)
6211              ? CLASSTYPE_TEMPLATE_INFO (d)
6212              : DECL_TEMPLATE_INFO (d));
6213   struct pending_template *pt;
6214   int level;
6215
6216   if (TI_PENDING_TEMPLATE_FLAG (ti))
6217     return;
6218
6219   /* We are called both from instantiate_decl, where we've already had a
6220      tinst_level pushed, and instantiate_template, where we haven't.
6221      Compensate.  */
6222   level = !current_tinst_level || current_tinst_level->decl != d;
6223
6224   if (level)
6225     push_tinst_level (d);
6226
6227   pt = ggc_alloc_pending_template ();
6228   pt->next = NULL;
6229   pt->tinst = current_tinst_level;
6230   if (last_pending_template)
6231     last_pending_template->next = pt;
6232   else
6233     pending_templates = pt;
6234
6235   last_pending_template = pt;
6236
6237   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6238
6239   if (level)
6240     pop_tinst_level ();
6241 }
6242
6243
6244 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6245    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6246    documentation for TEMPLATE_ID_EXPR.  */
6247
6248 tree
6249 lookup_template_function (tree fns, tree arglist)
6250 {
6251   tree type;
6252
6253   if (fns == error_mark_node || arglist == error_mark_node)
6254     return error_mark_node;
6255
6256   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6257   gcc_assert (fns && (is_overloaded_fn (fns)
6258                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6259
6260   if (BASELINK_P (fns))
6261     {
6262       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6263                                          unknown_type_node,
6264                                          BASELINK_FUNCTIONS (fns),
6265                                          arglist);
6266       return fns;
6267     }
6268
6269   type = TREE_TYPE (fns);
6270   if (TREE_CODE (fns) == OVERLOAD || !type)
6271     type = unknown_type_node;
6272
6273   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6274 }
6275
6276 /* Within the scope of a template class S<T>, the name S gets bound
6277    (in build_self_reference) to a TYPE_DECL for the class, not a
6278    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6279    or one of its enclosing classes, and that type is a template,
6280    return the associated TEMPLATE_DECL.  Otherwise, the original
6281    DECL is returned.
6282
6283    Also handle the case when DECL is a TREE_LIST of ambiguous
6284    injected-class-names from different bases.  */
6285
6286 tree
6287 maybe_get_template_decl_from_type_decl (tree decl)
6288 {
6289   if (decl == NULL_TREE)
6290     return decl;
6291
6292   /* DR 176: A lookup that finds an injected-class-name (10.2
6293      [class.member.lookup]) can result in an ambiguity in certain cases
6294      (for example, if it is found in more than one base class). If all of
6295      the injected-class-names that are found refer to specializations of
6296      the same class template, and if the name is followed by a
6297      template-argument-list, the reference refers to the class template
6298      itself and not a specialization thereof, and is not ambiguous.  */
6299   if (TREE_CODE (decl) == TREE_LIST)
6300     {
6301       tree t, tmpl = NULL_TREE;
6302       for (t = decl; t; t = TREE_CHAIN (t))
6303         {
6304           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6305           if (!tmpl)
6306             tmpl = elt;
6307           else if (tmpl != elt)
6308             break;
6309         }
6310       if (tmpl && t == NULL_TREE)
6311         return tmpl;
6312       else
6313         return decl;
6314     }
6315
6316   return (decl != NULL_TREE
6317           && DECL_SELF_REFERENCE_P (decl)
6318           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6319     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6320 }
6321
6322 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6323    parameters, find the desired type.
6324
6325    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6326
6327    IN_DECL, if non-NULL, is the template declaration we are trying to
6328    instantiate.
6329
6330    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6331    the class we are looking up.
6332
6333    Issue error and warning messages under control of COMPLAIN.
6334
6335    If the template class is really a local class in a template
6336    function, then the FUNCTION_CONTEXT is the function in which it is
6337    being instantiated.
6338
6339    ??? Note that this function is currently called *twice* for each
6340    template-id: the first time from the parser, while creating the
6341    incomplete type (finish_template_type), and the second type during the
6342    real instantiation (instantiate_template_class). This is surely something
6343    that we want to avoid. It also causes some problems with argument
6344    coercion (see convert_nontype_argument for more information on this).  */
6345
6346 tree
6347 lookup_template_class (tree d1,
6348                        tree arglist,
6349                        tree in_decl,
6350                        tree context,
6351                        int entering_scope,
6352                        tsubst_flags_t complain)
6353 {
6354   tree templ = NULL_TREE, parmlist;
6355   tree t;
6356   spec_entry **slot;
6357   spec_entry *entry;
6358   spec_entry elt;
6359   hashval_t hash;
6360
6361   timevar_push (TV_NAME_LOOKUP);
6362
6363   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6364     {
6365       tree value = innermost_non_namespace_value (d1);
6366       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6367         templ = value;
6368       else
6369         {
6370           if (context)
6371             push_decl_namespace (context);
6372           templ = lookup_name (d1);
6373           templ = maybe_get_template_decl_from_type_decl (templ);
6374           if (context)
6375             pop_decl_namespace ();
6376         }
6377       if (templ)
6378         context = DECL_CONTEXT (templ);
6379     }
6380   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6381     {
6382       tree type = TREE_TYPE (d1);
6383
6384       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6385          an implicit typename for the second A.  Deal with it.  */
6386       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6387         type = TREE_TYPE (type);
6388
6389       if (CLASSTYPE_TEMPLATE_INFO (type))
6390         {
6391           templ = CLASSTYPE_TI_TEMPLATE (type);
6392           d1 = DECL_NAME (templ);
6393         }
6394     }
6395   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6396            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6397     {
6398       templ = TYPE_TI_TEMPLATE (d1);
6399       d1 = DECL_NAME (templ);
6400     }
6401   else if (TREE_CODE (d1) == TEMPLATE_DECL
6402            && DECL_TEMPLATE_RESULT (d1)
6403            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6404     {
6405       templ = d1;
6406       d1 = DECL_NAME (templ);
6407       context = DECL_CONTEXT (templ);
6408     }
6409
6410   /* Issue an error message if we didn't find a template.  */
6411   if (! templ)
6412     {
6413       if (complain & tf_error)
6414         error ("%qT is not a template", d1);
6415       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6416     }
6417
6418   if (TREE_CODE (templ) != TEMPLATE_DECL
6419          /* Make sure it's a user visible template, if it was named by
6420             the user.  */
6421       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6422           && !PRIMARY_TEMPLATE_P (templ)))
6423     {
6424       if (complain & tf_error)
6425         {
6426           error ("non-template type %qT used as a template", d1);
6427           if (in_decl)
6428             error ("for template declaration %q+D", in_decl);
6429         }
6430       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6431     }
6432
6433   complain &= ~tf_user;
6434
6435   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6436     {
6437       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6438          template arguments */
6439
6440       tree parm;
6441       tree arglist2;
6442       tree outer;
6443
6444       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6445
6446       /* Consider an example where a template template parameter declared as
6447
6448            template <class T, class U = std::allocator<T> > class TT
6449
6450          The template parameter level of T and U are one level larger than
6451          of TT.  To proper process the default argument of U, say when an
6452          instantiation `TT<int>' is seen, we need to build the full
6453          arguments containing {int} as the innermost level.  Outer levels,
6454          available when not appearing as default template argument, can be
6455          obtained from the arguments of the enclosing template.
6456
6457          Suppose that TT is later substituted with std::vector.  The above
6458          instantiation is `TT<int, std::allocator<T> >' with TT at
6459          level 1, and T at level 2, while the template arguments at level 1
6460          becomes {std::vector} and the inner level 2 is {int}.  */
6461
6462       outer = DECL_CONTEXT (templ);
6463       if (outer)
6464         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6465       else if (current_template_parms)
6466         /* This is an argument of the current template, so we haven't set
6467            DECL_CONTEXT yet.  */
6468         outer = current_template_args ();
6469
6470       if (outer)
6471         arglist = add_to_template_args (outer, arglist);
6472
6473       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6474                                         complain,
6475                                         /*require_all_args=*/true,
6476                                         /*use_default_args=*/true);
6477       if (arglist2 == error_mark_node
6478           || (!uses_template_parms (arglist2)
6479               && check_instantiated_args (templ, arglist2, complain)))
6480         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6481
6482       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6483       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6484     }
6485   else
6486     {
6487       tree template_type = TREE_TYPE (templ);
6488       tree gen_tmpl;
6489       tree type_decl;
6490       tree found = NULL_TREE;
6491       int arg_depth;
6492       int parm_depth;
6493       int is_dependent_type;
6494       int use_partial_inst_tmpl = false;
6495
6496       gen_tmpl = most_general_template (templ);
6497       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6498       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6499       arg_depth = TMPL_ARGS_DEPTH (arglist);
6500
6501       if (arg_depth == 1 && parm_depth > 1)
6502         {
6503           /* We've been given an incomplete set of template arguments.
6504              For example, given:
6505
6506                template <class T> struct S1 {
6507                  template <class U> struct S2 {};
6508                  template <class U> struct S2<U*> {};
6509                 };
6510
6511              we will be called with an ARGLIST of `U*', but the
6512              TEMPLATE will be `template <class T> template
6513              <class U> struct S1<T>::S2'.  We must fill in the missing
6514              arguments.  */
6515           arglist
6516             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6517                                            arglist);
6518           arg_depth = TMPL_ARGS_DEPTH (arglist);
6519         }
6520
6521       /* Now we should have enough arguments.  */
6522       gcc_assert (parm_depth == arg_depth);
6523
6524       /* From here on, we're only interested in the most general
6525          template.  */
6526
6527       /* Calculate the BOUND_ARGS.  These will be the args that are
6528          actually tsubst'd into the definition to create the
6529          instantiation.  */
6530       if (parm_depth > 1)
6531         {
6532           /* We have multiple levels of arguments to coerce, at once.  */
6533           int i;
6534           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6535
6536           tree bound_args = make_tree_vec (parm_depth);
6537
6538           for (i = saved_depth,
6539                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6540                i > 0 && t != NULL_TREE;
6541                --i, t = TREE_CHAIN (t))
6542             {
6543               tree a;
6544               if (i == saved_depth)
6545                 a = coerce_template_parms (TREE_VALUE (t),
6546                                            arglist, gen_tmpl,
6547                                            complain,
6548                                            /*require_all_args=*/true,
6549                                            /*use_default_args=*/true);
6550               else
6551                 /* Outer levels should have already been coerced.  */
6552                 a = TMPL_ARGS_LEVEL (arglist, i);
6553
6554               /* Don't process further if one of the levels fails.  */
6555               if (a == error_mark_node)
6556                 {
6557                   /* Restore the ARGLIST to its full size.  */
6558                   TREE_VEC_LENGTH (arglist) = saved_depth;
6559                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6560                 }
6561
6562               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6563
6564               /* We temporarily reduce the length of the ARGLIST so
6565                  that coerce_template_parms will see only the arguments
6566                  corresponding to the template parameters it is
6567                  examining.  */
6568               TREE_VEC_LENGTH (arglist)--;
6569             }
6570
6571           /* Restore the ARGLIST to its full size.  */
6572           TREE_VEC_LENGTH (arglist) = saved_depth;
6573
6574           arglist = bound_args;
6575         }
6576       else
6577         arglist
6578           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6579                                    INNERMOST_TEMPLATE_ARGS (arglist),
6580                                    gen_tmpl,
6581                                    complain,
6582                                    /*require_all_args=*/true,
6583                                    /*use_default_args=*/true);
6584
6585       if (arglist == error_mark_node)
6586         /* We were unable to bind the arguments.  */
6587         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6588
6589       /* In the scope of a template class, explicit references to the
6590          template class refer to the type of the template, not any
6591          instantiation of it.  For example, in:
6592
6593            template <class T> class C { void f(C<T>); }
6594
6595          the `C<T>' is just the same as `C'.  Outside of the
6596          class, however, such a reference is an instantiation.  */
6597       if ((entering_scope
6598            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6599            || currently_open_class (template_type))
6600           /* comp_template_args is expensive, check it last.  */
6601           && comp_template_args (TYPE_TI_ARGS (template_type),
6602                                  arglist))
6603         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6604
6605       /* If we already have this specialization, return it.  */
6606       elt.tmpl = gen_tmpl;
6607       elt.args = arglist;
6608       hash = hash_specialization (&elt);
6609       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6610                                                   &elt, hash);
6611
6612       if (entry)
6613         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6614
6615       is_dependent_type = uses_template_parms (arglist);
6616
6617       /* If the deduced arguments are invalid, then the binding
6618          failed.  */
6619       if (!is_dependent_type
6620           && check_instantiated_args (gen_tmpl,
6621                                       INNERMOST_TEMPLATE_ARGS (arglist),
6622                                       complain))
6623         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6624
6625       if (!is_dependent_type
6626           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6627           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6628           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6629         {
6630           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6631                                       DECL_NAME (gen_tmpl),
6632                                       /*tag_scope=*/ts_global);
6633           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6634         }
6635
6636       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6637                         complain, in_decl);
6638       if (!context)
6639         context = global_namespace;
6640
6641       /* Create the type.  */
6642       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6643         {
6644           if (!is_dependent_type)
6645             {
6646               set_current_access_from_decl (TYPE_NAME (template_type));
6647               t = start_enum (TYPE_IDENTIFIER (template_type),
6648                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6649                                       arglist, complain, in_decl),
6650                               SCOPED_ENUM_P (template_type));
6651             }
6652           else
6653             {
6654               /* We don't want to call start_enum for this type, since
6655                  the values for the enumeration constants may involve
6656                  template parameters.  And, no one should be interested
6657                  in the enumeration constants for such a type.  */
6658               t = cxx_make_type (ENUMERAL_TYPE);
6659               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6660             }
6661         }
6662       else
6663         {
6664           t = make_class_type (TREE_CODE (template_type));
6665           CLASSTYPE_DECLARED_CLASS (t)
6666             = CLASSTYPE_DECLARED_CLASS (template_type);
6667           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6668           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6669
6670           /* A local class.  Make sure the decl gets registered properly.  */
6671           if (context == current_function_decl)
6672             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6673
6674           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6675             /* This instantiation is another name for the primary
6676                template type. Set the TYPE_CANONICAL field
6677                appropriately. */
6678             TYPE_CANONICAL (t) = template_type;
6679           else if (any_template_arguments_need_structural_equality_p (arglist))
6680             /* Some of the template arguments require structural
6681                equality testing, so this template class requires
6682                structural equality testing. */
6683             SET_TYPE_STRUCTURAL_EQUALITY (t);
6684         }
6685
6686       /* If we called start_enum or pushtag above, this information
6687          will already be set up.  */
6688       if (!TYPE_NAME (t))
6689         {
6690           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6691
6692           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6693           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6694           DECL_SOURCE_LOCATION (type_decl)
6695             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6696         }
6697       else
6698         type_decl = TYPE_NAME (t);
6699
6700       TREE_PRIVATE (type_decl)
6701         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6702       TREE_PROTECTED (type_decl)
6703         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6704       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6705         {
6706           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6707           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6708         }
6709
6710       /* Let's consider the explicit specialization of a member
6711          of a class template specialization that is implicitely instantiated,
6712          e.g.:
6713              template<class T>
6714              struct S
6715              {
6716                template<class U> struct M {}; //#0
6717              };
6718
6719              template<>
6720              template<>
6721              struct S<int>::M<char> //#1
6722              {
6723                int i;
6724              };
6725         [temp.expl.spec]/4 says this is valid.
6726
6727         In this case, when we write:
6728         S<int>::M<char> m;
6729
6730         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
6731         the one of #0.
6732
6733         When we encounter #1, we want to store the partial instantiation
6734         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
6735
6736         For all cases other than this "explicit specialization of member of a
6737         class template", we just want to store the most general template into
6738         the CLASSTYPE_TI_TEMPLATE of M.
6739
6740         This case of "explicit specialization of member of a class template"
6741         only happens when:
6742         1/ the enclosing class is an instantiation of, and therefore not
6743         the same as, the context of the most general template, and
6744         2/ we aren't looking at the partial instantiation itself, i.e.
6745         the innermost arguments are not the same as the innermost parms of
6746         the most general template.
6747
6748         So it's only when 1/ and 2/ happens that we want to use the partial
6749         instantiation of the member template in lieu of its most general
6750         template.  */
6751
6752       if (PRIMARY_TEMPLATE_P (gen_tmpl)
6753           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
6754           /* the enclosing class must be an instantiation...  */
6755           && CLASS_TYPE_P (context)
6756           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
6757         {
6758           tree partial_inst_args;
6759           TREE_VEC_LENGTH (arglist)--;
6760           ++processing_template_decl;
6761           partial_inst_args =
6762             tsubst (INNERMOST_TEMPLATE_ARGS
6763                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
6764                     arglist, complain, NULL_TREE);
6765           --processing_template_decl;
6766           TREE_VEC_LENGTH (arglist)++;
6767           use_partial_inst_tmpl =
6768             /*...and we must not be looking at the partial instantiation
6769              itself. */
6770             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
6771                                  partial_inst_args);
6772         }
6773
6774       if (!use_partial_inst_tmpl)
6775         /* This case is easy; there are no member templates involved.  */
6776         found = gen_tmpl;
6777       else
6778         {
6779           /* This is a full instantiation of a member template.  Find
6780              the partial instantiation of which this is an instance.  */
6781
6782           /* Temporarily reduce by one the number of levels in the ARGLIST
6783              so as to avoid comparing the last set of arguments.  */
6784           TREE_VEC_LENGTH (arglist)--;
6785           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6786           TREE_VEC_LENGTH (arglist)++;
6787           found = CLASSTYPE_TI_TEMPLATE (found);
6788         }
6789
6790       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6791
6792       elt.spec = t;
6793       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6794                                                        &elt, hash, INSERT);
6795       *slot = ggc_alloc_spec_entry ();
6796       **slot = elt;
6797
6798       /* Note this use of the partial instantiation so we can check it
6799          later in maybe_process_partial_specialization.  */
6800       DECL_TEMPLATE_INSTANTIATIONS (templ)
6801         = tree_cons (arglist, t,
6802                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6803
6804       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
6805         /* Now that the type has been registered on the instantiations
6806            list, we set up the enumerators.  Because the enumeration
6807            constants may involve the enumeration type itself, we make
6808            sure to register the type first, and then create the
6809            constants.  That way, doing tsubst_expr for the enumeration
6810            constants won't result in recursive calls here; we'll find
6811            the instantiation and exit above.  */
6812         tsubst_enum (template_type, t, arglist);
6813
6814       if (is_dependent_type)
6815         /* If the type makes use of template parameters, the
6816            code that generates debugging information will crash.  */
6817         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6818
6819       /* Possibly limit visibility based on template args.  */
6820       TREE_PUBLIC (type_decl) = 1;
6821       determine_visibility (type_decl);
6822
6823       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6824     }
6825   timevar_pop (TV_NAME_LOOKUP);
6826 }
6827 \f
6828 struct pair_fn_data
6829 {
6830   tree_fn_t fn;
6831   void *data;
6832   /* True when we should also visit template parameters that occur in
6833      non-deduced contexts.  */
6834   bool include_nondeduced_p;
6835   struct pointer_set_t *visited;
6836 };
6837
6838 /* Called from for_each_template_parm via walk_tree.  */
6839
6840 static tree
6841 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6842 {
6843   tree t = *tp;
6844   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6845   tree_fn_t fn = pfd->fn;
6846   void *data = pfd->data;
6847
6848   if (TYPE_P (t)
6849       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6850       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6851                                  pfd->include_nondeduced_p))
6852     return error_mark_node;
6853
6854   switch (TREE_CODE (t))
6855     {
6856     case RECORD_TYPE:
6857       if (TYPE_PTRMEMFUNC_P (t))
6858         break;
6859       /* Fall through.  */
6860
6861     case UNION_TYPE:
6862     case ENUMERAL_TYPE:
6863       if (!TYPE_TEMPLATE_INFO (t))
6864         *walk_subtrees = 0;
6865       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6866                                        fn, data, pfd->visited, 
6867                                        pfd->include_nondeduced_p))
6868         return error_mark_node;
6869       break;
6870
6871     case INTEGER_TYPE:
6872       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6873                                   fn, data, pfd->visited, 
6874                                   pfd->include_nondeduced_p)
6875           || for_each_template_parm (TYPE_MAX_VALUE (t),
6876                                      fn, data, pfd->visited,
6877                                      pfd->include_nondeduced_p))
6878         return error_mark_node;
6879       break;
6880
6881     case METHOD_TYPE:
6882       /* Since we're not going to walk subtrees, we have to do this
6883          explicitly here.  */
6884       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6885                                   pfd->visited, pfd->include_nondeduced_p))
6886         return error_mark_node;
6887       /* Fall through.  */
6888
6889     case FUNCTION_TYPE:
6890       /* Check the return type.  */
6891       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6892                                   pfd->include_nondeduced_p))
6893         return error_mark_node;
6894
6895       /* Check the parameter types.  Since default arguments are not
6896          instantiated until they are needed, the TYPE_ARG_TYPES may
6897          contain expressions that involve template parameters.  But,
6898          no-one should be looking at them yet.  And, once they're
6899          instantiated, they don't contain template parameters, so
6900          there's no point in looking at them then, either.  */
6901       {
6902         tree parm;
6903
6904         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6905           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6906                                       pfd->visited, pfd->include_nondeduced_p))
6907             return error_mark_node;
6908
6909         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6910            want walk_tree walking into them itself.  */
6911         *walk_subtrees = 0;
6912       }
6913       break;
6914
6915     case TYPEOF_TYPE:
6916       if (pfd->include_nondeduced_p
6917           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6918                                      pfd->visited, 
6919                                      pfd->include_nondeduced_p))
6920         return error_mark_node;
6921       break;
6922
6923     case FUNCTION_DECL:
6924     case VAR_DECL:
6925       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6926           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6927                                      pfd->visited, pfd->include_nondeduced_p))
6928         return error_mark_node;
6929       /* Fall through.  */
6930
6931     case PARM_DECL:
6932     case CONST_DECL:
6933       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6934           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6935                                      pfd->visited, pfd->include_nondeduced_p))
6936         return error_mark_node;
6937       if (DECL_CONTEXT (t)
6938           && pfd->include_nondeduced_p
6939           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6940                                      pfd->visited, pfd->include_nondeduced_p))
6941         return error_mark_node;
6942       break;
6943
6944     case BOUND_TEMPLATE_TEMPLATE_PARM:
6945       /* Record template parameters such as `T' inside `TT<T>'.  */
6946       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6947                                   pfd->include_nondeduced_p))
6948         return error_mark_node;
6949       /* Fall through.  */
6950
6951     case TEMPLATE_TEMPLATE_PARM:
6952     case TEMPLATE_TYPE_PARM:
6953     case TEMPLATE_PARM_INDEX:
6954       if (fn && (*fn)(t, data))
6955         return error_mark_node;
6956       else if (!fn)
6957         return error_mark_node;
6958       break;
6959
6960     case TEMPLATE_DECL:
6961       /* A template template parameter is encountered.  */
6962       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6963           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6964                                      pfd->include_nondeduced_p))
6965         return error_mark_node;
6966
6967       /* Already substituted template template parameter */
6968       *walk_subtrees = 0;
6969       break;
6970
6971     case TYPENAME_TYPE:
6972       if (!fn
6973           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6974                                      data, pfd->visited, 
6975                                      pfd->include_nondeduced_p))
6976         return error_mark_node;
6977       break;
6978
6979     case CONSTRUCTOR:
6980       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6981           && pfd->include_nondeduced_p
6982           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6983                                      (TREE_TYPE (t)), fn, data,
6984                                      pfd->visited, pfd->include_nondeduced_p))
6985         return error_mark_node;
6986       break;
6987
6988     case INDIRECT_REF:
6989     case COMPONENT_REF:
6990       /* If there's no type, then this thing must be some expression
6991          involving template parameters.  */
6992       if (!fn && !TREE_TYPE (t))
6993         return error_mark_node;
6994       break;
6995
6996     case MODOP_EXPR:
6997     case CAST_EXPR:
6998     case REINTERPRET_CAST_EXPR:
6999     case CONST_CAST_EXPR:
7000     case STATIC_CAST_EXPR:
7001     case DYNAMIC_CAST_EXPR:
7002     case ARROW_EXPR:
7003     case DOTSTAR_EXPR:
7004     case TYPEID_EXPR:
7005     case PSEUDO_DTOR_EXPR:
7006       if (!fn)
7007         return error_mark_node;
7008       break;
7009
7010     default:
7011       break;
7012     }
7013
7014   /* We didn't find any template parameters we liked.  */
7015   return NULL_TREE;
7016 }
7017
7018 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7019    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7020    call FN with the parameter and the DATA.
7021    If FN returns nonzero, the iteration is terminated, and
7022    for_each_template_parm returns 1.  Otherwise, the iteration
7023    continues.  If FN never returns a nonzero value, the value
7024    returned by for_each_template_parm is 0.  If FN is NULL, it is
7025    considered to be the function which always returns 1.
7026
7027    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7028    parameters that occur in non-deduced contexts.  When false, only
7029    visits those template parameters that can be deduced.  */
7030
7031 static int
7032 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7033                         struct pointer_set_t *visited,
7034                         bool include_nondeduced_p)
7035 {
7036   struct pair_fn_data pfd;
7037   int result;
7038
7039   /* Set up.  */
7040   pfd.fn = fn;
7041   pfd.data = data;
7042   pfd.include_nondeduced_p = include_nondeduced_p;
7043
7044   /* Walk the tree.  (Conceptually, we would like to walk without
7045      duplicates, but for_each_template_parm_r recursively calls
7046      for_each_template_parm, so we would need to reorganize a fair
7047      bit to use walk_tree_without_duplicates, so we keep our own
7048      visited list.)  */
7049   if (visited)
7050     pfd.visited = visited;
7051   else
7052     pfd.visited = pointer_set_create ();
7053   result = cp_walk_tree (&t,
7054                          for_each_template_parm_r,
7055                          &pfd,
7056                          pfd.visited) != NULL_TREE;
7057
7058   /* Clean up.  */
7059   if (!visited)
7060     {
7061       pointer_set_destroy (pfd.visited);
7062       pfd.visited = 0;
7063     }
7064
7065   return result;
7066 }
7067
7068 /* Returns true if T depends on any template parameter.  */
7069
7070 int
7071 uses_template_parms (tree t)
7072 {
7073   bool dependent_p;
7074   int saved_processing_template_decl;
7075
7076   saved_processing_template_decl = processing_template_decl;
7077   if (!saved_processing_template_decl)
7078     processing_template_decl = 1;
7079   if (TYPE_P (t))
7080     dependent_p = dependent_type_p (t);
7081   else if (TREE_CODE (t) == TREE_VEC)
7082     dependent_p = any_dependent_template_arguments_p (t);
7083   else if (TREE_CODE (t) == TREE_LIST)
7084     dependent_p = (uses_template_parms (TREE_VALUE (t))
7085                    || uses_template_parms (TREE_CHAIN (t)));
7086   else if (TREE_CODE (t) == TYPE_DECL)
7087     dependent_p = dependent_type_p (TREE_TYPE (t));
7088   else if (DECL_P (t)
7089            || EXPR_P (t)
7090            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7091            || TREE_CODE (t) == OVERLOAD
7092            || TREE_CODE (t) == BASELINK
7093            || TREE_CODE (t) == IDENTIFIER_NODE
7094            || TREE_CODE (t) == TRAIT_EXPR
7095            || TREE_CODE (t) == CONSTRUCTOR
7096            || CONSTANT_CLASS_P (t))
7097     dependent_p = (type_dependent_expression_p (t)
7098                    || value_dependent_expression_p (t));
7099   else
7100     {
7101       gcc_assert (t == error_mark_node);
7102       dependent_p = false;
7103     }
7104
7105   processing_template_decl = saved_processing_template_decl;
7106
7107   return dependent_p;
7108 }
7109
7110 /* Returns true if T depends on any template parameter with level LEVEL.  */
7111
7112 int
7113 uses_template_parms_level (tree t, int level)
7114 {
7115   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7116                                  /*include_nondeduced_p=*/true);
7117 }
7118
7119 static int tinst_depth;
7120 extern int max_tinst_depth;
7121 #ifdef GATHER_STATISTICS
7122 int depth_reached;
7123 #endif
7124 static int tinst_level_tick;
7125 static int last_template_error_tick;
7126
7127 /* We're starting to instantiate D; record the template instantiation context
7128    for diagnostics and to restore it later.  */
7129
7130 int
7131 push_tinst_level (tree d)
7132 {
7133   struct tinst_level *new_level;
7134
7135   if (tinst_depth >= max_tinst_depth)
7136     {
7137       /* If the instantiation in question still has unbound template parms,
7138          we don't really care if we can't instantiate it, so just return.
7139          This happens with base instantiation for implicit `typename'.  */
7140       if (uses_template_parms (d))
7141         return 0;
7142
7143       last_template_error_tick = tinst_level_tick;
7144       error ("template instantiation depth exceeds maximum of %d (use "
7145              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7146              max_tinst_depth, d);
7147
7148       print_instantiation_context ();
7149
7150       return 0;
7151     }
7152
7153   new_level = ggc_alloc_tinst_level ();
7154   new_level->decl = d;
7155   new_level->locus = input_location;
7156   new_level->in_system_header_p = in_system_header;
7157   new_level->next = current_tinst_level;
7158   current_tinst_level = new_level;
7159
7160   ++tinst_depth;
7161 #ifdef GATHER_STATISTICS
7162   if (tinst_depth > depth_reached)
7163     depth_reached = tinst_depth;
7164 #endif
7165
7166   ++tinst_level_tick;
7167   return 1;
7168 }
7169
7170 /* We're done instantiating this template; return to the instantiation
7171    context.  */
7172
7173 void
7174 pop_tinst_level (void)
7175 {
7176   /* Restore the filename and line number stashed away when we started
7177      this instantiation.  */
7178   input_location = current_tinst_level->locus;
7179   current_tinst_level = current_tinst_level->next;
7180   --tinst_depth;
7181   ++tinst_level_tick;
7182 }
7183
7184 /* We're instantiating a deferred template; restore the template
7185    instantiation context in which the instantiation was requested, which
7186    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7187
7188 static tree
7189 reopen_tinst_level (struct tinst_level *level)
7190 {
7191   struct tinst_level *t;
7192
7193   tinst_depth = 0;
7194   for (t = level; t; t = t->next)
7195     ++tinst_depth;
7196
7197   current_tinst_level = level;
7198   pop_tinst_level ();
7199   return level->decl;
7200 }
7201
7202 /* Returns the TINST_LEVEL which gives the original instantiation
7203    context.  */
7204
7205 struct tinst_level *
7206 outermost_tinst_level (void)
7207 {
7208   struct tinst_level *level = current_tinst_level;
7209   if (level)
7210     while (level->next)
7211       level = level->next;
7212   return level;
7213 }
7214
7215 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7216
7217 bool
7218 parameter_of_template_p (tree parm, tree templ)
7219 {
7220   tree parms;
7221   int i;
7222
7223   if (!parm || !templ)
7224     return false;
7225
7226   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7227   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7228
7229   parms = DECL_TEMPLATE_PARMS (templ);
7230   parms = INNERMOST_TEMPLATE_PARMS (parms);
7231
7232   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7233     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7234       return true;
7235
7236   return false;
7237 }
7238
7239 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7240    vector of template arguments, as for tsubst.
7241
7242    Returns an appropriate tsubst'd friend declaration.  */
7243
7244 static tree
7245 tsubst_friend_function (tree decl, tree args)
7246 {
7247   tree new_friend;
7248
7249   if (TREE_CODE (decl) == FUNCTION_DECL
7250       && DECL_TEMPLATE_INSTANTIATION (decl)
7251       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7252     /* This was a friend declared with an explicit template
7253        argument list, e.g.:
7254
7255        friend void f<>(T);
7256
7257        to indicate that f was a template instantiation, not a new
7258        function declaration.  Now, we have to figure out what
7259        instantiation of what template.  */
7260     {
7261       tree template_id, arglist, fns;
7262       tree new_args;
7263       tree tmpl;
7264       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7265
7266       /* Friend functions are looked up in the containing namespace scope.
7267          We must enter that scope, to avoid finding member functions of the
7268          current class with same name.  */
7269       push_nested_namespace (ns);
7270       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7271                          tf_warning_or_error, NULL_TREE,
7272                          /*integral_constant_expression_p=*/false);
7273       pop_nested_namespace (ns);
7274       arglist = tsubst (DECL_TI_ARGS (decl), args,
7275                         tf_warning_or_error, NULL_TREE);
7276       template_id = lookup_template_function (fns, arglist);
7277
7278       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7279       tmpl = determine_specialization (template_id, new_friend,
7280                                        &new_args,
7281                                        /*need_member_template=*/0,
7282                                        TREE_VEC_LENGTH (args),
7283                                        tsk_none);
7284       return instantiate_template (tmpl, new_args, tf_error);
7285     }
7286
7287   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7288
7289   /* The NEW_FRIEND will look like an instantiation, to the
7290      compiler, but is not an instantiation from the point of view of
7291      the language.  For example, we might have had:
7292
7293      template <class T> struct S {
7294        template <class U> friend void f(T, U);
7295      };
7296
7297      Then, in S<int>, template <class U> void f(int, U) is not an
7298      instantiation of anything.  */
7299   if (new_friend == error_mark_node)
7300     return error_mark_node;
7301
7302   DECL_USE_TEMPLATE (new_friend) = 0;
7303   if (TREE_CODE (decl) == TEMPLATE_DECL)
7304     {
7305       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7306       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7307         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7308     }
7309
7310   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7311      is not a template instantiation and should not be mangled like
7312      one.  Therefore, we forget the mangling here; we'll recompute it
7313      later if we need it.  */
7314   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7315     {
7316       SET_DECL_RTL (new_friend, NULL);
7317       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7318     }
7319
7320   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7321     {
7322       tree old_decl;
7323       tree new_friend_template_info;
7324       tree new_friend_result_template_info;
7325       tree ns;
7326       int  new_friend_is_defn;
7327
7328       /* We must save some information from NEW_FRIEND before calling
7329          duplicate decls since that function will free NEW_FRIEND if
7330          possible.  */
7331       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7332       new_friend_is_defn =
7333             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7334                            (template_for_substitution (new_friend)))
7335              != NULL_TREE);
7336       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7337         {
7338           /* This declaration is a `primary' template.  */
7339           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7340
7341           new_friend_result_template_info
7342             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7343         }
7344       else
7345         new_friend_result_template_info = NULL_TREE;
7346
7347       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7348       if (new_friend_is_defn)
7349         DECL_INITIAL (new_friend) = error_mark_node;
7350
7351       /* Inside pushdecl_namespace_level, we will push into the
7352          current namespace. However, the friend function should go
7353          into the namespace of the template.  */
7354       ns = decl_namespace_context (new_friend);
7355       push_nested_namespace (ns);
7356       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7357       pop_nested_namespace (ns);
7358
7359       if (old_decl == error_mark_node)
7360         return error_mark_node;
7361
7362       if (old_decl != new_friend)
7363         {
7364           /* This new friend declaration matched an existing
7365              declaration.  For example, given:
7366
7367                template <class T> void f(T);
7368                template <class U> class C {
7369                  template <class T> friend void f(T) {}
7370                };
7371
7372              the friend declaration actually provides the definition
7373              of `f', once C has been instantiated for some type.  So,
7374              old_decl will be the out-of-class template declaration,
7375              while new_friend is the in-class definition.
7376
7377              But, if `f' was called before this point, the
7378              instantiation of `f' will have DECL_TI_ARGS corresponding
7379              to `T' but not to `U', references to which might appear
7380              in the definition of `f'.  Previously, the most general
7381              template for an instantiation of `f' was the out-of-class
7382              version; now it is the in-class version.  Therefore, we
7383              run through all specialization of `f', adding to their
7384              DECL_TI_ARGS appropriately.  In particular, they need a
7385              new set of outer arguments, corresponding to the
7386              arguments for this class instantiation.
7387
7388              The same situation can arise with something like this:
7389
7390                friend void f(int);
7391                template <class T> class C {
7392                  friend void f(T) {}
7393                };
7394
7395              when `C<int>' is instantiated.  Now, `f(int)' is defined
7396              in the class.  */
7397
7398           if (!new_friend_is_defn)
7399             /* On the other hand, if the in-class declaration does
7400                *not* provide a definition, then we don't want to alter
7401                existing definitions.  We can just leave everything
7402                alone.  */
7403             ;
7404           else
7405             {
7406               tree new_template = TI_TEMPLATE (new_friend_template_info);
7407               tree new_args = TI_ARGS (new_friend_template_info);
7408
7409               /* Overwrite whatever template info was there before, if
7410                  any, with the new template information pertaining to
7411                  the declaration.  */
7412               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7413
7414               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7415                 {
7416                   /* We should have called reregister_specialization in
7417                      duplicate_decls.  */
7418                   gcc_assert (retrieve_specialization (new_template,
7419                                                        new_args, 0)
7420                               == old_decl);
7421
7422                   /* Instantiate it if the global has already been used.  */
7423                   if (DECL_ODR_USED (old_decl))
7424                     instantiate_decl (old_decl, /*defer_ok=*/true,
7425                                       /*expl_inst_class_mem_p=*/false);
7426                 }
7427               else
7428                 {
7429                   tree t;
7430
7431                   /* Indicate that the old function template is a partial
7432                      instantiation.  */
7433                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7434                     = new_friend_result_template_info;
7435
7436                   gcc_assert (new_template
7437                               == most_general_template (new_template));
7438                   gcc_assert (new_template != old_decl);
7439
7440                   /* Reassign any specializations already in the hash table
7441                      to the new more general template, and add the
7442                      additional template args.  */
7443                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7444                        t != NULL_TREE;
7445                        t = TREE_CHAIN (t))
7446                     {
7447                       tree spec = TREE_VALUE (t);
7448                       spec_entry elt;
7449
7450                       elt.tmpl = old_decl;
7451                       elt.args = DECL_TI_ARGS (spec);
7452                       elt.spec = NULL_TREE;
7453
7454                       htab_remove_elt (decl_specializations, &elt);
7455
7456                       DECL_TI_ARGS (spec)
7457                         = add_outermost_template_args (new_args,
7458                                                        DECL_TI_ARGS (spec));
7459
7460                       register_specialization
7461                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7462
7463                     }
7464                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7465                 }
7466             }
7467
7468           /* The information from NEW_FRIEND has been merged into OLD_DECL
7469              by duplicate_decls.  */
7470           new_friend = old_decl;
7471         }
7472     }
7473   else
7474     {
7475       tree context = DECL_CONTEXT (new_friend);
7476       bool dependent_p;
7477
7478       /* In the code
7479            template <class T> class C {
7480              template <class U> friend void C1<U>::f (); // case 1
7481              friend void C2<T>::f ();                    // case 2
7482            };
7483          we only need to make sure CONTEXT is a complete type for
7484          case 2.  To distinguish between the two cases, we note that
7485          CONTEXT of case 1 remains dependent type after tsubst while
7486          this isn't true for case 2.  */
7487       ++processing_template_decl;
7488       dependent_p = dependent_type_p (context);
7489       --processing_template_decl;
7490
7491       if (!dependent_p
7492           && !complete_type_or_else (context, NULL_TREE))
7493         return error_mark_node;
7494
7495       if (COMPLETE_TYPE_P (context))
7496         {
7497           /* Check to see that the declaration is really present, and,
7498              possibly obtain an improved declaration.  */
7499           tree fn = check_classfn (context,
7500                                    new_friend, NULL_TREE);
7501
7502           if (fn)
7503             new_friend = fn;
7504         }
7505     }
7506
7507   return new_friend;
7508 }
7509
7510 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7511    template arguments, as for tsubst.
7512
7513    Returns an appropriate tsubst'd friend type or error_mark_node on
7514    failure.  */
7515
7516 static tree
7517 tsubst_friend_class (tree friend_tmpl, tree args)
7518 {
7519   tree friend_type;
7520   tree tmpl;
7521   tree context;
7522
7523   context = DECL_CONTEXT (friend_tmpl);
7524
7525   if (context)
7526     {
7527       if (TREE_CODE (context) == NAMESPACE_DECL)
7528         push_nested_namespace (context);
7529       else
7530         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7531     }
7532
7533   /* Look for a class template declaration.  We look for hidden names
7534      because two friend declarations of the same template are the
7535      same.  For example, in:
7536
7537        struct A { 
7538          template <typename> friend class F;
7539        };
7540        template <typename> struct B { 
7541          template <typename> friend class F;
7542        };
7543
7544      both F templates are the same.  */
7545   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7546                            /*block_p=*/true, 0, 
7547                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7548
7549   /* But, if we don't find one, it might be because we're in a
7550      situation like this:
7551
7552        template <class T>
7553        struct S {
7554          template <class U>
7555          friend struct S;
7556        };
7557
7558      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7559      for `S<int>', not the TEMPLATE_DECL.  */
7560   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7561     {
7562       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7563       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7564     }
7565
7566   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7567     {
7568       /* The friend template has already been declared.  Just
7569          check to see that the declarations match, and install any new
7570          default parameters.  We must tsubst the default parameters,
7571          of course.  We only need the innermost template parameters
7572          because that is all that redeclare_class_template will look
7573          at.  */
7574       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7575           > TMPL_ARGS_DEPTH (args))
7576         {
7577           tree parms;
7578           location_t saved_input_location;
7579           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7580                                          args, tf_warning_or_error);
7581
7582           saved_input_location = input_location;
7583           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7584           redeclare_class_template (TREE_TYPE (tmpl), parms);
7585           input_location = saved_input_location;
7586           
7587         }
7588
7589       friend_type = TREE_TYPE (tmpl);
7590     }
7591   else
7592     {
7593       /* The friend template has not already been declared.  In this
7594          case, the instantiation of the template class will cause the
7595          injection of this template into the global scope.  */
7596       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7597       if (tmpl == error_mark_node)
7598         return error_mark_node;
7599
7600       /* The new TMPL is not an instantiation of anything, so we
7601          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7602          the new type because that is supposed to be the corresponding
7603          template decl, i.e., TMPL.  */
7604       DECL_USE_TEMPLATE (tmpl) = 0;
7605       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7606       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7607       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7608         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7609
7610       /* Inject this template into the global scope.  */
7611       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7612     }
7613
7614   if (context)
7615     {
7616       if (TREE_CODE (context) == NAMESPACE_DECL)
7617         pop_nested_namespace (context);
7618       else
7619         pop_nested_class ();
7620     }
7621
7622   return friend_type;
7623 }
7624
7625 /* Returns zero if TYPE cannot be completed later due to circularity.
7626    Otherwise returns one.  */
7627
7628 static int
7629 can_complete_type_without_circularity (tree type)
7630 {
7631   if (type == NULL_TREE || type == error_mark_node)
7632     return 0;
7633   else if (COMPLETE_TYPE_P (type))
7634     return 1;
7635   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7636     return can_complete_type_without_circularity (TREE_TYPE (type));
7637   else if (CLASS_TYPE_P (type)
7638            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7639     return 0;
7640   else
7641     return 1;
7642 }
7643
7644 /* Apply any attributes which had to be deferred until instantiation
7645    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7646    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7647
7648 static void
7649 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7650                                 tree args, tsubst_flags_t complain, tree in_decl)
7651 {
7652   tree last_dep = NULL_TREE;
7653   tree t;
7654   tree *p;
7655
7656   for (t = attributes; t; t = TREE_CHAIN (t))
7657     if (ATTR_IS_DEPENDENT (t))
7658       {
7659         last_dep = t;
7660         attributes = copy_list (attributes);
7661         break;
7662       }
7663
7664   if (DECL_P (*decl_p))
7665     {
7666       if (TREE_TYPE (*decl_p) == error_mark_node)
7667         return;
7668       p = &DECL_ATTRIBUTES (*decl_p);
7669     }
7670   else
7671     p = &TYPE_ATTRIBUTES (*decl_p);
7672
7673   if (last_dep)
7674     {
7675       tree late_attrs = NULL_TREE;
7676       tree *q = &late_attrs;
7677
7678       for (*p = attributes; *p; )
7679         {
7680           t = *p;
7681           if (ATTR_IS_DEPENDENT (t))
7682             {
7683               *p = TREE_CHAIN (t);
7684               TREE_CHAIN (t) = NULL_TREE;
7685               /* If the first attribute argument is an identifier, don't
7686                  pass it through tsubst.  Attributes like mode, format,
7687                  cleanup and several target specific attributes expect it
7688                  unmodified.  */
7689               if (TREE_VALUE (t)
7690                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7691                   && TREE_VALUE (TREE_VALUE (t))
7692                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7693                       == IDENTIFIER_NODE))
7694                 {
7695                   tree chain
7696                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7697                                    in_decl,
7698                                    /*integral_constant_expression_p=*/false);
7699                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7700                     TREE_VALUE (t)
7701                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7702                                    chain);
7703                 }
7704               else
7705                 TREE_VALUE (t)
7706                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7707                                  /*integral_constant_expression_p=*/false);
7708               *q = t;
7709               q = &TREE_CHAIN (t);
7710             }
7711           else
7712             p = &TREE_CHAIN (t);
7713         }
7714
7715       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7716     }
7717 }
7718
7719 /* Perform (or defer) access check for typedefs that were referenced
7720    from within the template TMPL code.
7721    This is a subroutine of instantiate_template and instantiate_class_template.
7722    TMPL is the template to consider and TARGS is the list of arguments of
7723    that template.  */
7724
7725 static void
7726 perform_typedefs_access_check (tree tmpl, tree targs)
7727 {
7728   location_t saved_location;
7729   int i;
7730   qualified_typedef_usage_t *iter;
7731
7732   if (!tmpl
7733       || (!CLASS_TYPE_P (tmpl)
7734           && TREE_CODE (tmpl) != FUNCTION_DECL))
7735     return;
7736
7737   saved_location = input_location;
7738   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
7739                     get_types_needing_access_check (tmpl),
7740                     i, iter)
7741     {
7742       tree type_decl = iter->typedef_decl;
7743       tree type_scope = iter->context;
7744
7745       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7746         continue;
7747
7748       if (uses_template_parms (type_decl))
7749         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7750       if (uses_template_parms (type_scope))
7751         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7752
7753       /* Make access check error messages point to the location
7754          of the use of the typedef.  */
7755       input_location = iter->locus;
7756       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7757                                      type_decl, type_decl);
7758     }
7759     input_location = saved_location;
7760 }
7761
7762 tree
7763 instantiate_class_template (tree type)
7764 {
7765   tree templ, args, pattern, t, member;
7766   tree typedecl;
7767   tree pbinfo;
7768   tree base_list;
7769   unsigned int saved_maximum_field_alignment;
7770
7771   if (type == error_mark_node)
7772     return error_mark_node;
7773
7774   if (COMPLETE_OR_OPEN_TYPE_P (type)
7775       || uses_template_parms (type))
7776     return type;
7777
7778   /* Figure out which template is being instantiated.  */
7779   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7780   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7781
7782   /* Determine what specialization of the original template to
7783      instantiate.  */
7784   t = most_specialized_class (type, templ, tf_warning_or_error);
7785   if (t == error_mark_node)
7786     {
7787       TYPE_BEING_DEFINED (type) = 1;
7788       return error_mark_node;
7789     }
7790   else if (t)
7791     {
7792       /* This TYPE is actually an instantiation of a partial
7793          specialization.  We replace the innermost set of ARGS with
7794          the arguments appropriate for substitution.  For example,
7795          given:
7796
7797            template <class T> struct S {};
7798            template <class T> struct S<T*> {};
7799
7800          and supposing that we are instantiating S<int*>, ARGS will
7801          presently be {int*} -- but we need {int}.  */
7802       pattern = TREE_TYPE (t);
7803       args = TREE_PURPOSE (t);
7804     }
7805   else
7806     {
7807       pattern = TREE_TYPE (templ);
7808       args = CLASSTYPE_TI_ARGS (type);
7809     }
7810
7811   /* If the template we're instantiating is incomplete, then clearly
7812      there's nothing we can do.  */
7813   if (!COMPLETE_TYPE_P (pattern))
7814     return type;
7815
7816   /* If we've recursively instantiated too many templates, stop.  */
7817   if (! push_tinst_level (type))
7818     return type;
7819
7820   /* Now we're really doing the instantiation.  Mark the type as in
7821      the process of being defined.  */
7822   TYPE_BEING_DEFINED (type) = 1;
7823
7824   /* We may be in the middle of deferred access check.  Disable
7825      it now.  */
7826   push_deferring_access_checks (dk_no_deferred);
7827
7828   push_to_top_level ();
7829   /* Use #pragma pack from the template context.  */
7830   saved_maximum_field_alignment = maximum_field_alignment;
7831   maximum_field_alignment = TYPE_PRECISION (pattern);
7832
7833   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7834
7835   /* Set the input location to the most specialized template definition.
7836      This is needed if tsubsting causes an error.  */
7837   typedecl = TYPE_MAIN_DECL (pattern);
7838   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
7839     DECL_SOURCE_LOCATION (typedecl);
7840
7841   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7842   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7843   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7844   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7845   TYPE_HAS_COPY_ASSIGN (type) = TYPE_HAS_COPY_ASSIGN (pattern);
7846   TYPE_HAS_CONST_COPY_ASSIGN (type) = TYPE_HAS_CONST_COPY_ASSIGN (pattern);
7847   TYPE_HAS_COPY_CTOR (type) = TYPE_HAS_COPY_CTOR (pattern);
7848   TYPE_HAS_CONST_COPY_CTOR (type) = TYPE_HAS_CONST_COPY_CTOR (pattern);
7849   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7850   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7851   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7852   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7853   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7854   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7855   if (ANON_AGGR_TYPE_P (pattern))
7856     SET_ANON_AGGR_TYPE_P (type);
7857   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7858     {
7859       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7860       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7861     }
7862
7863   pbinfo = TYPE_BINFO (pattern);
7864
7865   /* We should never instantiate a nested class before its enclosing
7866      class; we need to look up the nested class by name before we can
7867      instantiate it, and that lookup should instantiate the enclosing
7868      class.  */
7869   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7870               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
7871
7872   base_list = NULL_TREE;
7873   if (BINFO_N_BASE_BINFOS (pbinfo))
7874     {
7875       tree pbase_binfo;
7876       tree context = TYPE_CONTEXT (type);
7877       tree pushed_scope;
7878       int i;
7879
7880       /* We must enter the scope containing the type, as that is where
7881          the accessibility of types named in dependent bases are
7882          looked up from.  */
7883       pushed_scope = push_scope (context ? context : global_namespace);
7884
7885       /* Substitute into each of the bases to determine the actual
7886          basetypes.  */
7887       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7888         {
7889           tree base;
7890           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7891           tree expanded_bases = NULL_TREE;
7892           int idx, len = 1;
7893
7894           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7895             {
7896               expanded_bases = 
7897                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7898                                        args, tf_error, NULL_TREE);
7899               if (expanded_bases == error_mark_node)
7900                 continue;
7901
7902               len = TREE_VEC_LENGTH (expanded_bases);
7903             }
7904
7905           for (idx = 0; idx < len; idx++)
7906             {
7907               if (expanded_bases)
7908                 /* Extract the already-expanded base class.  */
7909                 base = TREE_VEC_ELT (expanded_bases, idx);
7910               else
7911                 /* Substitute to figure out the base class.  */
7912                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7913                                NULL_TREE);
7914
7915               if (base == error_mark_node)
7916                 continue;
7917
7918               base_list = tree_cons (access, base, base_list);
7919               if (BINFO_VIRTUAL_P (pbase_binfo))
7920                 TREE_TYPE (base_list) = integer_type_node;
7921             }
7922         }
7923
7924       /* The list is now in reverse order; correct that.  */
7925       base_list = nreverse (base_list);
7926
7927       if (pushed_scope)
7928         pop_scope (pushed_scope);
7929     }
7930   /* Now call xref_basetypes to set up all the base-class
7931      information.  */
7932   xref_basetypes (type, base_list);
7933
7934   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7935                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7936                                   args, tf_error, NULL_TREE);
7937
7938   /* Now that our base classes are set up, enter the scope of the
7939      class, so that name lookups into base classes, etc. will work
7940      correctly.  This is precisely analogous to what we do in
7941      begin_class_definition when defining an ordinary non-template
7942      class, except we also need to push the enclosing classes.  */
7943   push_nested_class (type);
7944
7945   /* Now members are processed in the order of declaration.  */
7946   for (member = CLASSTYPE_DECL_LIST (pattern);
7947        member; member = TREE_CHAIN (member))
7948     {
7949       tree t = TREE_VALUE (member);
7950
7951       if (TREE_PURPOSE (member))
7952         {
7953           if (TYPE_P (t))
7954             {
7955               /* Build new CLASSTYPE_NESTED_UTDS.  */
7956
7957               tree newtag;
7958               bool class_template_p;
7959
7960               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7961                                   && TYPE_LANG_SPECIFIC (t)
7962                                   && CLASSTYPE_IS_TEMPLATE (t));
7963               /* If the member is a class template, then -- even after
7964                  substitution -- there may be dependent types in the
7965                  template argument list for the class.  We increment
7966                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7967                  that function will assume that no types are dependent
7968                  when outside of a template.  */
7969               if (class_template_p)
7970                 ++processing_template_decl;
7971               newtag = tsubst (t, args, tf_error, NULL_TREE);
7972               if (class_template_p)
7973                 --processing_template_decl;
7974               if (newtag == error_mark_node)
7975                 continue;
7976
7977               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7978                 {
7979                   tree name = TYPE_IDENTIFIER (t);
7980
7981                   if (class_template_p)
7982                     /* Unfortunately, lookup_template_class sets
7983                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7984                        instantiation (i.e., for the type of a member
7985                        template class nested within a template class.)
7986                        This behavior is required for
7987                        maybe_process_partial_specialization to work
7988                        correctly, but is not accurate in this case;
7989                        the TAG is not an instantiation of anything.
7990                        (The corresponding TEMPLATE_DECL is an
7991                        instantiation, but the TYPE is not.) */
7992                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7993
7994                   /* Now, we call pushtag to put this NEWTAG into the scope of
7995                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7996                      pushtag calling push_template_decl.  We don't have to do
7997                      this for enums because it will already have been done in
7998                      tsubst_enum.  */
7999                   if (name)
8000                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8001                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8002                 }
8003             }
8004           else if (TREE_CODE (t) == FUNCTION_DECL
8005                    || DECL_FUNCTION_TEMPLATE_P (t))
8006             {
8007               /* Build new TYPE_METHODS.  */
8008               tree r;
8009
8010               if (TREE_CODE (t) == TEMPLATE_DECL)
8011                 ++processing_template_decl;
8012               r = tsubst (t, args, tf_error, NULL_TREE);
8013               if (TREE_CODE (t) == TEMPLATE_DECL)
8014                 --processing_template_decl;
8015               set_current_access_from_decl (r);
8016               finish_member_declaration (r);
8017             }
8018           else
8019             {
8020               /* Build new TYPE_FIELDS.  */
8021               if (TREE_CODE (t) == STATIC_ASSERT)
8022                 {
8023                   tree condition = 
8024                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8025                                  tf_warning_or_error, NULL_TREE,
8026                                  /*integral_constant_expression_p=*/true);
8027                   finish_static_assert (condition,
8028                                         STATIC_ASSERT_MESSAGE (t), 
8029                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8030                                         /*member_p=*/true);
8031                 }
8032               else if (TREE_CODE (t) != CONST_DECL)
8033                 {
8034                   tree r;
8035
8036                   /* The file and line for this declaration, to
8037                      assist in error message reporting.  Since we
8038                      called push_tinst_level above, we don't need to
8039                      restore these.  */
8040                   input_location = DECL_SOURCE_LOCATION (t);
8041
8042                   if (TREE_CODE (t) == TEMPLATE_DECL)
8043                     ++processing_template_decl;
8044                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8045                   if (TREE_CODE (t) == TEMPLATE_DECL)
8046                     --processing_template_decl;
8047                   if (TREE_CODE (r) == VAR_DECL)
8048                     {
8049                       /* In [temp.inst]:
8050
8051                            [t]he initialization (and any associated
8052                            side-effects) of a static data member does
8053                            not occur unless the static data member is
8054                            itself used in a way that requires the
8055                            definition of the static data member to
8056                            exist.
8057
8058                          Therefore, we do not substitute into the
8059                          initialized for the static data member here.  */
8060                       finish_static_data_member_decl
8061                         (r,
8062                          /*init=*/NULL_TREE,
8063                          /*init_const_expr_p=*/false,
8064                          /*asmspec_tree=*/NULL_TREE,
8065                          /*flags=*/0);
8066                       if (DECL_INITIALIZED_IN_CLASS_P (r))
8067                         check_static_variable_definition (r, TREE_TYPE (r));
8068                     }
8069                   else if (TREE_CODE (r) == FIELD_DECL)
8070                     {
8071                       /* Determine whether R has a valid type and can be
8072                          completed later.  If R is invalid, then it is
8073                          replaced by error_mark_node so that it will not be
8074                          added to TYPE_FIELDS.  */
8075                       tree rtype = TREE_TYPE (r);
8076                       if (can_complete_type_without_circularity (rtype))
8077                         complete_type (rtype);
8078
8079                       if (!COMPLETE_TYPE_P (rtype))
8080                         {
8081                           cxx_incomplete_type_error (r, rtype);
8082                           r = error_mark_node;
8083                         }
8084                     }
8085
8086                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8087                      such a thing will already have been added to the field
8088                      list by tsubst_enum in finish_member_declaration in the
8089                      CLASSTYPE_NESTED_UTDS case above.  */
8090                   if (!(TREE_CODE (r) == TYPE_DECL
8091                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8092                         && DECL_ARTIFICIAL (r)))
8093                     {
8094                       set_current_access_from_decl (r);
8095                       finish_member_declaration (r);
8096                     }
8097                 }
8098             }
8099         }
8100       else
8101         {
8102           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8103             {
8104               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8105
8106               tree friend_type = t;
8107               bool adjust_processing_template_decl = false;
8108
8109               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8110                 {
8111                   /* template <class T> friend class C;  */
8112                   friend_type = tsubst_friend_class (friend_type, args);
8113                   adjust_processing_template_decl = true;
8114                 }
8115               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8116                 {
8117                   /* template <class T> friend class C::D;  */
8118                   friend_type = tsubst (friend_type, args,
8119                                         tf_warning_or_error, NULL_TREE);
8120                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8121                     friend_type = TREE_TYPE (friend_type);
8122                   adjust_processing_template_decl = true;
8123                 }
8124               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8125                 {
8126                   /* This could be either
8127
8128                        friend class T::C;
8129
8130                      when dependent_type_p is false or
8131
8132                        template <class U> friend class T::C;
8133
8134                      otherwise.  */
8135                   friend_type = tsubst (friend_type, args,
8136                                         tf_warning_or_error, NULL_TREE);
8137                   /* Bump processing_template_decl for correct
8138                      dependent_type_p calculation.  */
8139                   ++processing_template_decl;
8140                   if (dependent_type_p (friend_type))
8141                     adjust_processing_template_decl = true;
8142                   --processing_template_decl;
8143                 }
8144               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8145                        && hidden_name_p (TYPE_NAME (friend_type)))
8146                 {
8147                   /* friend class C;
8148
8149                      where C hasn't been declared yet.  Let's lookup name
8150                      from namespace scope directly, bypassing any name that
8151                      come from dependent base class.  */
8152                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8153
8154                   /* The call to xref_tag_from_type does injection for friend
8155                      classes.  */
8156                   push_nested_namespace (ns);
8157                   friend_type =
8158                     xref_tag_from_type (friend_type, NULL_TREE,
8159                                         /*tag_scope=*/ts_current);
8160                   pop_nested_namespace (ns);
8161                 }
8162               else if (uses_template_parms (friend_type))
8163                 /* friend class C<T>;  */
8164                 friend_type = tsubst (friend_type, args,
8165                                       tf_warning_or_error, NULL_TREE);
8166               /* Otherwise it's
8167
8168                    friend class C;
8169
8170                  where C is already declared or
8171
8172                    friend class C<int>;
8173
8174                  We don't have to do anything in these cases.  */
8175
8176               if (adjust_processing_template_decl)
8177                 /* Trick make_friend_class into realizing that the friend
8178                    we're adding is a template, not an ordinary class.  It's
8179                    important that we use make_friend_class since it will
8180                    perform some error-checking and output cross-reference
8181                    information.  */
8182                 ++processing_template_decl;
8183
8184               if (friend_type != error_mark_node)
8185                 make_friend_class (type, friend_type, /*complain=*/false);
8186
8187               if (adjust_processing_template_decl)
8188                 --processing_template_decl;
8189             }
8190           else
8191             {
8192               /* Build new DECL_FRIENDLIST.  */
8193               tree r;
8194
8195               /* The file and line for this declaration, to
8196                  assist in error message reporting.  Since we
8197                  called push_tinst_level above, we don't need to
8198                  restore these.  */
8199               input_location = DECL_SOURCE_LOCATION (t);
8200
8201               if (TREE_CODE (t) == TEMPLATE_DECL)
8202                 {
8203                   ++processing_template_decl;
8204                   push_deferring_access_checks (dk_no_check);
8205                 }
8206
8207               r = tsubst_friend_function (t, args);
8208               add_friend (type, r, /*complain=*/false);
8209               if (TREE_CODE (t) == TEMPLATE_DECL)
8210                 {
8211                   pop_deferring_access_checks ();
8212                   --processing_template_decl;
8213                 }
8214             }
8215         }
8216     }
8217
8218   /* Set the file and line number information to whatever is given for
8219      the class itself.  This puts error messages involving generated
8220      implicit functions at a predictable point, and the same point
8221      that would be used for non-template classes.  */
8222   input_location = DECL_SOURCE_LOCATION (typedecl);
8223
8224   unreverse_member_declarations (type);
8225   finish_struct_1 (type);
8226   TYPE_BEING_DEFINED (type) = 0;
8227
8228   /* Now that the class is complete, instantiate default arguments for
8229      any member functions.  We don't do this earlier because the
8230      default arguments may reference members of the class.  */
8231   if (!PRIMARY_TEMPLATE_P (templ))
8232     for (t = TYPE_METHODS (type); t; t = DECL_CHAIN (t))
8233       if (TREE_CODE (t) == FUNCTION_DECL
8234           /* Implicitly generated member functions will not have template
8235              information; they are not instantiations, but instead are
8236              created "fresh" for each instantiation.  */
8237           && DECL_TEMPLATE_INFO (t))
8238         tsubst_default_arguments (t);
8239
8240   /* Some typedefs referenced from within the template code need to be access
8241      checked at template instantiation time, i.e now. These types were
8242      added to the template at parsing time. Let's get those and perform
8243      the access checks then.  */
8244   perform_typedefs_access_check (pattern, args);
8245   perform_deferred_access_checks ();
8246   pop_nested_class ();
8247   maximum_field_alignment = saved_maximum_field_alignment;
8248   pop_from_top_level ();
8249   pop_deferring_access_checks ();
8250   pop_tinst_level ();
8251
8252   /* The vtable for a template class can be emitted in any translation
8253      unit in which the class is instantiated.  When there is no key
8254      method, however, finish_struct_1 will already have added TYPE to
8255      the keyed_classes list.  */
8256   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8257     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8258
8259   return type;
8260 }
8261
8262 static tree
8263 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8264 {
8265   tree r;
8266
8267   if (!t)
8268     r = t;
8269   else if (TYPE_P (t))
8270     r = tsubst (t, args, complain, in_decl);
8271   else
8272     {
8273       r = tsubst_expr (t, args, complain, in_decl,
8274                        /*integral_constant_expression_p=*/true);
8275       r = fold_non_dependent_expr (r);
8276     }
8277   return r;
8278 }
8279
8280 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8281    NONTYPE_ARGUMENT_PACK.  */
8282
8283 static tree
8284 make_fnparm_pack (tree spec_parm)
8285 {
8286   /* Collect all of the extra "packed" parameters into an
8287      argument pack.  */
8288   tree parmvec;
8289   tree parmtypevec;
8290   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8291   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8292   int i, len = list_length (spec_parm);
8293
8294   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8295   parmvec = make_tree_vec (len);
8296   parmtypevec = make_tree_vec (len);
8297   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
8298     {
8299       TREE_VEC_ELT (parmvec, i) = spec_parm;
8300       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8301     }
8302
8303   /* Build the argument packs.  */
8304   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8305   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8306   TREE_TYPE (argpack) = argtypepack;
8307
8308   return argpack;
8309 }        
8310
8311 /* Substitute ARGS into T, which is an pack expansion
8312    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8313    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8314    (if only a partial substitution could be performed) or
8315    ERROR_MARK_NODE if there was an error.  */
8316 tree
8317 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8318                        tree in_decl)
8319 {
8320   tree pattern;
8321   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8322   int i, len = -1;
8323   tree result;
8324   int incomplete = 0;
8325   htab_t saved_local_specializations = NULL;
8326
8327   gcc_assert (PACK_EXPANSION_P (t));
8328   pattern = PACK_EXPANSION_PATTERN (t);
8329
8330   /* Determine the argument packs that will instantiate the parameter
8331      packs used in the expansion expression. While we're at it,
8332      compute the number of arguments to be expanded and make sure it
8333      is consistent.  */
8334   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8335        pack = TREE_CHAIN (pack))
8336     {
8337       tree parm_pack = TREE_VALUE (pack);
8338       tree arg_pack = NULL_TREE;
8339       tree orig_arg = NULL_TREE;
8340
8341       if (TREE_CODE (parm_pack) == PARM_DECL)
8342         {
8343           if (!cp_unevaluated_operand)
8344             arg_pack = retrieve_local_specialization (parm_pack);
8345           else
8346             {
8347               /* We can't rely on local_specializations for a parameter
8348                  name used later in a function declaration (such as in a
8349                  late-specified return type).  Even if it exists, it might
8350                  have the wrong value for a recursive call.  Just make a
8351                  dummy decl, since it's only used for its type.  */
8352               arg_pack = tsubst_decl (parm_pack, args, complain);
8353               arg_pack = make_fnparm_pack (arg_pack);
8354             }
8355         }
8356       else
8357         {
8358           int level, idx, levels;
8359           template_parm_level_and_index (parm_pack, &level, &idx);
8360
8361           levels = TMPL_ARGS_DEPTH (args);
8362           if (level <= levels)
8363             arg_pack = TMPL_ARG (args, level, idx);
8364         }
8365
8366       orig_arg = arg_pack;
8367       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8368         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8369       
8370       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8371         /* This can only happen if we forget to expand an argument
8372            pack somewhere else. Just return an error, silently.  */
8373         {
8374           result = make_tree_vec (1);
8375           TREE_VEC_ELT (result, 0) = error_mark_node;
8376           return result;
8377         }
8378
8379       if (arg_pack
8380           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8381           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8382         {
8383           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8384           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8385           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8386               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8387             /* The argument pack that the parameter maps to is just an
8388                expansion of the parameter itself, such as one would
8389                find in the implicit typedef of a class inside the
8390                class itself.  Consider this parameter "unsubstituted",
8391                so that we will maintain the outer pack expansion.  */
8392             arg_pack = NULL_TREE;
8393         }
8394           
8395       if (arg_pack)
8396         {
8397           int my_len = 
8398             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8399
8400           /* It's all-or-nothing with incomplete argument packs.  */
8401           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8402             return error_mark_node;
8403           
8404           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8405             incomplete = 1;
8406
8407           if (len < 0)
8408             len = my_len;
8409           else if (len != my_len)
8410             {
8411               if (incomplete)
8412                 /* We got explicit args for some packs but not others;
8413                    do nothing now and try again after deduction.  */
8414                 return t;
8415               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8416                 error ("mismatched argument pack lengths while expanding "
8417                        "%<%T%>",
8418                        pattern);
8419               else
8420                 error ("mismatched argument pack lengths while expanding "
8421                        "%<%E%>",
8422                        pattern);
8423               return error_mark_node;
8424             }
8425
8426           /* Keep track of the parameter packs and their corresponding
8427              argument packs.  */
8428           packs = tree_cons (parm_pack, arg_pack, packs);
8429           TREE_TYPE (packs) = orig_arg;
8430         }
8431       else
8432         /* We can't substitute for this parameter pack.  */
8433         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8434                                          TREE_VALUE (pack),
8435                                          unsubstituted_packs);
8436     }
8437
8438   /* We cannot expand this expansion expression, because we don't have
8439      all of the argument packs we need. Substitute into the pattern
8440      and return a PACK_EXPANSION_*. The caller will need to deal with
8441      that.  */
8442   if (unsubstituted_packs)
8443     {
8444       tree new_pat;
8445       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8446         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8447                                /*integral_constant_expression_p=*/false);
8448       else
8449         new_pat = tsubst (pattern, args, complain, in_decl);
8450       return make_pack_expansion (new_pat);
8451     }
8452
8453   /* We could not find any argument packs that work.  */
8454   if (len < 0)
8455     return error_mark_node;
8456
8457   if (cp_unevaluated_operand)
8458     {
8459       /* We're in a late-specified return type, so create our own local
8460          specializations table; the current table is either NULL or (in the
8461          case of recursive unification) might have bindings that we don't
8462          want to use or alter.  */
8463       saved_local_specializations = local_specializations;
8464       local_specializations = htab_create (37,
8465                                            hash_local_specialization,
8466                                            eq_local_specializations,
8467                                            NULL);
8468     }
8469
8470   /* For each argument in each argument pack, substitute into the
8471      pattern.  */
8472   result = make_tree_vec (len + incomplete);
8473   for (i = 0; i < len + incomplete; ++i)
8474     {
8475       /* For parameter pack, change the substitution of the parameter
8476          pack to the ith argument in its argument pack, then expand
8477          the pattern.  */
8478       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8479         {
8480           tree parm = TREE_PURPOSE (pack);
8481
8482           if (TREE_CODE (parm) == PARM_DECL)
8483             {
8484               /* Select the Ith argument from the pack.  */
8485               tree arg = make_node (ARGUMENT_PACK_SELECT);
8486               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8487               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8488               mark_used (parm);
8489               register_local_specialization (arg, parm);
8490             }
8491           else
8492             {
8493               tree value = parm;
8494               int idx, level;
8495               template_parm_level_and_index (parm, &level, &idx);
8496               
8497               if (i < len) 
8498                 {
8499                   /* Select the Ith argument from the pack. */
8500                   value = make_node (ARGUMENT_PACK_SELECT);
8501                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8502                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8503                 }
8504
8505               /* Update the corresponding argument.  */
8506               TMPL_ARG (args, level, idx) = value;
8507             }
8508         }
8509
8510       /* Substitute into the PATTERN with the altered arguments.  */
8511       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8512         TREE_VEC_ELT (result, i) = 
8513           tsubst_expr (pattern, args, complain, in_decl,
8514                        /*integral_constant_expression_p=*/false);
8515       else
8516         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8517
8518       if (i == len)
8519         /* When we have incomplete argument packs, the last "expanded"
8520            result is itself a pack expansion, which allows us
8521            to deduce more arguments.  */
8522         TREE_VEC_ELT (result, i) = 
8523           make_pack_expansion (TREE_VEC_ELT (result, i));
8524
8525       if (TREE_VEC_ELT (result, i) == error_mark_node)
8526         {
8527           result = error_mark_node;
8528           break;
8529         }
8530     }
8531
8532   /* Update ARGS to restore the substitution from parameter packs to
8533      their argument packs.  */
8534   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8535     {
8536       tree parm = TREE_PURPOSE (pack);
8537
8538       if (TREE_CODE (parm) == PARM_DECL)
8539         register_local_specialization (TREE_TYPE (pack), parm);
8540       else
8541         {
8542           int idx, level;
8543           template_parm_level_and_index (parm, &level, &idx);
8544           
8545           /* Update the corresponding argument.  */
8546           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8547             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8548               TREE_TYPE (pack);
8549           else
8550             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8551         }
8552     }
8553
8554   if (saved_local_specializations)
8555     {
8556       htab_delete (local_specializations);
8557       local_specializations = saved_local_specializations;
8558     }
8559   
8560   return result;
8561 }
8562
8563 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8564    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8565    parameter packs; all parms generated from a function parameter pack will
8566    have the same DECL_PARM_INDEX.  */
8567
8568 tree
8569 get_pattern_parm (tree parm, tree tmpl)
8570 {
8571   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8572   tree patparm;
8573
8574   if (DECL_ARTIFICIAL (parm))
8575     {
8576       for (patparm = DECL_ARGUMENTS (pattern);
8577            patparm; patparm = DECL_CHAIN (patparm))
8578         if (DECL_ARTIFICIAL (patparm)
8579             && DECL_NAME (parm) == DECL_NAME (patparm))
8580           break;
8581     }
8582   else
8583     {
8584       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8585       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8586       gcc_assert (DECL_PARM_INDEX (patparm)
8587                   == DECL_PARM_INDEX (parm));
8588     }
8589
8590   return patparm;
8591 }
8592
8593 /* Substitute ARGS into the vector or list of template arguments T.  */
8594
8595 static tree
8596 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8597 {
8598   tree orig_t = t;
8599   int len = TREE_VEC_LENGTH (t);
8600   int need_new = 0, i, expanded_len_adjust = 0, out;
8601   tree *elts = XALLOCAVEC (tree, len);
8602
8603   for (i = 0; i < len; i++)
8604     {
8605       tree orig_arg = TREE_VEC_ELT (t, i);
8606       tree new_arg;
8607
8608       if (TREE_CODE (orig_arg) == TREE_VEC)
8609         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8610       else if (PACK_EXPANSION_P (orig_arg))
8611         {
8612           /* Substitute into an expansion expression.  */
8613           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8614
8615           if (TREE_CODE (new_arg) == TREE_VEC)
8616             /* Add to the expanded length adjustment the number of
8617                expanded arguments. We subtract one from this
8618                measurement, because the argument pack expression
8619                itself is already counted as 1 in
8620                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8621                the argument pack is empty.  */
8622             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8623         }
8624       else if (ARGUMENT_PACK_P (orig_arg))
8625         {
8626           /* Substitute into each of the arguments.  */
8627           new_arg = TYPE_P (orig_arg)
8628             ? cxx_make_type (TREE_CODE (orig_arg))
8629             : make_node (TREE_CODE (orig_arg));
8630           
8631           SET_ARGUMENT_PACK_ARGS (
8632             new_arg,
8633             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8634                                   args, complain, in_decl));
8635
8636           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8637             new_arg = error_mark_node;
8638
8639           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8640             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8641                                           complain, in_decl);
8642             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8643
8644             if (TREE_TYPE (new_arg) == error_mark_node)
8645               new_arg = error_mark_node;
8646           }
8647         }
8648       else
8649         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8650
8651       if (new_arg == error_mark_node)
8652         return error_mark_node;
8653
8654       elts[i] = new_arg;
8655       if (new_arg != orig_arg)
8656         need_new = 1;
8657     }
8658
8659   if (!need_new)
8660     return t;
8661
8662   /* Make space for the expanded arguments coming from template
8663      argument packs.  */
8664   t = make_tree_vec (len + expanded_len_adjust);
8665   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
8666      arguments for a member template.
8667      In that case each TREE_VEC in ORIG_T represents a level of template
8668      arguments, and ORIG_T won't carry any non defaulted argument count.
8669      It will rather be the nested TREE_VECs that will carry one.
8670      In other words, ORIG_T carries a non defaulted argument count only
8671      if it doesn't contain any nested TREE_VEC.  */
8672   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
8673     {
8674       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
8675       count += expanded_len_adjust;
8676       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
8677     }
8678   for (i = 0, out = 0; i < len; i++)
8679     {
8680       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8681            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8682           && TREE_CODE (elts[i]) == TREE_VEC)
8683         {
8684           int idx;
8685
8686           /* Now expand the template argument pack "in place".  */
8687           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8688             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8689         }
8690       else
8691         {
8692           TREE_VEC_ELT (t, out) = elts[i];
8693           out++;
8694         }
8695     }
8696
8697   return t;
8698 }
8699
8700 /* Return the result of substituting ARGS into the template parameters
8701    given by PARMS.  If there are m levels of ARGS and m + n levels of
8702    PARMS, then the result will contain n levels of PARMS.  For
8703    example, if PARMS is `template <class T> template <class U>
8704    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8705    result will be `template <int*, double, class V>'.  */
8706
8707 static tree
8708 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8709 {
8710   tree r = NULL_TREE;
8711   tree* new_parms;
8712
8713   /* When substituting into a template, we must set
8714      PROCESSING_TEMPLATE_DECL as the template parameters may be
8715      dependent if they are based on one-another, and the dependency
8716      predicates are short-circuit outside of templates.  */
8717   ++processing_template_decl;
8718
8719   for (new_parms = &r;
8720        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8721        new_parms = &(TREE_CHAIN (*new_parms)),
8722          parms = TREE_CHAIN (parms))
8723     {
8724       tree new_vec =
8725         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8726       int i;
8727
8728       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8729         {
8730           tree tuple;
8731           tree default_value;
8732           tree parm_decl;
8733
8734           if (parms == error_mark_node)
8735             continue;
8736
8737           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8738
8739           if (tuple == error_mark_node)
8740             continue;
8741
8742           default_value = TREE_PURPOSE (tuple);
8743           parm_decl = TREE_VALUE (tuple);
8744
8745           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8746           if (TREE_CODE (parm_decl) == PARM_DECL
8747               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8748             parm_decl = error_mark_node;
8749           default_value = tsubst_template_arg (default_value, args,
8750                                                complain, NULL_TREE);
8751
8752           tuple = build_tree_list (default_value, parm_decl);
8753           TREE_VEC_ELT (new_vec, i) = tuple;
8754         }
8755
8756       *new_parms =
8757         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8758                              - TMPL_ARGS_DEPTH (args)),
8759                    new_vec, NULL_TREE);
8760     }
8761
8762   --processing_template_decl;
8763
8764   return r;
8765 }
8766
8767 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8768    type T.  If T is not an aggregate or enumeration type, it is
8769    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8770    ENTERING_SCOPE is nonzero, T is the context for a template which
8771    we are presently tsubst'ing.  Return the substituted value.  */
8772
8773 static tree
8774 tsubst_aggr_type (tree t,
8775                   tree args,
8776                   tsubst_flags_t complain,
8777                   tree in_decl,
8778                   int entering_scope)
8779 {
8780   if (t == NULL_TREE)
8781     return NULL_TREE;
8782
8783   switch (TREE_CODE (t))
8784     {
8785     case RECORD_TYPE:
8786       if (TYPE_PTRMEMFUNC_P (t))
8787         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8788
8789       /* Else fall through.  */
8790     case ENUMERAL_TYPE:
8791     case UNION_TYPE:
8792       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8793         {
8794           tree argvec;
8795           tree context;
8796           tree r;
8797           int saved_unevaluated_operand;
8798           int saved_inhibit_evaluation_warnings;
8799
8800           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8801           saved_unevaluated_operand = cp_unevaluated_operand;
8802           cp_unevaluated_operand = 0;
8803           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8804           c_inhibit_evaluation_warnings = 0;
8805
8806           /* First, determine the context for the type we are looking
8807              up.  */
8808           context = TYPE_CONTEXT (t);
8809           if (context)
8810             {
8811               context = tsubst_aggr_type (context, args, complain,
8812                                           in_decl, /*entering_scope=*/1);
8813               /* If context is a nested class inside a class template,
8814                  it may still need to be instantiated (c++/33959).  */
8815               if (TYPE_P (context))
8816                 context = complete_type (context);
8817             }
8818
8819           /* Then, figure out what arguments are appropriate for the
8820              type we are trying to find.  For example, given:
8821
8822                template <class T> struct S;
8823                template <class T, class U> void f(T, U) { S<U> su; }
8824
8825              and supposing that we are instantiating f<int, double>,
8826              then our ARGS will be {int, double}, but, when looking up
8827              S we only want {double}.  */
8828           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8829                                          complain, in_decl);
8830           if (argvec == error_mark_node)
8831             r = error_mark_node;
8832           else
8833             {
8834               r = lookup_template_class (t, argvec, in_decl, context,
8835                                          entering_scope, complain);
8836               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
8837             }
8838
8839           cp_unevaluated_operand = saved_unevaluated_operand;
8840           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8841
8842           return r;
8843         }
8844       else
8845         /* This is not a template type, so there's nothing to do.  */
8846         return t;
8847
8848     default:
8849       return tsubst (t, args, complain, in_decl);
8850     }
8851 }
8852
8853 /* Substitute into the default argument ARG (a default argument for
8854    FN), which has the indicated TYPE.  */
8855
8856 tree
8857 tsubst_default_argument (tree fn, tree type, tree arg)
8858 {
8859   tree saved_class_ptr = NULL_TREE;
8860   tree saved_class_ref = NULL_TREE;
8861
8862   /* This default argument came from a template.  Instantiate the
8863      default argument here, not in tsubst.  In the case of
8864      something like:
8865
8866        template <class T>
8867        struct S {
8868          static T t();
8869          void f(T = t());
8870        };
8871
8872      we must be careful to do name lookup in the scope of S<T>,
8873      rather than in the current class.  */
8874   push_access_scope (fn);
8875   /* The "this" pointer is not valid in a default argument.  */
8876   if (cfun)
8877     {
8878       saved_class_ptr = current_class_ptr;
8879       cp_function_chain->x_current_class_ptr = NULL_TREE;
8880       saved_class_ref = current_class_ref;
8881       cp_function_chain->x_current_class_ref = NULL_TREE;
8882     }
8883
8884   push_deferring_access_checks(dk_no_deferred);
8885   /* The default argument expression may cause implicitly defined
8886      member functions to be synthesized, which will result in garbage
8887      collection.  We must treat this situation as if we were within
8888      the body of function so as to avoid collecting live data on the
8889      stack.  */
8890   ++function_depth;
8891   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8892                      tf_warning_or_error, NULL_TREE,
8893                      /*integral_constant_expression_p=*/false);
8894   --function_depth;
8895   pop_deferring_access_checks();
8896
8897   /* Restore the "this" pointer.  */
8898   if (cfun)
8899     {
8900       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8901       cp_function_chain->x_current_class_ref = saved_class_ref;
8902     }
8903
8904   /* Make sure the default argument is reasonable.  */
8905   arg = check_default_argument (type, arg);
8906
8907   pop_access_scope (fn);
8908
8909   return arg;
8910 }
8911
8912 /* Substitute into all the default arguments for FN.  */
8913
8914 static void
8915 tsubst_default_arguments (tree fn)
8916 {
8917   tree arg;
8918   tree tmpl_args;
8919
8920   tmpl_args = DECL_TI_ARGS (fn);
8921
8922   /* If this function is not yet instantiated, we certainly don't need
8923      its default arguments.  */
8924   if (uses_template_parms (tmpl_args))
8925     return;
8926
8927   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8928        arg;
8929        arg = TREE_CHAIN (arg))
8930     if (TREE_PURPOSE (arg))
8931       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8932                                                     TREE_VALUE (arg),
8933                                                     TREE_PURPOSE (arg));
8934 }
8935
8936 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8937    result of the substitution.  Issue error and warning messages under
8938    control of COMPLAIN.  */
8939
8940 static tree
8941 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8942 {
8943 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8944   location_t saved_loc;
8945   tree r = NULL_TREE;
8946   tree in_decl = t;
8947   hashval_t hash = 0;
8948
8949   /* Set the filename and linenumber to improve error-reporting.  */
8950   saved_loc = input_location;
8951   input_location = DECL_SOURCE_LOCATION (t);
8952
8953   switch (TREE_CODE (t))
8954     {
8955     case TEMPLATE_DECL:
8956       {
8957         /* We can get here when processing a member function template,
8958            member class template, or template template parameter.  */
8959         tree decl = DECL_TEMPLATE_RESULT (t);
8960         tree spec;
8961         tree tmpl_args;
8962         tree full_args;
8963
8964         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8965           {
8966             /* Template template parameter is treated here.  */
8967             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8968             if (new_type == error_mark_node)
8969               RETURN (error_mark_node);
8970
8971             r = copy_decl (t);
8972             DECL_CHAIN (r) = NULL_TREE;
8973             TREE_TYPE (r) = new_type;
8974             DECL_TEMPLATE_RESULT (r)
8975               = build_decl (DECL_SOURCE_LOCATION (decl),
8976                             TYPE_DECL, DECL_NAME (decl), new_type);
8977             DECL_TEMPLATE_PARMS (r)
8978               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8979                                        complain);
8980             TYPE_NAME (new_type) = r;
8981             break;
8982           }
8983
8984         /* We might already have an instance of this template.
8985            The ARGS are for the surrounding class type, so the
8986            full args contain the tsubst'd args for the context,
8987            plus the innermost args from the template decl.  */
8988         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8989           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8990           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8991         /* Because this is a template, the arguments will still be
8992            dependent, even after substitution.  If
8993            PROCESSING_TEMPLATE_DECL is not set, the dependency
8994            predicates will short-circuit.  */
8995         ++processing_template_decl;
8996         full_args = tsubst_template_args (tmpl_args, args,
8997                                           complain, in_decl);
8998         --processing_template_decl;
8999         if (full_args == error_mark_node)
9000           RETURN (error_mark_node);
9001
9002         /* If this is a default template template argument,
9003            tsubst might not have changed anything.  */
9004         if (full_args == tmpl_args)
9005           RETURN (t);
9006
9007         hash = hash_tmpl_and_args (t, full_args);
9008         spec = retrieve_specialization (t, full_args, hash);
9009         if (spec != NULL_TREE)
9010           {
9011             r = spec;
9012             break;
9013           }
9014
9015         /* Make a new template decl.  It will be similar to the
9016            original, but will record the current template arguments.
9017            We also create a new function declaration, which is just
9018            like the old one, but points to this new template, rather
9019            than the old one.  */
9020         r = copy_decl (t);
9021         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9022         DECL_CHAIN (r) = NULL_TREE;
9023
9024         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9025
9026         if (TREE_CODE (decl) == TYPE_DECL)
9027           {
9028             tree new_type;
9029             ++processing_template_decl;
9030             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9031             --processing_template_decl;
9032             if (new_type == error_mark_node)
9033               RETURN (error_mark_node);
9034
9035             TREE_TYPE (r) = new_type;
9036             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9037             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9038             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9039             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9040           }
9041         else
9042           {
9043             tree new_decl;
9044             ++processing_template_decl;
9045             new_decl = tsubst (decl, args, complain, in_decl);
9046             --processing_template_decl;
9047             if (new_decl == error_mark_node)
9048               RETURN (error_mark_node);
9049
9050             DECL_TEMPLATE_RESULT (r) = new_decl;
9051             DECL_TI_TEMPLATE (new_decl) = r;
9052             TREE_TYPE (r) = TREE_TYPE (new_decl);
9053             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9054             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9055           }
9056
9057         SET_DECL_IMPLICIT_INSTANTIATION (r);
9058         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9059         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9060
9061         /* The template parameters for this new template are all the
9062            template parameters for the old template, except the
9063            outermost level of parameters.  */
9064         DECL_TEMPLATE_PARMS (r)
9065           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9066                                    complain);
9067
9068         if (PRIMARY_TEMPLATE_P (t))
9069           DECL_PRIMARY_TEMPLATE (r) = r;
9070
9071         if (TREE_CODE (decl) != TYPE_DECL)
9072           /* Record this non-type partial instantiation.  */
9073           register_specialization (r, t,
9074                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9075                                    false, hash);
9076       }
9077       break;
9078
9079     case FUNCTION_DECL:
9080       {
9081         tree ctx;
9082         tree argvec = NULL_TREE;
9083         tree *friends;
9084         tree gen_tmpl;
9085         tree type;
9086         int member;
9087         int args_depth;
9088         int parms_depth;
9089
9090         /* Nobody should be tsubst'ing into non-template functions.  */
9091         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9092
9093         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9094           {
9095             tree spec;
9096             bool dependent_p;
9097
9098             /* If T is not dependent, just return it.  We have to
9099                increment PROCESSING_TEMPLATE_DECL because
9100                value_dependent_expression_p assumes that nothing is
9101                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9102             ++processing_template_decl;
9103             dependent_p = value_dependent_expression_p (t);
9104             --processing_template_decl;
9105             if (!dependent_p)
9106               RETURN (t);
9107
9108             /* Calculate the most general template of which R is a
9109                specialization, and the complete set of arguments used to
9110                specialize R.  */
9111             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9112             argvec = tsubst_template_args (DECL_TI_ARGS
9113                                           (DECL_TEMPLATE_RESULT
9114                                                  (DECL_TI_TEMPLATE (t))),
9115                                            args, complain, in_decl);
9116
9117             /* Check to see if we already have this specialization.  */
9118             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9119             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9120
9121             if (spec)
9122               {
9123                 r = spec;
9124                 break;
9125               }
9126
9127             /* We can see more levels of arguments than parameters if
9128                there was a specialization of a member template, like
9129                this:
9130
9131                  template <class T> struct S { template <class U> void f(); }
9132                  template <> template <class U> void S<int>::f(U);
9133
9134                Here, we'll be substituting into the specialization,
9135                because that's where we can find the code we actually
9136                want to generate, but we'll have enough arguments for
9137                the most general template.
9138
9139                We also deal with the peculiar case:
9140
9141                  template <class T> struct S {
9142                    template <class U> friend void f();
9143                  };
9144                  template <class U> void f() {}
9145                  template S<int>;
9146                  template void f<double>();
9147
9148                Here, the ARGS for the instantiation of will be {int,
9149                double}.  But, we only need as many ARGS as there are
9150                levels of template parameters in CODE_PATTERN.  We are
9151                careful not to get fooled into reducing the ARGS in
9152                situations like:
9153
9154                  template <class T> struct S { template <class U> void f(U); }
9155                  template <class T> template <> void S<T>::f(int) {}
9156
9157                which we can spot because the pattern will be a
9158                specialization in this case.  */
9159             args_depth = TMPL_ARGS_DEPTH (args);
9160             parms_depth =
9161               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9162             if (args_depth > parms_depth
9163                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9164               args = get_innermost_template_args (args, parms_depth);
9165           }
9166         else
9167           {
9168             /* This special case arises when we have something like this:
9169
9170                  template <class T> struct S {
9171                    friend void f<int>(int, double);
9172                  };
9173
9174                Here, the DECL_TI_TEMPLATE for the friend declaration
9175                will be an IDENTIFIER_NODE.  We are being called from
9176                tsubst_friend_function, and we want only to create a
9177                new decl (R) with appropriate types so that we can call
9178                determine_specialization.  */
9179             gen_tmpl = NULL_TREE;
9180           }
9181
9182         if (DECL_CLASS_SCOPE_P (t))
9183           {
9184             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9185               member = 2;
9186             else
9187               member = 1;
9188             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9189                                     complain, t, /*entering_scope=*/1);
9190           }
9191         else
9192           {
9193             member = 0;
9194             ctx = DECL_CONTEXT (t);
9195           }
9196         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9197         if (type == error_mark_node)
9198           RETURN (error_mark_node);
9199
9200         /* We do NOT check for matching decls pushed separately at this
9201            point, as they may not represent instantiations of this
9202            template, and in any case are considered separate under the
9203            discrete model.  */
9204         r = copy_decl (t);
9205         DECL_USE_TEMPLATE (r) = 0;
9206         TREE_TYPE (r) = type;
9207         /* Clear out the mangled name and RTL for the instantiation.  */
9208         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9209         SET_DECL_RTL (r, NULL);
9210         /* Leave DECL_INITIAL set on deleted instantiations.  */
9211         if (!DECL_DELETED_FN (r))
9212           DECL_INITIAL (r) = NULL_TREE;
9213         DECL_CONTEXT (r) = ctx;
9214
9215         if (member && DECL_CONV_FN_P (r))
9216           /* Type-conversion operator.  Reconstruct the name, in
9217              case it's the name of one of the template's parameters.  */
9218           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9219
9220         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9221                                      complain, t);
9222         DECL_RESULT (r) = NULL_TREE;
9223
9224         TREE_STATIC (r) = 0;
9225         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9226         DECL_EXTERNAL (r) = 1;
9227         /* If this is an instantiation of a function with internal
9228            linkage, we already know what object file linkage will be
9229            assigned to the instantiation.  */
9230         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9231         DECL_DEFER_OUTPUT (r) = 0;
9232         DECL_CHAIN (r) = NULL_TREE;
9233         DECL_PENDING_INLINE_INFO (r) = 0;
9234         DECL_PENDING_INLINE_P (r) = 0;
9235         DECL_SAVED_TREE (r) = NULL_TREE;
9236         DECL_STRUCT_FUNCTION (r) = NULL;
9237         TREE_USED (r) = 0;
9238         /* We'll re-clone as appropriate in instantiate_template.  */
9239         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9240
9241         /* If we aren't complaining now, return on error before we register
9242            the specialization so that we'll complain eventually.  */
9243         if ((complain & tf_error) == 0
9244             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9245             && !grok_op_properties (r, /*complain=*/false))
9246           RETURN (error_mark_node);
9247
9248         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9249            this in the special friend case mentioned above where
9250            GEN_TMPL is NULL.  */
9251         if (gen_tmpl)
9252           {
9253             DECL_TEMPLATE_INFO (r)
9254               = build_template_info (gen_tmpl, argvec);
9255             SET_DECL_IMPLICIT_INSTANTIATION (r);
9256             register_specialization (r, gen_tmpl, argvec, false, hash);
9257
9258             /* We're not supposed to instantiate default arguments
9259                until they are called, for a template.  But, for a
9260                declaration like:
9261
9262                  template <class T> void f ()
9263                  { extern void g(int i = T()); }
9264
9265                we should do the substitution when the template is
9266                instantiated.  We handle the member function case in
9267                instantiate_class_template since the default arguments
9268                might refer to other members of the class.  */
9269             if (!member
9270                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9271                 && !uses_template_parms (argvec))
9272               tsubst_default_arguments (r);
9273           }
9274         else
9275           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9276
9277         /* Copy the list of befriending classes.  */
9278         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9279              *friends;
9280              friends = &TREE_CHAIN (*friends))
9281           {
9282             *friends = copy_node (*friends);
9283             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9284                                             args, complain,
9285                                             in_decl);
9286           }
9287
9288         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9289           {
9290             maybe_retrofit_in_chrg (r);
9291             if (DECL_CONSTRUCTOR_P (r))
9292               grok_ctor_properties (ctx, r);
9293             /* If this is an instantiation of a member template, clone it.
9294                If it isn't, that'll be handled by
9295                clone_constructors_and_destructors.  */
9296             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9297               clone_function_decl (r, /*update_method_vec_p=*/0);
9298           }
9299         else if ((complain & tf_error) != 0
9300                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9301                  && !grok_op_properties (r, /*complain=*/true))
9302           RETURN (error_mark_node);
9303
9304         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9305           SET_DECL_FRIEND_CONTEXT (r,
9306                                    tsubst (DECL_FRIEND_CONTEXT (t),
9307                                             args, complain, in_decl));
9308
9309         /* Possibly limit visibility based on template args.  */
9310         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9311         if (DECL_VISIBILITY_SPECIFIED (t))
9312           {
9313             DECL_VISIBILITY_SPECIFIED (r) = 0;
9314             DECL_ATTRIBUTES (r)
9315               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9316           }
9317         determine_visibility (r);
9318         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9319             && !processing_template_decl)
9320           defaulted_late_check (r);
9321
9322         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9323                                         args, complain, in_decl);
9324       }
9325       break;
9326
9327     case PARM_DECL:
9328       {
9329         tree type = NULL_TREE;
9330         int i, len = 1;
9331         tree expanded_types = NULL_TREE;
9332         tree prev_r = NULL_TREE;
9333         tree first_r = NULL_TREE;
9334
9335         if (FUNCTION_PARAMETER_PACK_P (t))
9336           {
9337             /* If there is a local specialization that isn't a
9338                parameter pack, it means that we're doing a "simple"
9339                substitution from inside tsubst_pack_expansion. Just
9340                return the local specialization (which will be a single
9341                parm).  */
9342             tree spec = retrieve_local_specialization (t);
9343             if (spec 
9344                 && TREE_CODE (spec) == PARM_DECL
9345                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9346               RETURN (spec);
9347
9348             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9349                the parameters in this function parameter pack.  */
9350             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9351                                                     complain, in_decl);
9352             if (TREE_CODE (expanded_types) == TREE_VEC)
9353               {
9354                 len = TREE_VEC_LENGTH (expanded_types);
9355
9356                 /* Zero-length parameter packs are boring. Just substitute
9357                    into the chain.  */
9358                 if (len == 0)
9359                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9360                                   TREE_CHAIN (t)));
9361               }
9362             else
9363               {
9364                 /* All we did was update the type. Make a note of that.  */
9365                 type = expanded_types;
9366                 expanded_types = NULL_TREE;
9367               }
9368           }
9369
9370         /* Loop through all of the parameter's we'll build. When T is
9371            a function parameter pack, LEN is the number of expanded
9372            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9373         r = NULL_TREE;
9374         for (i = 0; i < len; ++i)
9375           {
9376             prev_r = r;
9377             r = copy_node (t);
9378             if (DECL_TEMPLATE_PARM_P (t))
9379               SET_DECL_TEMPLATE_PARM_P (r);
9380
9381             /* An argument of a function parameter pack is not a parameter
9382                pack.  */
9383             FUNCTION_PARAMETER_PACK_P (r) = false;
9384
9385             if (expanded_types)
9386               /* We're on the Ith parameter of the function parameter
9387                  pack.  */
9388               {
9389                 /* Get the Ith type.  */
9390                 type = TREE_VEC_ELT (expanded_types, i);
9391
9392                 if (DECL_NAME (r))
9393                   /* Rename the parameter to include the index.  */
9394                   DECL_NAME (r) =
9395                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9396               }
9397             else if (!type)
9398               /* We're dealing with a normal parameter.  */
9399               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9400
9401             type = type_decays_to (type);
9402             TREE_TYPE (r) = type;
9403             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9404
9405             if (DECL_INITIAL (r))
9406               {
9407                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9408                   DECL_INITIAL (r) = TREE_TYPE (r);
9409                 else
9410                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9411                                              complain, in_decl);
9412               }
9413
9414             DECL_CONTEXT (r) = NULL_TREE;
9415
9416             if (!DECL_TEMPLATE_PARM_P (r))
9417               DECL_ARG_TYPE (r) = type_passed_as (type);
9418
9419             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9420                                             args, complain, in_decl);
9421
9422             /* Keep track of the first new parameter we
9423                generate. That's what will be returned to the
9424                caller.  */
9425             if (!first_r)
9426               first_r = r;
9427
9428             /* Build a proper chain of parameters when substituting
9429                into a function parameter pack.  */
9430             if (prev_r)
9431               DECL_CHAIN (prev_r) = r;
9432           }
9433
9434         if (DECL_CHAIN (t))
9435           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
9436                                    complain, DECL_CHAIN (t));
9437
9438         /* FIRST_R contains the start of the chain we've built.  */
9439         r = first_r;
9440       }
9441       break;
9442
9443     case FIELD_DECL:
9444       {
9445         tree type;
9446
9447         r = copy_decl (t);
9448         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9449         if (type == error_mark_node)
9450           RETURN (error_mark_node);
9451         TREE_TYPE (r) = type;
9452         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9453
9454         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9455         DECL_INITIAL (r)
9456           = tsubst_expr (DECL_INITIAL (t), args,
9457                          complain, in_decl,
9458                          /*integral_constant_expression_p=*/true);
9459         /* We don't have to set DECL_CONTEXT here; it is set by
9460            finish_member_declaration.  */
9461         DECL_CHAIN (r) = NULL_TREE;
9462         if (VOID_TYPE_P (type))
9463           error ("instantiation of %q+D as type %qT", r, type);
9464
9465         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9466                                         args, complain, in_decl);
9467       }
9468       break;
9469
9470     case USING_DECL:
9471       /* We reach here only for member using decls.  */
9472       if (DECL_DEPENDENT_P (t))
9473         {
9474           r = do_class_using_decl
9475             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9476              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9477           if (!r)
9478             r = error_mark_node;
9479           else
9480             {
9481               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9482               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9483             }
9484         }
9485       else
9486         {
9487           r = copy_node (t);
9488           DECL_CHAIN (r) = NULL_TREE;
9489         }
9490       break;
9491
9492     case TYPE_DECL:
9493     case VAR_DECL:
9494       {
9495         tree argvec = NULL_TREE;
9496         tree gen_tmpl = NULL_TREE;
9497         tree spec;
9498         tree tmpl = NULL_TREE;
9499         tree ctx;
9500         tree type = NULL_TREE;
9501         bool local_p;
9502
9503         if (TREE_CODE (t) == TYPE_DECL
9504             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9505           {
9506             /* If this is the canonical decl, we don't have to
9507                mess with instantiations, and often we can't (for
9508                typename, template type parms and such).  Note that
9509                TYPE_NAME is not correct for the above test if
9510                we've copied the type for a typedef.  */
9511             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9512             if (type == error_mark_node)
9513               RETURN (error_mark_node);
9514             r = TYPE_NAME (type);
9515             break;
9516           }
9517
9518         /* Check to see if we already have the specialization we
9519            need.  */
9520         spec = NULL_TREE;
9521         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9522           {
9523             /* T is a static data member or namespace-scope entity.
9524                We have to substitute into namespace-scope variables
9525                (even though such entities are never templates) because
9526                of cases like:
9527                
9528                  template <class T> void f() { extern T t; }
9529
9530                where the entity referenced is not known until
9531                instantiation time.  */
9532             local_p = false;
9533             ctx = DECL_CONTEXT (t);
9534             if (DECL_CLASS_SCOPE_P (t))
9535               {
9536                 ctx = tsubst_aggr_type (ctx, args,
9537                                         complain,
9538                                         in_decl, /*entering_scope=*/1);
9539                 /* If CTX is unchanged, then T is in fact the
9540                    specialization we want.  That situation occurs when
9541                    referencing a static data member within in its own
9542                    class.  We can use pointer equality, rather than
9543                    same_type_p, because DECL_CONTEXT is always
9544                    canonical.  */
9545                 if (ctx == DECL_CONTEXT (t))
9546                   spec = t;
9547               }
9548
9549             if (!spec)
9550               {
9551                 tmpl = DECL_TI_TEMPLATE (t);
9552                 gen_tmpl = most_general_template (tmpl);
9553                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9554                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9555                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9556               }
9557           }
9558         else
9559           {
9560             /* A local variable.  */
9561             local_p = true;
9562             /* Subsequent calls to pushdecl will fill this in.  */
9563             ctx = NULL_TREE;
9564             spec = retrieve_local_specialization (t);
9565           }
9566         /* If we already have the specialization we need, there is
9567            nothing more to do.  */ 
9568         if (spec)
9569           {
9570             r = spec;
9571             break;
9572           }
9573
9574         /* Create a new node for the specialization we need.  */
9575         r = copy_decl (t);
9576         if (type == NULL_TREE)
9577           {
9578             if (is_typedef_decl (t))
9579               type = DECL_ORIGINAL_TYPE (t);
9580             else
9581               type = TREE_TYPE (t);
9582             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
9583               type = strip_array_domain (type);
9584             type = tsubst (type, args, complain, in_decl);
9585           }
9586         if (TREE_CODE (r) == VAR_DECL)
9587           {
9588             /* Even if the original location is out of scope, the
9589                newly substituted one is not.  */
9590             DECL_DEAD_FOR_LOCAL (r) = 0;
9591             DECL_INITIALIZED_P (r) = 0;
9592             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9593             if (type == error_mark_node)
9594               RETURN (error_mark_node);
9595             if (TREE_CODE (type) == FUNCTION_TYPE)
9596               {
9597                 /* It may seem that this case cannot occur, since:
9598
9599                      typedef void f();
9600                      void g() { f x; }
9601
9602                    declares a function, not a variable.  However:
9603       
9604                      typedef void f();
9605                      template <typename T> void g() { T t; }
9606                      template void g<f>();
9607
9608                    is an attempt to declare a variable with function
9609                    type.  */
9610                 error ("variable %qD has function type",
9611                        /* R is not yet sufficiently initialized, so we
9612                           just use its name.  */
9613                        DECL_NAME (r));
9614                 RETURN (error_mark_node);
9615               }
9616             type = complete_type (type);
9617             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9618               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9619             type = check_var_type (DECL_NAME (r), type);
9620
9621             if (DECL_HAS_VALUE_EXPR_P (t))
9622               {
9623                 tree ve = DECL_VALUE_EXPR (t);
9624                 ve = tsubst_expr (ve, args, complain, in_decl,
9625                                   /*constant_expression_p=*/false);
9626                 SET_DECL_VALUE_EXPR (r, ve);
9627               }
9628           }
9629         else if (DECL_SELF_REFERENCE_P (t))
9630           SET_DECL_SELF_REFERENCE_P (r);
9631         TREE_TYPE (r) = type;
9632         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9633         DECL_CONTEXT (r) = ctx;
9634         /* Clear out the mangled name and RTL for the instantiation.  */
9635         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9636         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9637           SET_DECL_RTL (r, NULL);
9638         /* The initializer must not be expanded until it is required;
9639            see [temp.inst].  */
9640         DECL_INITIAL (r) = NULL_TREE;
9641         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9642           SET_DECL_RTL (r, NULL);
9643         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9644         if (TREE_CODE (r) == VAR_DECL)
9645           {
9646             /* Possibly limit visibility based on template args.  */
9647             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9648             if (DECL_VISIBILITY_SPECIFIED (t))
9649               {
9650                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9651                 DECL_ATTRIBUTES (r)
9652                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9653               }
9654             determine_visibility (r);
9655           }
9656
9657         if (!local_p)
9658           {
9659             /* A static data member declaration is always marked
9660                external when it is declared in-class, even if an
9661                initializer is present.  We mimic the non-template
9662                processing here.  */
9663             DECL_EXTERNAL (r) = 1;
9664
9665             register_specialization (r, gen_tmpl, argvec, false, hash);
9666             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9667             SET_DECL_IMPLICIT_INSTANTIATION (r);
9668           }
9669         else if (cp_unevaluated_operand)
9670           {
9671             /* We're substituting this var in a decltype outside of its
9672                scope, such as for a lambda return type.  Don't add it to
9673                local_specializations, do perform auto deduction.  */
9674             tree auto_node = type_uses_auto (type);
9675             tree init
9676               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9677                              /*constant_expression_p=*/false);
9678
9679             if (auto_node && init && describable_type (init))
9680               {
9681                 type = do_auto_deduction (type, init, auto_node);
9682                 TREE_TYPE (r) = type;
9683               }
9684           }
9685         else
9686           register_local_specialization (r, t);
9687
9688         DECL_CHAIN (r) = NULL_TREE;
9689
9690         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9691                                         /*flags=*/0,
9692                                         args, complain, in_decl);
9693
9694         /* Preserve a typedef that names a type.  */
9695         if (is_typedef_decl (r))
9696           {
9697             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
9698             set_underlying_type (r);
9699           }
9700
9701         layout_decl (r, 0);
9702       }
9703       break;
9704
9705     default:
9706       gcc_unreachable ();
9707     }
9708 #undef RETURN
9709
9710  out:
9711   /* Restore the file and line information.  */
9712   input_location = saved_loc;
9713
9714   return r;
9715 }
9716
9717 /* Substitute into the ARG_TYPES of a function type.  */
9718
9719 static tree
9720 tsubst_arg_types (tree arg_types,
9721                   tree args,
9722                   tsubst_flags_t complain,
9723                   tree in_decl)
9724 {
9725   tree remaining_arg_types;
9726   tree type = NULL_TREE;
9727   int i = 1;
9728   tree expanded_args = NULL_TREE;
9729   tree default_arg;
9730
9731   if (!arg_types || arg_types == void_list_node)
9732     return arg_types;
9733
9734   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9735                                           args, complain, in_decl);
9736   if (remaining_arg_types == error_mark_node)
9737     return error_mark_node;
9738
9739   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9740     {
9741       /* For a pack expansion, perform substitution on the
9742          entire expression. Later on, we'll handle the arguments
9743          one-by-one.  */
9744       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9745                                             args, complain, in_decl);
9746
9747       if (TREE_CODE (expanded_args) == TREE_VEC)
9748         /* So that we'll spin through the parameters, one by one.  */
9749         i = TREE_VEC_LENGTH (expanded_args);
9750       else
9751         {
9752           /* We only partially substituted into the parameter
9753              pack. Our type is TYPE_PACK_EXPANSION.  */
9754           type = expanded_args;
9755           expanded_args = NULL_TREE;
9756         }
9757     }
9758
9759   while (i > 0) {
9760     --i;
9761     
9762     if (expanded_args)
9763       type = TREE_VEC_ELT (expanded_args, i);
9764     else if (!type)
9765       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9766
9767     if (type == error_mark_node)
9768       return error_mark_node;
9769     if (VOID_TYPE_P (type))
9770       {
9771         if (complain & tf_error)
9772           {
9773             error ("invalid parameter type %qT", type);
9774             if (in_decl)
9775               error ("in declaration %q+D", in_decl);
9776           }
9777         return error_mark_node;
9778     }
9779     
9780     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9781        top-level qualifiers as required.  */
9782     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9783
9784     /* We do not substitute into default arguments here.  The standard
9785        mandates that they be instantiated only when needed, which is
9786        done in build_over_call.  */
9787     default_arg = TREE_PURPOSE (arg_types);
9788
9789     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9790       {
9791         /* We've instantiated a template before its default arguments
9792            have been parsed.  This can happen for a nested template
9793            class, and is not an error unless we require the default
9794            argument in a call of this function.  */
9795         remaining_arg_types = 
9796           tree_cons (default_arg, type, remaining_arg_types);
9797         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9798                        remaining_arg_types);
9799       }
9800     else
9801       remaining_arg_types = 
9802         hash_tree_cons (default_arg, type, remaining_arg_types);
9803   }
9804         
9805   return remaining_arg_types;
9806 }
9807
9808 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9809    *not* handle the exception-specification for FNTYPE, because the
9810    initial substitution of explicitly provided template parameters
9811    during argument deduction forbids substitution into the
9812    exception-specification:
9813
9814      [temp.deduct]
9815
9816      All references in the function type of the function template to  the
9817      corresponding template parameters are replaced by the specified tem-
9818      plate argument values.  If a substitution in a template parameter or
9819      in  the function type of the function template results in an invalid
9820      type, type deduction fails.  [Note: The equivalent  substitution  in
9821      exception specifications is done only when the function is instanti-
9822      ated, at which point a program is  ill-formed  if  the  substitution
9823      results in an invalid type.]  */
9824
9825 static tree
9826 tsubst_function_type (tree t,
9827                       tree args,
9828                       tsubst_flags_t complain,
9829                       tree in_decl)
9830 {
9831   tree return_type;
9832   tree arg_types;
9833   tree fntype;
9834
9835   /* The TYPE_CONTEXT is not used for function/method types.  */
9836   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9837
9838   /* Substitute the return type.  */
9839   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9840   if (return_type == error_mark_node)
9841     return error_mark_node;
9842   /* The standard does not presently indicate that creation of a
9843      function type with an invalid return type is a deduction failure.
9844      However, that is clearly analogous to creating an array of "void"
9845      or a reference to a reference.  This is core issue #486.  */
9846   if (TREE_CODE (return_type) == ARRAY_TYPE
9847       || TREE_CODE (return_type) == FUNCTION_TYPE)
9848     {
9849       if (complain & tf_error)
9850         {
9851           if (TREE_CODE (return_type) == ARRAY_TYPE)
9852             error ("function returning an array");
9853           else
9854             error ("function returning a function");
9855         }
9856       return error_mark_node;
9857     }
9858
9859   /* Substitute the argument types.  */
9860   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9861                                 complain, in_decl);
9862   if (arg_types == error_mark_node)
9863     return error_mark_node;
9864
9865   /* Construct a new type node and return it.  */
9866   if (TREE_CODE (t) == FUNCTION_TYPE)
9867     {
9868       fntype = build_function_type (return_type, arg_types);
9869       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
9870     }
9871   else
9872     {
9873       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9874       if (! MAYBE_CLASS_TYPE_P (r))
9875         {
9876           /* [temp.deduct]
9877
9878              Type deduction may fail for any of the following
9879              reasons:
9880
9881              -- Attempting to create "pointer to member of T" when T
9882              is not a class type.  */
9883           if (complain & tf_error)
9884             error ("creating pointer to member function of non-class type %qT",
9885                       r);
9886           return error_mark_node;
9887         }
9888
9889       fntype = build_method_type_directly (r, return_type,
9890                                            TREE_CHAIN (arg_types));
9891     }
9892   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9893
9894   return fntype;
9895 }
9896
9897 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9898    ARGS into that specification, and return the substituted
9899    specification.  If there is no specification, return NULL_TREE.  */
9900
9901 static tree
9902 tsubst_exception_specification (tree fntype,
9903                                 tree args,
9904                                 tsubst_flags_t complain,
9905                                 tree in_decl)
9906 {
9907   tree specs;
9908   tree new_specs;
9909
9910   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9911   new_specs = NULL_TREE;
9912   if (specs && TREE_PURPOSE (specs))
9913     {
9914       /* A noexcept-specifier.  */
9915       new_specs = tsubst_copy_and_build
9916         (TREE_PURPOSE (specs), args, complain, in_decl, /*function_p=*/false,
9917          /*integral_constant_expression_p=*/true);
9918       new_specs = build_noexcept_spec (new_specs, complain);
9919     }
9920   else if (specs)
9921     {
9922       if (! TREE_VALUE (specs))
9923         new_specs = specs;
9924       else
9925         while (specs)
9926           {
9927             tree spec;
9928             int i, len = 1;
9929             tree expanded_specs = NULL_TREE;
9930
9931             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9932               {
9933                 /* Expand the pack expansion type.  */
9934                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9935                                                        args, complain,
9936                                                        in_decl);
9937
9938                 if (expanded_specs == error_mark_node)
9939                   return error_mark_node;
9940                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9941                   len = TREE_VEC_LENGTH (expanded_specs);
9942                 else
9943                   {
9944                     /* We're substituting into a member template, so
9945                        we got a TYPE_PACK_EXPANSION back.  Add that
9946                        expansion and move on.  */
9947                     gcc_assert (TREE_CODE (expanded_specs) 
9948                                 == TYPE_PACK_EXPANSION);
9949                     new_specs = add_exception_specifier (new_specs,
9950                                                          expanded_specs,
9951                                                          complain);
9952                     specs = TREE_CHAIN (specs);
9953                     continue;
9954                   }
9955               }
9956
9957             for (i = 0; i < len; ++i)
9958               {
9959                 if (expanded_specs)
9960                   spec = TREE_VEC_ELT (expanded_specs, i);
9961                 else
9962                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9963                 if (spec == error_mark_node)
9964                   return spec;
9965                 new_specs = add_exception_specifier (new_specs, spec, 
9966                                                      complain);
9967               }
9968
9969             specs = TREE_CHAIN (specs);
9970           }
9971     }
9972   return new_specs;
9973 }
9974
9975 /* Take the tree structure T and replace template parameters used
9976    therein with the argument vector ARGS.  IN_DECL is an associated
9977    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9978    Issue error and warning messages under control of COMPLAIN.  Note
9979    that we must be relatively non-tolerant of extensions here, in
9980    order to preserve conformance; if we allow substitutions that
9981    should not be allowed, we may allow argument deductions that should
9982    not succeed, and therefore report ambiguous overload situations
9983    where there are none.  In theory, we could allow the substitution,
9984    but indicate that it should have failed, and allow our caller to
9985    make sure that the right thing happens, but we don't try to do this
9986    yet.
9987
9988    This function is used for dealing with types, decls and the like;
9989    for expressions, use tsubst_expr or tsubst_copy.  */
9990
9991 tree
9992 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9993 {
9994   enum tree_code code;
9995   tree type, r;
9996
9997   if (t == NULL_TREE || t == error_mark_node
9998       || t == integer_type_node
9999       || t == void_type_node
10000       || t == char_type_node
10001       || t == unknown_type_node
10002       || TREE_CODE (t) == NAMESPACE_DECL)
10003     return t;
10004
10005   if (DECL_P (t))
10006     return tsubst_decl (t, args, complain);
10007
10008   if (args == NULL_TREE)
10009     return t;
10010
10011   code = TREE_CODE (t);
10012
10013   if (code == IDENTIFIER_NODE)
10014     type = IDENTIFIER_TYPE_VALUE (t);
10015   else
10016     type = TREE_TYPE (t);
10017
10018   gcc_assert (type != unknown_type_node);
10019
10020   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10021      such as attribute aligned.  */
10022   if (TYPE_P (t)
10023       && TYPE_NAME (t)
10024       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
10025     {
10026       tree decl = TYPE_NAME (t);
10027       
10028       if (DECL_CLASS_SCOPE_P (decl)
10029           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10030           && uses_template_parms (DECL_CONTEXT (decl)))
10031         {
10032           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10033           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10034           r = retrieve_specialization (tmpl, gen_args, 0);
10035         }
10036       else if (DECL_FUNCTION_SCOPE_P (decl)
10037                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10038                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10039         r = retrieve_local_specialization (decl);
10040       else
10041         /* The typedef is from a non-template context.  */
10042         return t;
10043
10044       if (r)
10045         {
10046           r = TREE_TYPE (r);
10047           r = cp_build_qualified_type_real
10048             (r, cp_type_quals (t) | cp_type_quals (r),
10049              complain | tf_ignore_bad_quals);
10050           return r;
10051         }
10052       /* Else we must be instantiating the typedef, so fall through.  */
10053     }
10054
10055   if (type
10056       && code != TYPENAME_TYPE
10057       && code != TEMPLATE_TYPE_PARM
10058       && code != IDENTIFIER_NODE
10059       && code != FUNCTION_TYPE
10060       && code != METHOD_TYPE)
10061     type = tsubst (type, args, complain, in_decl);
10062   if (type == error_mark_node)
10063     return error_mark_node;
10064
10065   switch (code)
10066     {
10067     case RECORD_TYPE:
10068     case UNION_TYPE:
10069     case ENUMERAL_TYPE:
10070       return tsubst_aggr_type (t, args, complain, in_decl,
10071                                /*entering_scope=*/0);
10072
10073     case ERROR_MARK:
10074     case IDENTIFIER_NODE:
10075     case VOID_TYPE:
10076     case REAL_TYPE:
10077     case COMPLEX_TYPE:
10078     case VECTOR_TYPE:
10079     case BOOLEAN_TYPE:
10080     case INTEGER_CST:
10081     case REAL_CST:
10082     case STRING_CST:
10083       return t;
10084
10085     case INTEGER_TYPE:
10086       if (t == integer_type_node)
10087         return t;
10088
10089       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10090           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10091         return t;
10092
10093       {
10094         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10095
10096         max = tsubst_expr (omax, args, complain, in_decl,
10097                            /*integral_constant_expression_p=*/false);
10098
10099         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10100            needed.  */
10101         if (TREE_CODE (max) == NOP_EXPR
10102             && TREE_SIDE_EFFECTS (omax)
10103             && !TREE_TYPE (max))
10104           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10105
10106         max = fold_decl_constant_value (max);
10107
10108         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10109            with TREE_SIDE_EFFECTS that indicates this is not an integral
10110            constant expression.  */
10111         if (processing_template_decl
10112             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10113           {
10114             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10115             TREE_SIDE_EFFECTS (max) = 1;
10116           }
10117
10118         if (TREE_CODE (max) != INTEGER_CST
10119             && !at_function_scope_p ()
10120             && !TREE_SIDE_EFFECTS (max)
10121             && !value_dependent_expression_p (max))
10122           {
10123             if (complain & tf_error)
10124               error ("array bound is not an integer constant");
10125             return error_mark_node;
10126           }
10127
10128         /* [temp.deduct]
10129
10130            Type deduction may fail for any of the following
10131            reasons:
10132
10133              Attempting to create an array with a size that is
10134              zero or negative.  */
10135         if (integer_zerop (max) && !(complain & tf_error))
10136           /* We must fail if performing argument deduction (as
10137              indicated by the state of complain), so that
10138              another substitution can be found.  */
10139           return error_mark_node;
10140         else if (TREE_CODE (max) == INTEGER_CST
10141                  && INT_CST_LT (max, integer_zero_node))
10142           {
10143             if (complain & tf_error)
10144               error ("creating array with negative size (%qE)", max);
10145
10146             return error_mark_node;
10147           }
10148
10149         return compute_array_index_type (NULL_TREE, max);
10150       }
10151
10152     case TEMPLATE_TYPE_PARM:
10153     case TEMPLATE_TEMPLATE_PARM:
10154     case BOUND_TEMPLATE_TEMPLATE_PARM:
10155     case TEMPLATE_PARM_INDEX:
10156       {
10157         int idx;
10158         int level;
10159         int levels;
10160         tree arg = NULL_TREE;
10161
10162         r = NULL_TREE;
10163
10164         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10165         template_parm_level_and_index (t, &level, &idx); 
10166
10167         levels = TMPL_ARGS_DEPTH (args);
10168         if (level <= levels)
10169           {
10170             arg = TMPL_ARG (args, level, idx);
10171
10172             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10173               /* See through ARGUMENT_PACK_SELECT arguments. */
10174               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10175           }
10176
10177         if (arg == error_mark_node)
10178           return error_mark_node;
10179         else if (arg != NULL_TREE)
10180           {
10181             if (ARGUMENT_PACK_P (arg))
10182               /* If ARG is an argument pack, we don't actually want to
10183                  perform a substitution here, because substitutions
10184                  for argument packs are only done
10185                  element-by-element. We can get to this point when
10186                  substituting the type of a non-type template
10187                  parameter pack, when that type actually contains
10188                  template parameter packs from an outer template, e.g.,
10189
10190                  template<typename... Types> struct A {
10191                    template<Types... Values> struct B { };
10192                  };  */
10193               return t;
10194
10195             if (code == TEMPLATE_TYPE_PARM)
10196               {
10197                 int quals;
10198                 gcc_assert (TYPE_P (arg));
10199
10200                 quals = cp_type_quals (arg) | cp_type_quals (t);
10201                   
10202                 return cp_build_qualified_type_real
10203                   (arg, quals, complain | tf_ignore_bad_quals);
10204               }
10205             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10206               {
10207                 /* We are processing a type constructed from a
10208                    template template parameter.  */
10209                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10210                                       args, complain, in_decl);
10211                 if (argvec == error_mark_node)
10212                   return error_mark_node;
10213
10214                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10215                    are resolving nested-types in the signature of a
10216                    member function templates.  Otherwise ARG is a
10217                    TEMPLATE_DECL and is the real template to be
10218                    instantiated.  */
10219                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10220                   arg = TYPE_NAME (arg);
10221
10222                 r = lookup_template_class (arg,
10223                                            argvec, in_decl,
10224                                            DECL_CONTEXT (arg),
10225                                             /*entering_scope=*/0,
10226                                            complain);
10227                 return cp_build_qualified_type_real
10228                   (r, cp_type_quals (t), complain);
10229               }
10230             else
10231               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10232               return unshare_expr (arg);
10233           }
10234
10235         if (level == 1)
10236           /* This can happen during the attempted tsubst'ing in
10237              unify.  This means that we don't yet have any information
10238              about the template parameter in question.  */
10239           return t;
10240
10241         /* If we get here, we must have been looking at a parm for a
10242            more deeply nested template.  Make a new version of this
10243            template parameter, but with a lower level.  */
10244         switch (code)
10245           {
10246           case TEMPLATE_TYPE_PARM:
10247           case TEMPLATE_TEMPLATE_PARM:
10248           case BOUND_TEMPLATE_TEMPLATE_PARM:
10249             if (cp_type_quals (t))
10250               {
10251                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10252                 r = cp_build_qualified_type_real
10253                   (r, cp_type_quals (t),
10254                    complain | (code == TEMPLATE_TYPE_PARM
10255                                ? tf_ignore_bad_quals : 0));
10256               }
10257             else
10258               {
10259                 r = copy_type (t);
10260                 TEMPLATE_TYPE_PARM_INDEX (r)
10261                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10262                                                 r, levels, args, complain);
10263                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10264                 TYPE_MAIN_VARIANT (r) = r;
10265                 TYPE_POINTER_TO (r) = NULL_TREE;
10266                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10267
10268                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10269                   /* We have reduced the level of the template
10270                      template parameter, but not the levels of its
10271                      template parameters, so canonical_type_parameter
10272                      will not be able to find the canonical template
10273                      template parameter for this level. Thus, we
10274                      require structural equality checking to compare
10275                      TEMPLATE_TEMPLATE_PARMs. */
10276                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10277                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10278                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10279                 else
10280                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10281
10282                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10283                   {
10284                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10285                                           complain, in_decl);
10286                     if (argvec == error_mark_node)
10287                       return error_mark_node;
10288
10289                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10290                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10291                   }
10292               }
10293             break;
10294
10295           case TEMPLATE_PARM_INDEX:
10296             r = reduce_template_parm_level (t, type, levels, args, complain);
10297             break;
10298
10299           default:
10300             gcc_unreachable ();
10301           }
10302
10303         return r;
10304       }
10305
10306     case TREE_LIST:
10307       {
10308         tree purpose, value, chain;
10309
10310         if (t == void_list_node)
10311           return t;
10312
10313         purpose = TREE_PURPOSE (t);
10314         if (purpose)
10315           {
10316             purpose = tsubst (purpose, args, complain, in_decl);
10317             if (purpose == error_mark_node)
10318               return error_mark_node;
10319           }
10320         value = TREE_VALUE (t);
10321         if (value)
10322           {
10323             value = tsubst (value, args, complain, in_decl);
10324             if (value == error_mark_node)
10325               return error_mark_node;
10326           }
10327         chain = TREE_CHAIN (t);
10328         if (chain && chain != void_type_node)
10329           {
10330             chain = tsubst (chain, args, complain, in_decl);
10331             if (chain == error_mark_node)
10332               return error_mark_node;
10333           }
10334         if (purpose == TREE_PURPOSE (t)
10335             && value == TREE_VALUE (t)
10336             && chain == TREE_CHAIN (t))
10337           return t;
10338         return hash_tree_cons (purpose, value, chain);
10339       }
10340
10341     case TREE_BINFO:
10342       /* We should never be tsubsting a binfo.  */
10343       gcc_unreachable ();
10344
10345     case TREE_VEC:
10346       /* A vector of template arguments.  */
10347       gcc_assert (!type);
10348       return tsubst_template_args (t, args, complain, in_decl);
10349
10350     case POINTER_TYPE:
10351     case REFERENCE_TYPE:
10352       {
10353         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10354           return t;
10355
10356         /* [temp.deduct]
10357
10358            Type deduction may fail for any of the following
10359            reasons:
10360
10361            -- Attempting to create a pointer to reference type.
10362            -- Attempting to create a reference to a reference type or
10363               a reference to void.
10364
10365           Core issue 106 says that creating a reference to a reference
10366           during instantiation is no longer a cause for failure. We
10367           only enforce this check in strict C++98 mode.  */
10368         if ((TREE_CODE (type) == REFERENCE_TYPE
10369              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10370             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10371           {
10372             static location_t last_loc;
10373
10374             /* We keep track of the last time we issued this error
10375                message to avoid spewing a ton of messages during a
10376                single bad template instantiation.  */
10377             if (complain & tf_error
10378                 && last_loc != input_location)
10379               {
10380                 if (TREE_CODE (type) == VOID_TYPE)
10381                   error ("forming reference to void");
10382                else if (code == POINTER_TYPE)
10383                  error ("forming pointer to reference type %qT", type);
10384                else
10385                   error ("forming reference to reference type %qT", type);
10386                 last_loc = input_location;
10387               }
10388
10389             return error_mark_node;
10390           }
10391         else if (code == POINTER_TYPE)
10392           {
10393             r = build_pointer_type (type);
10394             if (TREE_CODE (type) == METHOD_TYPE)
10395               r = build_ptrmemfunc_type (r);
10396           }
10397         else if (TREE_CODE (type) == REFERENCE_TYPE)
10398           /* In C++0x, during template argument substitution, when there is an
10399              attempt to create a reference to a reference type, reference
10400              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10401
10402              "If a template-argument for a template-parameter T names a type
10403              that is a reference to a type A, an attempt to create the type
10404              'lvalue reference to cv T' creates the type 'lvalue reference to
10405              A,' while an attempt to create the type type rvalue reference to
10406              cv T' creates the type T"
10407           */
10408           r = cp_build_reference_type
10409               (TREE_TYPE (type),
10410                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10411         else
10412           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10413         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
10414
10415         if (r != error_mark_node)
10416           /* Will this ever be needed for TYPE_..._TO values?  */
10417           layout_type (r);
10418
10419         return r;
10420       }
10421     case OFFSET_TYPE:
10422       {
10423         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10424         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10425           {
10426             /* [temp.deduct]
10427
10428                Type deduction may fail for any of the following
10429                reasons:
10430
10431                -- Attempting to create "pointer to member of T" when T
10432                   is not a class type.  */
10433             if (complain & tf_error)
10434               error ("creating pointer to member of non-class type %qT", r);
10435             return error_mark_node;
10436           }
10437         if (TREE_CODE (type) == REFERENCE_TYPE)
10438           {
10439             if (complain & tf_error)
10440               error ("creating pointer to member reference type %qT", type);
10441             return error_mark_node;
10442           }
10443         if (TREE_CODE (type) == VOID_TYPE)
10444           {
10445             if (complain & tf_error)
10446               error ("creating pointer to member of type void");
10447             return error_mark_node;
10448           }
10449         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10450         if (TREE_CODE (type) == FUNCTION_TYPE)
10451           {
10452             /* The type of the implicit object parameter gets its
10453                cv-qualifiers from the FUNCTION_TYPE. */
10454             tree memptr;
10455             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
10456             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10457             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10458                                                  complain);
10459           }
10460         else
10461           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10462                                                cp_type_quals (t),
10463                                                complain);
10464       }
10465     case FUNCTION_TYPE:
10466     case METHOD_TYPE:
10467       {
10468         tree fntype;
10469         tree specs;
10470         fntype = tsubst_function_type (t, args, complain, in_decl);
10471         if (fntype == error_mark_node)
10472           return error_mark_node;
10473
10474         /* Substitute the exception specification.  */
10475         specs = tsubst_exception_specification (t, args, complain,
10476                                                 in_decl);
10477         if (specs == error_mark_node)
10478           return error_mark_node;
10479         if (specs)
10480           fntype = build_exception_variant (fntype, specs);
10481         return fntype;
10482       }
10483     case ARRAY_TYPE:
10484       {
10485         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10486         if (domain == error_mark_node)
10487           return error_mark_node;
10488
10489         /* As an optimization, we avoid regenerating the array type if
10490            it will obviously be the same as T.  */
10491         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10492           return t;
10493
10494         /* These checks should match the ones in grokdeclarator.
10495
10496            [temp.deduct]
10497
10498            The deduction may fail for any of the following reasons:
10499
10500            -- Attempting to create an array with an element type that
10501               is void, a function type, or a reference type, or [DR337]
10502               an abstract class type.  */
10503         if (TREE_CODE (type) == VOID_TYPE
10504             || TREE_CODE (type) == FUNCTION_TYPE
10505             || TREE_CODE (type) == REFERENCE_TYPE)
10506           {
10507             if (complain & tf_error)
10508               error ("creating array of %qT", type);
10509             return error_mark_node;
10510           }
10511         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10512           {
10513             if (complain & tf_error)
10514               error ("creating array of %qT, which is an abstract class type",
10515                      type);
10516             return error_mark_node;
10517           }
10518
10519         r = build_cplus_array_type (type, domain);
10520
10521         if (TYPE_USER_ALIGN (t))
10522           {
10523             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10524             TYPE_USER_ALIGN (r) = 1;
10525           }
10526
10527         return r;
10528       }
10529
10530     case PLUS_EXPR:
10531     case MINUS_EXPR:
10532       {
10533         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10534         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10535
10536         if (e1 == error_mark_node || e2 == error_mark_node)
10537           return error_mark_node;
10538
10539         return fold_build2_loc (input_location,
10540                                 code, TREE_TYPE (t), e1, e2);
10541       }
10542
10543     case NEGATE_EXPR:
10544     case NOP_EXPR:
10545       {
10546         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10547         if (e == error_mark_node)
10548           return error_mark_node;
10549
10550         return fold_build1_loc (input_location, code, TREE_TYPE (t), e);
10551       }
10552
10553     case TYPENAME_TYPE:
10554       {
10555         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10556                                      in_decl, /*entering_scope=*/1);
10557         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10558                               complain, in_decl);
10559
10560         if (ctx == error_mark_node || f == error_mark_node)
10561           return error_mark_node;
10562
10563         if (!MAYBE_CLASS_TYPE_P (ctx))
10564           {
10565             if (complain & tf_error)
10566               error ("%qT is not a class, struct, or union type", ctx);
10567             return error_mark_node;
10568           }
10569         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10570           {
10571             /* Normally, make_typename_type does not require that the CTX
10572                have complete type in order to allow things like:
10573
10574                  template <class T> struct S { typename S<T>::X Y; };
10575
10576                But, such constructs have already been resolved by this
10577                point, so here CTX really should have complete type, unless
10578                it's a partial instantiation.  */
10579             if (!(complain & tf_no_class_instantiations))
10580               ctx = complete_type (ctx);
10581             if (!COMPLETE_TYPE_P (ctx))
10582               {
10583                 if (complain & tf_error)
10584                   cxx_incomplete_type_error (NULL_TREE, ctx);
10585                 return error_mark_node;
10586               }
10587           }
10588
10589         f = make_typename_type (ctx, f, typename_type,
10590                                 (complain & tf_error) | tf_keep_type_decl);
10591         if (f == error_mark_node)
10592           return f;
10593         if (TREE_CODE (f) == TYPE_DECL)
10594           {
10595             complain |= tf_ignore_bad_quals;
10596             f = TREE_TYPE (f);
10597           }
10598
10599         if (TREE_CODE (f) != TYPENAME_TYPE)
10600           {
10601             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10602               error ("%qT resolves to %qT, which is not an enumeration type",
10603                      t, f);
10604             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10605               error ("%qT resolves to %qT, which is is not a class type",
10606                      t, f);
10607           }
10608
10609         return cp_build_qualified_type_real
10610           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10611       }
10612
10613     case UNBOUND_CLASS_TEMPLATE:
10614       {
10615         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10616                                      in_decl, /*entering_scope=*/1);
10617         tree name = TYPE_IDENTIFIER (t);
10618         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10619
10620         if (ctx == error_mark_node || name == error_mark_node)
10621           return error_mark_node;
10622
10623         if (parm_list)
10624           parm_list = tsubst_template_parms (parm_list, args, complain);
10625         return make_unbound_class_template (ctx, name, parm_list, complain);
10626       }
10627
10628     case INDIRECT_REF:
10629     case ADDR_EXPR:
10630     case CALL_EXPR:
10631       gcc_unreachable ();
10632
10633     case ARRAY_REF:
10634       {
10635         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10636         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10637                                /*integral_constant_expression_p=*/false);
10638         if (e1 == error_mark_node || e2 == error_mark_node)
10639           return error_mark_node;
10640
10641         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10642       }
10643
10644     case SCOPE_REF:
10645       {
10646         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10647         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10648         if (e1 == error_mark_node || e2 == error_mark_node)
10649           return error_mark_node;
10650
10651         return build_qualified_name (/*type=*/NULL_TREE,
10652                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10653       }
10654
10655     case TYPEOF_TYPE:
10656       {
10657         tree type;
10658
10659         ++cp_unevaluated_operand;
10660         ++c_inhibit_evaluation_warnings;
10661
10662         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10663                             complain, in_decl,
10664                             /*integral_constant_expression_p=*/false);
10665
10666         --cp_unevaluated_operand;
10667         --c_inhibit_evaluation_warnings;
10668
10669         type = finish_typeof (type);
10670         return cp_build_qualified_type_real (type,
10671                                              cp_type_quals (t)
10672                                              | cp_type_quals (type),
10673                                              complain);
10674       }
10675
10676     case DECLTYPE_TYPE:
10677       {
10678         tree type;
10679
10680         ++cp_unevaluated_operand;
10681         ++c_inhibit_evaluation_warnings;
10682
10683         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10684                             complain, in_decl,
10685                             /*integral_constant_expression_p=*/false);
10686
10687         --cp_unevaluated_operand;
10688         --c_inhibit_evaluation_warnings;
10689
10690         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10691           type = lambda_capture_field_type (type);
10692         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10693           type = lambda_return_type (type);
10694         else
10695           type = finish_decltype_type
10696             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10697         return cp_build_qualified_type_real (type,
10698                                              cp_type_quals (t)
10699                                              | cp_type_quals (type),
10700                                              complain);
10701       }
10702
10703     case TYPE_ARGUMENT_PACK:
10704     case NONTYPE_ARGUMENT_PACK:
10705       {
10706         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
10707         tree packed_out = 
10708           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10709                                 args,
10710                                 complain,
10711                                 in_decl);
10712         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10713
10714         /* For template nontype argument packs, also substitute into
10715            the type.  */
10716         if (code == NONTYPE_ARGUMENT_PACK)
10717           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10718
10719         return r;
10720       }
10721       break;
10722
10723     default:
10724       sorry ("use of %qs in template", tree_code_name [(int) code]);
10725       return error_mark_node;
10726     }
10727 }
10728
10729 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10730    type of the expression on the left-hand side of the "." or "->"
10731    operator.  */
10732
10733 static tree
10734 tsubst_baselink (tree baselink, tree object_type,
10735                  tree args, tsubst_flags_t complain, tree in_decl)
10736 {
10737     tree name;
10738     tree qualifying_scope;
10739     tree fns;
10740     tree optype;
10741     tree template_args = 0;
10742     bool template_id_p = false;
10743
10744     /* A baselink indicates a function from a base class.  Both the
10745        BASELINK_ACCESS_BINFO and the base class referenced may
10746        indicate bases of the template class, rather than the
10747        instantiated class.  In addition, lookups that were not
10748        ambiguous before may be ambiguous now.  Therefore, we perform
10749        the lookup again.  */
10750     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10751     qualifying_scope = tsubst (qualifying_scope, args,
10752                                complain, in_decl);
10753     fns = BASELINK_FUNCTIONS (baselink);
10754     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10755     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10756       {
10757         template_id_p = true;
10758         template_args = TREE_OPERAND (fns, 1);
10759         fns = TREE_OPERAND (fns, 0);
10760         if (template_args)
10761           template_args = tsubst_template_args (template_args, args,
10762                                                 complain, in_decl);
10763       }
10764     name = DECL_NAME (get_first_fn (fns));
10765     if (IDENTIFIER_TYPENAME_P (name))
10766       name = mangle_conv_op_name_for_type (optype);
10767     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10768     if (!baselink)
10769       return error_mark_node;
10770
10771     /* If lookup found a single function, mark it as used at this
10772        point.  (If it lookup found multiple functions the one selected
10773        later by overload resolution will be marked as used at that
10774        point.)  */
10775     if (BASELINK_P (baselink))
10776       fns = BASELINK_FUNCTIONS (baselink);
10777     if (!template_id_p && !really_overloaded_fn (fns))
10778       mark_used (OVL_CURRENT (fns));
10779
10780     /* Add back the template arguments, if present.  */
10781     if (BASELINK_P (baselink) && template_id_p)
10782       BASELINK_FUNCTIONS (baselink)
10783         = build_nt (TEMPLATE_ID_EXPR,
10784                     BASELINK_FUNCTIONS (baselink),
10785                     template_args);
10786     /* Update the conversion operator type.  */
10787     BASELINK_OPTYPE (baselink) = optype;
10788
10789     if (!object_type)
10790       object_type = current_class_type;
10791     return adjust_result_of_qualified_name_lookup (baselink,
10792                                                    qualifying_scope,
10793                                                    object_type);
10794 }
10795
10796 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10797    true if the qualified-id will be a postfix-expression in-and-of
10798    itself; false if more of the postfix-expression follows the
10799    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10800    of "&".  */
10801
10802 static tree
10803 tsubst_qualified_id (tree qualified_id, tree args,
10804                      tsubst_flags_t complain, tree in_decl,
10805                      bool done, bool address_p)
10806 {
10807   tree expr;
10808   tree scope;
10809   tree name;
10810   bool is_template;
10811   tree template_args;
10812
10813   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10814
10815   /* Figure out what name to look up.  */
10816   name = TREE_OPERAND (qualified_id, 1);
10817   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10818     {
10819       is_template = true;
10820       template_args = TREE_OPERAND (name, 1);
10821       if (template_args)
10822         template_args = tsubst_template_args (template_args, args,
10823                                               complain, in_decl);
10824       name = TREE_OPERAND (name, 0);
10825     }
10826   else
10827     {
10828       is_template = false;
10829       template_args = NULL_TREE;
10830     }
10831
10832   /* Substitute into the qualifying scope.  When there are no ARGS, we
10833      are just trying to simplify a non-dependent expression.  In that
10834      case the qualifying scope may be dependent, and, in any case,
10835      substituting will not help.  */
10836   scope = TREE_OPERAND (qualified_id, 0);
10837   if (args)
10838     {
10839       scope = tsubst (scope, args, complain, in_decl);
10840       expr = tsubst_copy (name, args, complain, in_decl);
10841     }
10842   else
10843     expr = name;
10844
10845   if (dependent_scope_p (scope))
10846     return build_qualified_name (NULL_TREE, scope, expr,
10847                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10848
10849   if (!BASELINK_P (name) && !DECL_P (expr))
10850     {
10851       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10852         {
10853           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10854           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10855             {
10856               error ("qualifying type %qT does not match destructor name ~%qT",
10857                      scope, TREE_OPERAND (expr, 0));
10858               expr = error_mark_node;
10859             }
10860           else
10861             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10862                                           /*is_type_p=*/0, false);
10863         }
10864       else
10865         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10866       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10867                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10868         {
10869           if (complain & tf_error)
10870             {
10871               error ("dependent-name %qE is parsed as a non-type, but "
10872                      "instantiation yields a type", qualified_id);
10873               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10874             }
10875           return error_mark_node;
10876         }
10877     }
10878
10879   if (DECL_P (expr))
10880     {
10881       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10882                                            scope);
10883       /* Remember that there was a reference to this entity.  */
10884       mark_used (expr);
10885     }
10886
10887   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10888     {
10889       if (complain & tf_error)
10890         qualified_name_lookup_error (scope,
10891                                      TREE_OPERAND (qualified_id, 1),
10892                                      expr, input_location);
10893       return error_mark_node;
10894     }
10895
10896   if (is_template)
10897     expr = lookup_template_function (expr, template_args);
10898
10899   if (expr == error_mark_node && complain & tf_error)
10900     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10901                                  expr, input_location);
10902   else if (TYPE_P (scope))
10903     {
10904       expr = (adjust_result_of_qualified_name_lookup
10905               (expr, scope, current_class_type));
10906       expr = (finish_qualified_id_expr
10907               (scope, expr, done, address_p,
10908                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10909                /*template_arg_p=*/false));
10910     }
10911
10912   /* Expressions do not generally have reference type.  */
10913   if (TREE_CODE (expr) != SCOPE_REF
10914       /* However, if we're about to form a pointer-to-member, we just
10915          want the referenced member referenced.  */
10916       && TREE_CODE (expr) != OFFSET_REF)
10917     expr = convert_from_reference (expr);
10918
10919   return expr;
10920 }
10921
10922 /* Like tsubst, but deals with expressions.  This function just replaces
10923    template parms; to finish processing the resultant expression, use
10924    tsubst_expr.  */
10925
10926 static tree
10927 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10928 {
10929   enum tree_code code;
10930   tree r;
10931
10932   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10933     return t;
10934
10935   code = TREE_CODE (t);
10936
10937   switch (code)
10938     {
10939     case PARM_DECL:
10940       r = retrieve_local_specialization (t);
10941
10942       if (r == NULL)
10943         {
10944           tree c;
10945           /* This can happen for a parameter name used later in a function
10946              declaration (such as in a late-specified return type).  Just
10947              make a dummy decl, since it's only used for its type.  */
10948           gcc_assert (cp_unevaluated_operand != 0);
10949           /* We copy T because want to tsubst the PARM_DECL only,
10950              not the following PARM_DECLs that are chained to T.  */
10951           c = copy_node (t);
10952           r = tsubst_decl (c, args, complain);
10953           /* Give it the template pattern as its context; its true context
10954              hasn't been instantiated yet and this is good enough for
10955              mangling.  */
10956           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10957         }
10958       
10959       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10960         r = ARGUMENT_PACK_SELECT_ARG (r);
10961       mark_used (r);
10962       return r;
10963
10964     case CONST_DECL:
10965       {
10966         tree enum_type;
10967         tree v;
10968
10969         if (DECL_TEMPLATE_PARM_P (t))
10970           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10971         /* There is no need to substitute into namespace-scope
10972            enumerators.  */
10973         if (DECL_NAMESPACE_SCOPE_P (t))
10974           return t;
10975         /* If ARGS is NULL, then T is known to be non-dependent.  */
10976         if (args == NULL_TREE)
10977           return integral_constant_value (t);
10978
10979         /* Unfortunately, we cannot just call lookup_name here.
10980            Consider:
10981
10982              template <int I> int f() {
10983              enum E { a = I };
10984              struct S { void g() { E e = a; } };
10985              };
10986
10987            When we instantiate f<7>::S::g(), say, lookup_name is not
10988            clever enough to find f<7>::a.  */
10989         enum_type
10990           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10991                               /*entering_scope=*/0);
10992
10993         for (v = TYPE_VALUES (enum_type);
10994              v != NULL_TREE;
10995              v = TREE_CHAIN (v))
10996           if (TREE_PURPOSE (v) == DECL_NAME (t))
10997             return TREE_VALUE (v);
10998
10999           /* We didn't find the name.  That should never happen; if
11000              name-lookup found it during preliminary parsing, we
11001              should find it again here during instantiation.  */
11002         gcc_unreachable ();
11003       }
11004       return t;
11005
11006     case FIELD_DECL:
11007       if (DECL_CONTEXT (t))
11008         {
11009           tree ctx;
11010
11011           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11012                                   /*entering_scope=*/1);
11013           if (ctx != DECL_CONTEXT (t))
11014             {
11015               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11016               if (!r)
11017                 {
11018                   if (complain & tf_error)
11019                     error ("using invalid field %qD", t);
11020                   return error_mark_node;
11021                 }
11022               return r;
11023             }
11024         }
11025
11026       return t;
11027
11028     case VAR_DECL:
11029     case FUNCTION_DECL:
11030       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11031           || local_variable_p (t))
11032         t = tsubst (t, args, complain, in_decl);
11033       mark_used (t);
11034       return t;
11035
11036     case BASELINK:
11037       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11038
11039     case TEMPLATE_DECL:
11040       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11041         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11042                        args, complain, in_decl);
11043       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11044         return tsubst (t, args, complain, in_decl);
11045       else if (DECL_CLASS_SCOPE_P (t)
11046                && uses_template_parms (DECL_CONTEXT (t)))
11047         {
11048           /* Template template argument like the following example need
11049              special treatment:
11050
11051                template <template <class> class TT> struct C {};
11052                template <class T> struct D {
11053                  template <class U> struct E {};
11054                  C<E> c;                                // #1
11055                };
11056                D<int> d;                                // #2
11057
11058              We are processing the template argument `E' in #1 for
11059              the template instantiation #2.  Originally, `E' is a
11060              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11061              have to substitute this with one having context `D<int>'.  */
11062
11063           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11064           return lookup_field (context, DECL_NAME(t), 0, false);
11065         }
11066       else
11067         /* Ordinary template template argument.  */
11068         return t;
11069
11070     case CAST_EXPR:
11071     case REINTERPRET_CAST_EXPR:
11072     case CONST_CAST_EXPR:
11073     case STATIC_CAST_EXPR:
11074     case DYNAMIC_CAST_EXPR:
11075     case NOP_EXPR:
11076       return build1
11077         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11078          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11079
11080     case SIZEOF_EXPR:
11081       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11082         {
11083           /* We only want to compute the number of arguments.  */
11084           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11085                                                 complain, in_decl);
11086           int len = 0;
11087
11088           if (TREE_CODE (expanded) == TREE_VEC)
11089             len = TREE_VEC_LENGTH (expanded);
11090
11091           if (expanded == error_mark_node)
11092             return error_mark_node;
11093           else if (PACK_EXPANSION_P (expanded)
11094                    || (TREE_CODE (expanded) == TREE_VEC
11095                        && len > 0
11096                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11097             {
11098               if (TREE_CODE (expanded) == TREE_VEC)
11099                 expanded = TREE_VEC_ELT (expanded, len - 1);
11100
11101               if (TYPE_P (expanded))
11102                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11103                                                    complain & tf_error);
11104               else
11105                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11106                                                    complain & tf_error);
11107             }
11108           else
11109             return build_int_cst (size_type_node, len);
11110         }
11111       /* Fall through */
11112
11113     case INDIRECT_REF:
11114     case NEGATE_EXPR:
11115     case TRUTH_NOT_EXPR:
11116     case BIT_NOT_EXPR:
11117     case ADDR_EXPR:
11118     case UNARY_PLUS_EXPR:      /* Unary + */
11119     case ALIGNOF_EXPR:
11120     case ARROW_EXPR:
11121     case THROW_EXPR:
11122     case TYPEID_EXPR:
11123     case REALPART_EXPR:
11124     case IMAGPART_EXPR:
11125       return build1
11126         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11127          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11128
11129     case COMPONENT_REF:
11130       {
11131         tree object;
11132         tree name;
11133
11134         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11135         name = TREE_OPERAND (t, 1);
11136         if (TREE_CODE (name) == BIT_NOT_EXPR)
11137           {
11138             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11139                                 complain, in_decl);
11140             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11141           }
11142         else if (TREE_CODE (name) == SCOPE_REF
11143                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11144           {
11145             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11146                                      complain, in_decl);
11147             name = TREE_OPERAND (name, 1);
11148             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11149                                 complain, in_decl);
11150             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11151             name = build_qualified_name (/*type=*/NULL_TREE,
11152                                          base, name,
11153                                          /*template_p=*/false);
11154           }
11155         else if (TREE_CODE (name) == BASELINK)
11156           name = tsubst_baselink (name,
11157                                   non_reference (TREE_TYPE (object)),
11158                                   args, complain,
11159                                   in_decl);
11160         else
11161           name = tsubst_copy (name, args, complain, in_decl);
11162         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11163       }
11164
11165     case PLUS_EXPR:
11166     case MINUS_EXPR:
11167     case MULT_EXPR:
11168     case TRUNC_DIV_EXPR:
11169     case CEIL_DIV_EXPR:
11170     case FLOOR_DIV_EXPR:
11171     case ROUND_DIV_EXPR:
11172     case EXACT_DIV_EXPR:
11173     case BIT_AND_EXPR:
11174     case BIT_IOR_EXPR:
11175     case BIT_XOR_EXPR:
11176     case TRUNC_MOD_EXPR:
11177     case FLOOR_MOD_EXPR:
11178     case TRUTH_ANDIF_EXPR:
11179     case TRUTH_ORIF_EXPR:
11180     case TRUTH_AND_EXPR:
11181     case TRUTH_OR_EXPR:
11182     case RSHIFT_EXPR:
11183     case LSHIFT_EXPR:
11184     case RROTATE_EXPR:
11185     case LROTATE_EXPR:
11186     case EQ_EXPR:
11187     case NE_EXPR:
11188     case MAX_EXPR:
11189     case MIN_EXPR:
11190     case LE_EXPR:
11191     case GE_EXPR:
11192     case LT_EXPR:
11193     case GT_EXPR:
11194     case COMPOUND_EXPR:
11195     case DOTSTAR_EXPR:
11196     case MEMBER_REF:
11197     case PREDECREMENT_EXPR:
11198     case PREINCREMENT_EXPR:
11199     case POSTDECREMENT_EXPR:
11200     case POSTINCREMENT_EXPR:
11201       return build_nt
11202         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11203          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11204
11205     case SCOPE_REF:
11206       return build_qualified_name (/*type=*/NULL_TREE,
11207                                    tsubst_copy (TREE_OPERAND (t, 0),
11208                                                 args, complain, in_decl),
11209                                    tsubst_copy (TREE_OPERAND (t, 1),
11210                                                 args, complain, in_decl),
11211                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11212
11213     case ARRAY_REF:
11214       return build_nt
11215         (ARRAY_REF,
11216          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11217          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11218          NULL_TREE, NULL_TREE);
11219
11220     case CALL_EXPR:
11221       {
11222         int n = VL_EXP_OPERAND_LENGTH (t);
11223         tree result = build_vl_exp (CALL_EXPR, n);
11224         int i;
11225         for (i = 0; i < n; i++)
11226           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11227                                              complain, in_decl);
11228         return result;
11229       }
11230
11231     case COND_EXPR:
11232     case MODOP_EXPR:
11233     case PSEUDO_DTOR_EXPR:
11234       {
11235         r = build_nt
11236           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11237            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11238            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11239         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11240         return r;
11241       }
11242
11243     case NEW_EXPR:
11244       {
11245         r = build_nt
11246         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11247          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11248          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11249         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11250         return r;
11251       }
11252
11253     case DELETE_EXPR:
11254       {
11255         r = build_nt
11256         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11257          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11258         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11259         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11260         return r;
11261       }
11262
11263     case TEMPLATE_ID_EXPR:
11264       {
11265         /* Substituted template arguments */
11266         tree fn = TREE_OPERAND (t, 0);
11267         tree targs = TREE_OPERAND (t, 1);
11268
11269         fn = tsubst_copy (fn, args, complain, in_decl);
11270         if (targs)
11271           targs = tsubst_template_args (targs, args, complain, in_decl);
11272
11273         return lookup_template_function (fn, targs);
11274       }
11275
11276     case TREE_LIST:
11277       {
11278         tree purpose, value, chain;
11279
11280         if (t == void_list_node)
11281           return t;
11282
11283         purpose = TREE_PURPOSE (t);
11284         if (purpose)
11285           purpose = tsubst_copy (purpose, args, complain, in_decl);
11286         value = TREE_VALUE (t);
11287         if (value)
11288           value = tsubst_copy (value, args, complain, in_decl);
11289         chain = TREE_CHAIN (t);
11290         if (chain && chain != void_type_node)
11291           chain = tsubst_copy (chain, args, complain, in_decl);
11292         if (purpose == TREE_PURPOSE (t)
11293             && value == TREE_VALUE (t)
11294             && chain == TREE_CHAIN (t))
11295           return t;
11296         return tree_cons (purpose, value, chain);
11297       }
11298
11299     case RECORD_TYPE:
11300     case UNION_TYPE:
11301     case ENUMERAL_TYPE:
11302     case INTEGER_TYPE:
11303     case TEMPLATE_TYPE_PARM:
11304     case TEMPLATE_TEMPLATE_PARM:
11305     case BOUND_TEMPLATE_TEMPLATE_PARM:
11306     case TEMPLATE_PARM_INDEX:
11307     case POINTER_TYPE:
11308     case REFERENCE_TYPE:
11309     case OFFSET_TYPE:
11310     case FUNCTION_TYPE:
11311     case METHOD_TYPE:
11312     case ARRAY_TYPE:
11313     case TYPENAME_TYPE:
11314     case UNBOUND_CLASS_TEMPLATE:
11315     case TYPEOF_TYPE:
11316     case DECLTYPE_TYPE:
11317     case TYPE_DECL:
11318       return tsubst (t, args, complain, in_decl);
11319
11320     case IDENTIFIER_NODE:
11321       if (IDENTIFIER_TYPENAME_P (t))
11322         {
11323           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11324           return mangle_conv_op_name_for_type (new_type);
11325         }
11326       else
11327         return t;
11328
11329     case CONSTRUCTOR:
11330       /* This is handled by tsubst_copy_and_build.  */
11331       gcc_unreachable ();
11332
11333     case VA_ARG_EXPR:
11334       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11335                                           in_decl),
11336                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11337
11338     case CLEANUP_POINT_EXPR:
11339       /* We shouldn't have built any of these during initial template
11340          generation.  Instead, they should be built during instantiation
11341          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11342       gcc_unreachable ();
11343
11344     case OFFSET_REF:
11345       r = build2
11346         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11347          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11348          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11349       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
11350       mark_used (TREE_OPERAND (r, 1));
11351       return r;
11352
11353     case EXPR_PACK_EXPANSION:
11354       error ("invalid use of pack expansion expression");
11355       return error_mark_node;
11356
11357     case NONTYPE_ARGUMENT_PACK:
11358       error ("use %<...%> to expand argument pack");
11359       return error_mark_node;
11360
11361     default:
11362       return t;
11363     }
11364 }
11365
11366 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11367
11368 static tree
11369 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11370                     tree in_decl)
11371 {
11372   tree new_clauses = NULL, nc, oc;
11373
11374   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11375     {
11376       nc = copy_node (oc);
11377       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11378       new_clauses = nc;
11379
11380       switch (OMP_CLAUSE_CODE (nc))
11381         {
11382         case OMP_CLAUSE_LASTPRIVATE:
11383           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11384             {
11385               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11386               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11387                            in_decl, /*integral_constant_expression_p=*/false);
11388               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11389                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11390             }
11391           /* FALLTHRU */
11392         case OMP_CLAUSE_PRIVATE:
11393         case OMP_CLAUSE_SHARED:
11394         case OMP_CLAUSE_FIRSTPRIVATE:
11395         case OMP_CLAUSE_REDUCTION:
11396         case OMP_CLAUSE_COPYIN:
11397         case OMP_CLAUSE_COPYPRIVATE:
11398         case OMP_CLAUSE_IF:
11399         case OMP_CLAUSE_NUM_THREADS:
11400         case OMP_CLAUSE_SCHEDULE:
11401         case OMP_CLAUSE_COLLAPSE:
11402           OMP_CLAUSE_OPERAND (nc, 0)
11403             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11404                            in_decl, /*integral_constant_expression_p=*/false);
11405           break;
11406         case OMP_CLAUSE_NOWAIT:
11407         case OMP_CLAUSE_ORDERED:
11408         case OMP_CLAUSE_DEFAULT:
11409         case OMP_CLAUSE_UNTIED:
11410           break;
11411         default:
11412           gcc_unreachable ();
11413         }
11414     }
11415
11416   return finish_omp_clauses (nreverse (new_clauses));
11417 }
11418
11419 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11420
11421 static tree
11422 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11423                           tree in_decl)
11424 {
11425 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11426
11427   tree purpose, value, chain;
11428
11429   if (t == NULL)
11430     return t;
11431
11432   if (TREE_CODE (t) != TREE_LIST)
11433     return tsubst_copy_and_build (t, args, complain, in_decl,
11434                                   /*function_p=*/false,
11435                                   /*integral_constant_expression_p=*/false);
11436
11437   if (t == void_list_node)
11438     return t;
11439
11440   purpose = TREE_PURPOSE (t);
11441   if (purpose)
11442     purpose = RECUR (purpose);
11443   value = TREE_VALUE (t);
11444   if (value && TREE_CODE (value) != LABEL_DECL)
11445     value = RECUR (value);
11446   chain = TREE_CHAIN (t);
11447   if (chain && chain != void_type_node)
11448     chain = RECUR (chain);
11449   return tree_cons (purpose, value, chain);
11450 #undef RECUR
11451 }
11452
11453 /* Substitute one OMP_FOR iterator.  */
11454
11455 static void
11456 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11457                          tree condv, tree incrv, tree *clauses,
11458                          tree args, tsubst_flags_t complain, tree in_decl,
11459                          bool integral_constant_expression_p)
11460 {
11461 #define RECUR(NODE)                             \
11462   tsubst_expr ((NODE), args, complain, in_decl, \
11463                integral_constant_expression_p)
11464   tree decl, init, cond, incr, auto_node;
11465
11466   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11467   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11468   decl = RECUR (TREE_OPERAND (init, 0));
11469   init = TREE_OPERAND (init, 1);
11470   auto_node = type_uses_auto (TREE_TYPE (decl));
11471   if (auto_node && init)
11472     {
11473       tree init_expr = init;
11474       if (TREE_CODE (init_expr) == DECL_EXPR)
11475         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11476       init_expr = RECUR (init_expr);
11477       TREE_TYPE (decl)
11478         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11479     }
11480   gcc_assert (!type_dependent_expression_p (decl));
11481
11482   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11483     {
11484       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11485       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11486       if (TREE_CODE (incr) == MODIFY_EXPR)
11487         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11488                                     RECUR (TREE_OPERAND (incr, 1)),
11489                                     complain);
11490       else
11491         incr = RECUR (incr);
11492       TREE_VEC_ELT (declv, i) = decl;
11493       TREE_VEC_ELT (initv, i) = init;
11494       TREE_VEC_ELT (condv, i) = cond;
11495       TREE_VEC_ELT (incrv, i) = incr;
11496       return;
11497     }
11498
11499   if (init && TREE_CODE (init) != DECL_EXPR)
11500     {
11501       tree c;
11502       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11503         {
11504           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11505                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11506               && OMP_CLAUSE_DECL (c) == decl)
11507             break;
11508           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11509                    && OMP_CLAUSE_DECL (c) == decl)
11510             error ("iteration variable %qD should not be firstprivate", decl);
11511           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11512                    && OMP_CLAUSE_DECL (c) == decl)
11513             error ("iteration variable %qD should not be reduction", decl);
11514         }
11515       if (c == NULL)
11516         {
11517           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11518           OMP_CLAUSE_DECL (c) = decl;
11519           c = finish_omp_clauses (c);
11520           if (c)
11521             {
11522               OMP_CLAUSE_CHAIN (c) = *clauses;
11523               *clauses = c;
11524             }
11525         }
11526     }
11527   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11528   if (COMPARISON_CLASS_P (cond))
11529     cond = build2 (TREE_CODE (cond), boolean_type_node,
11530                    RECUR (TREE_OPERAND (cond, 0)),
11531                    RECUR (TREE_OPERAND (cond, 1)));
11532   else
11533     cond = RECUR (cond);
11534   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11535   switch (TREE_CODE (incr))
11536     {
11537     case PREINCREMENT_EXPR:
11538     case PREDECREMENT_EXPR:
11539     case POSTINCREMENT_EXPR:
11540     case POSTDECREMENT_EXPR:
11541       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11542                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11543       break;
11544     case MODIFY_EXPR:
11545       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11546           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11547         {
11548           tree rhs = TREE_OPERAND (incr, 1);
11549           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11550                          RECUR (TREE_OPERAND (incr, 0)),
11551                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11552                                  RECUR (TREE_OPERAND (rhs, 0)),
11553                                  RECUR (TREE_OPERAND (rhs, 1))));
11554         }
11555       else
11556         incr = RECUR (incr);
11557       break;
11558     case MODOP_EXPR:
11559       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11560           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11561         {
11562           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11563           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11564                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11565                                  TREE_TYPE (decl), lhs,
11566                                  RECUR (TREE_OPERAND (incr, 2))));
11567         }
11568       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11569                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11570                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11571         {
11572           tree rhs = TREE_OPERAND (incr, 2);
11573           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11574                          RECUR (TREE_OPERAND (incr, 0)),
11575                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11576                                  RECUR (TREE_OPERAND (rhs, 0)),
11577                                  RECUR (TREE_OPERAND (rhs, 1))));
11578         }
11579       else
11580         incr = RECUR (incr);
11581       break;
11582     default:
11583       incr = RECUR (incr);
11584       break;
11585     }
11586
11587   TREE_VEC_ELT (declv, i) = decl;
11588   TREE_VEC_ELT (initv, i) = init;
11589   TREE_VEC_ELT (condv, i) = cond;
11590   TREE_VEC_ELT (incrv, i) = incr;
11591 #undef RECUR
11592 }
11593
11594 /* Like tsubst_copy for expressions, etc. but also does semantic
11595    processing.  */
11596
11597 static tree
11598 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11599              bool integral_constant_expression_p)
11600 {
11601 #define RECUR(NODE)                             \
11602   tsubst_expr ((NODE), args, complain, in_decl, \
11603                integral_constant_expression_p)
11604
11605   tree stmt, tmp;
11606
11607   if (t == NULL_TREE || t == error_mark_node)
11608     return t;
11609
11610   if (EXPR_HAS_LOCATION (t))
11611     input_location = EXPR_LOCATION (t);
11612   if (STATEMENT_CODE_P (TREE_CODE (t)))
11613     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11614
11615   switch (TREE_CODE (t))
11616     {
11617     case STATEMENT_LIST:
11618       {
11619         tree_stmt_iterator i;
11620         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11621           RECUR (tsi_stmt (i));
11622         break;
11623       }
11624
11625     case CTOR_INITIALIZER:
11626       finish_mem_initializers (tsubst_initializer_list
11627                                (TREE_OPERAND (t, 0), args));
11628       break;
11629
11630     case RETURN_EXPR:
11631       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11632       break;
11633
11634     case EXPR_STMT:
11635       tmp = RECUR (EXPR_STMT_EXPR (t));
11636       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11637         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11638       else
11639         finish_expr_stmt (tmp);
11640       break;
11641
11642     case USING_STMT:
11643       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11644       break;
11645
11646     case DECL_EXPR:
11647       {
11648         tree decl;
11649         tree init;
11650
11651         decl = DECL_EXPR_DECL (t);
11652         if (TREE_CODE (decl) == LABEL_DECL)
11653           finish_label_decl (DECL_NAME (decl));
11654         else if (TREE_CODE (decl) == USING_DECL)
11655           {
11656             tree scope = USING_DECL_SCOPE (decl);
11657             tree name = DECL_NAME (decl);
11658             tree decl;
11659
11660             scope = RECUR (scope);
11661             decl = lookup_qualified_name (scope, name,
11662                                           /*is_type_p=*/false,
11663                                           /*complain=*/false);
11664             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11665               qualified_name_lookup_error (scope, name, decl, input_location);
11666             else
11667               do_local_using_decl (decl, scope, name);
11668           }
11669         else
11670           {
11671             init = DECL_INITIAL (decl);
11672             decl = tsubst (decl, args, complain, in_decl);
11673             if (decl != error_mark_node)
11674               {
11675                 /* By marking the declaration as instantiated, we avoid
11676                    trying to instantiate it.  Since instantiate_decl can't
11677                    handle local variables, and since we've already done
11678                    all that needs to be done, that's the right thing to
11679                    do.  */
11680                 if (TREE_CODE (decl) == VAR_DECL)
11681                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11682                 if (TREE_CODE (decl) == VAR_DECL
11683                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11684                   /* Anonymous aggregates are a special case.  */
11685                   finish_anon_union (decl);
11686                 else
11687                   {
11688                     maybe_push_decl (decl);
11689                     if (TREE_CODE (decl) == VAR_DECL
11690                         && DECL_PRETTY_FUNCTION_P (decl))
11691                       {
11692                         /* For __PRETTY_FUNCTION__ we have to adjust the
11693                            initializer.  */
11694                         const char *const name
11695                           = cxx_printable_name (current_function_decl, 2);
11696                         init = cp_fname_init (name, &TREE_TYPE (decl));
11697                       }
11698                     else
11699                       {
11700                         tree t = RECUR (init);
11701
11702                         if (init && !t)
11703                           {
11704                             /* If we had an initializer but it
11705                                instantiated to nothing,
11706                                value-initialize the object.  This will
11707                                only occur when the initializer was a
11708                                pack expansion where the parameter packs
11709                                used in that expansion were of length
11710                                zero.  */
11711                             init = build_value_init (TREE_TYPE (decl),
11712                                                      complain);
11713                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
11714                               init = get_target_expr (init);
11715                           }
11716                         else
11717                           init = t;
11718                       }
11719
11720                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11721                   }
11722               }
11723           }
11724
11725         /* A DECL_EXPR can also be used as an expression, in the condition
11726            clause of an if/for/while construct.  */
11727         return decl;
11728       }
11729
11730     case FOR_STMT:
11731       stmt = begin_for_stmt ();
11732                           RECUR (FOR_INIT_STMT (t));
11733       finish_for_init_stmt (stmt);
11734       tmp = RECUR (FOR_COND (t));
11735       finish_for_cond (tmp, stmt);
11736       tmp = RECUR (FOR_EXPR (t));
11737       finish_for_expr (tmp, stmt);
11738       RECUR (FOR_BODY (t));
11739       finish_for_stmt (stmt);
11740       break;
11741
11742     case WHILE_STMT:
11743       stmt = begin_while_stmt ();
11744       tmp = RECUR (WHILE_COND (t));
11745       finish_while_stmt_cond (tmp, stmt);
11746       RECUR (WHILE_BODY (t));
11747       finish_while_stmt (stmt);
11748       break;
11749
11750     case DO_STMT:
11751       stmt = begin_do_stmt ();
11752       RECUR (DO_BODY (t));
11753       finish_do_body (stmt);
11754       tmp = RECUR (DO_COND (t));
11755       finish_do_stmt (tmp, stmt);
11756       break;
11757
11758     case IF_STMT:
11759       stmt = begin_if_stmt ();
11760       tmp = RECUR (IF_COND (t));
11761       finish_if_stmt_cond (tmp, stmt);
11762       RECUR (THEN_CLAUSE (t));
11763       finish_then_clause (stmt);
11764
11765       if (ELSE_CLAUSE (t))
11766         {
11767           begin_else_clause (stmt);
11768           RECUR (ELSE_CLAUSE (t));
11769           finish_else_clause (stmt);
11770         }
11771
11772       finish_if_stmt (stmt);
11773       break;
11774
11775     case BIND_EXPR:
11776       if (BIND_EXPR_BODY_BLOCK (t))
11777         stmt = begin_function_body ();
11778       else
11779         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11780                                     ? BCS_TRY_BLOCK : 0);
11781
11782       RECUR (BIND_EXPR_BODY (t));
11783
11784       if (BIND_EXPR_BODY_BLOCK (t))
11785         finish_function_body (stmt);
11786       else
11787         finish_compound_stmt (stmt);
11788       break;
11789
11790     case BREAK_STMT:
11791       finish_break_stmt ();
11792       break;
11793
11794     case CONTINUE_STMT:
11795       finish_continue_stmt ();
11796       break;
11797
11798     case SWITCH_STMT:
11799       stmt = begin_switch_stmt ();
11800       tmp = RECUR (SWITCH_STMT_COND (t));
11801       finish_switch_cond (tmp, stmt);
11802       RECUR (SWITCH_STMT_BODY (t));
11803       finish_switch_stmt (stmt);
11804       break;
11805
11806     case CASE_LABEL_EXPR:
11807       finish_case_label (EXPR_LOCATION (t),
11808                          RECUR (CASE_LOW (t)),
11809                          RECUR (CASE_HIGH (t)));
11810       break;
11811
11812     case LABEL_EXPR:
11813       {
11814         tree decl = LABEL_EXPR_LABEL (t);
11815         tree label;
11816
11817         label = finish_label_stmt (DECL_NAME (decl));
11818         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11819           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11820       }
11821       break;
11822
11823     case GOTO_EXPR:
11824       tmp = GOTO_DESTINATION (t);
11825       if (TREE_CODE (tmp) != LABEL_DECL)
11826         /* Computed goto's must be tsubst'd into.  On the other hand,
11827            non-computed gotos must not be; the identifier in question
11828            will have no binding.  */
11829         tmp = RECUR (tmp);
11830       else
11831         tmp = DECL_NAME (tmp);
11832       finish_goto_stmt (tmp);
11833       break;
11834
11835     case ASM_EXPR:
11836       tmp = finish_asm_stmt
11837         (ASM_VOLATILE_P (t),
11838          RECUR (ASM_STRING (t)),
11839          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11840          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11841          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11842          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11843       {
11844         tree asm_expr = tmp;
11845         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11846           asm_expr = TREE_OPERAND (asm_expr, 0);
11847         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11848       }
11849       break;
11850
11851     case TRY_BLOCK:
11852       if (CLEANUP_P (t))
11853         {
11854           stmt = begin_try_block ();
11855           RECUR (TRY_STMTS (t));
11856           finish_cleanup_try_block (stmt);
11857           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11858         }
11859       else
11860         {
11861           tree compound_stmt = NULL_TREE;
11862
11863           if (FN_TRY_BLOCK_P (t))
11864             stmt = begin_function_try_block (&compound_stmt);
11865           else
11866             stmt = begin_try_block ();
11867
11868           RECUR (TRY_STMTS (t));
11869
11870           if (FN_TRY_BLOCK_P (t))
11871             finish_function_try_block (stmt);
11872           else
11873             finish_try_block (stmt);
11874
11875           RECUR (TRY_HANDLERS (t));
11876           if (FN_TRY_BLOCK_P (t))
11877             finish_function_handler_sequence (stmt, compound_stmt);
11878           else
11879             finish_handler_sequence (stmt);
11880         }
11881       break;
11882
11883     case HANDLER:
11884       {
11885         tree decl = HANDLER_PARMS (t);
11886
11887         if (decl)
11888           {
11889             decl = tsubst (decl, args, complain, in_decl);
11890             /* Prevent instantiate_decl from trying to instantiate
11891                this variable.  We've already done all that needs to be
11892                done.  */
11893             if (decl != error_mark_node)
11894               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11895           }
11896         stmt = begin_handler ();
11897         finish_handler_parms (decl, stmt);
11898         RECUR (HANDLER_BODY (t));
11899         finish_handler (stmt);
11900       }
11901       break;
11902
11903     case TAG_DEFN:
11904       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11905       break;
11906
11907     case STATIC_ASSERT:
11908       {
11909         tree condition = 
11910           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11911                        args,
11912                        complain, in_decl,
11913                        /*integral_constant_expression_p=*/true);
11914         finish_static_assert (condition,
11915                               STATIC_ASSERT_MESSAGE (t),
11916                               STATIC_ASSERT_SOURCE_LOCATION (t),
11917                               /*member_p=*/false);
11918       }
11919       break;
11920
11921     case OMP_PARALLEL:
11922       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11923                                 args, complain, in_decl);
11924       stmt = begin_omp_parallel ();
11925       RECUR (OMP_PARALLEL_BODY (t));
11926       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11927         = OMP_PARALLEL_COMBINED (t);
11928       break;
11929
11930     case OMP_TASK:
11931       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11932                                 args, complain, in_decl);
11933       stmt = begin_omp_task ();
11934       RECUR (OMP_TASK_BODY (t));
11935       finish_omp_task (tmp, stmt);
11936       break;
11937
11938     case OMP_FOR:
11939       {
11940         tree clauses, body, pre_body;
11941         tree declv, initv, condv, incrv;
11942         int i;
11943
11944         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11945                                       args, complain, in_decl);
11946         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11947         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11948         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11949         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11950
11951         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11952           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11953                                    &clauses, args, complain, in_decl,
11954                                    integral_constant_expression_p);
11955
11956         stmt = begin_omp_structured_block ();
11957
11958         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11959           if (TREE_VEC_ELT (initv, i) == NULL
11960               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11961             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11962           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11963             {
11964               tree init = RECUR (TREE_VEC_ELT (initv, i));
11965               gcc_assert (init == TREE_VEC_ELT (declv, i));
11966               TREE_VEC_ELT (initv, i) = NULL_TREE;
11967             }
11968           else
11969             {
11970               tree decl_expr = TREE_VEC_ELT (initv, i);
11971               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11972               gcc_assert (init != NULL);
11973               TREE_VEC_ELT (initv, i) = RECUR (init);
11974               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11975               RECUR (decl_expr);
11976               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11977             }
11978
11979         pre_body = push_stmt_list ();
11980         RECUR (OMP_FOR_PRE_BODY (t));
11981         pre_body = pop_stmt_list (pre_body);
11982
11983         body = push_stmt_list ();
11984         RECUR (OMP_FOR_BODY (t));
11985         body = pop_stmt_list (body);
11986
11987         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11988                             body, pre_body, clauses);
11989
11990         add_stmt (finish_omp_structured_block (stmt));
11991       }
11992       break;
11993
11994     case OMP_SECTIONS:
11995     case OMP_SINGLE:
11996       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11997       stmt = push_stmt_list ();
11998       RECUR (OMP_BODY (t));
11999       stmt = pop_stmt_list (stmt);
12000
12001       t = copy_node (t);
12002       OMP_BODY (t) = stmt;
12003       OMP_CLAUSES (t) = tmp;
12004       add_stmt (t);
12005       break;
12006
12007     case OMP_SECTION:
12008     case OMP_CRITICAL:
12009     case OMP_MASTER:
12010     case OMP_ORDERED:
12011       stmt = push_stmt_list ();
12012       RECUR (OMP_BODY (t));
12013       stmt = pop_stmt_list (stmt);
12014
12015       t = copy_node (t);
12016       OMP_BODY (t) = stmt;
12017       add_stmt (t);
12018       break;
12019
12020     case OMP_ATOMIC:
12021       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12022       {
12023         tree op1 = TREE_OPERAND (t, 1);
12024         tree lhs = RECUR (TREE_OPERAND (op1, 0));
12025         tree rhs = RECUR (TREE_OPERAND (op1, 1));
12026         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
12027       }
12028       break;
12029
12030     case EXPR_PACK_EXPANSION:
12031       error ("invalid use of pack expansion expression");
12032       return error_mark_node;
12033
12034     case NONTYPE_ARGUMENT_PACK:
12035       error ("use %<...%> to expand argument pack");
12036       return error_mark_node;
12037
12038     default:
12039       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12040
12041       return tsubst_copy_and_build (t, args, complain, in_decl,
12042                                     /*function_p=*/false,
12043                                     integral_constant_expression_p);
12044     }
12045
12046   return NULL_TREE;
12047 #undef RECUR
12048 }
12049
12050 /* T is a postfix-expression that is not being used in a function
12051    call.  Return the substituted version of T.  */
12052
12053 static tree
12054 tsubst_non_call_postfix_expression (tree t, tree args,
12055                                     tsubst_flags_t complain,
12056                                     tree in_decl)
12057 {
12058   if (TREE_CODE (t) == SCOPE_REF)
12059     t = tsubst_qualified_id (t, args, complain, in_decl,
12060                              /*done=*/false, /*address_p=*/false);
12061   else
12062     t = tsubst_copy_and_build (t, args, complain, in_decl,
12063                                /*function_p=*/false,
12064                                /*integral_constant_expression_p=*/false);
12065
12066   return t;
12067 }
12068
12069 /* Like tsubst but deals with expressions and performs semantic
12070    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12071
12072 tree
12073 tsubst_copy_and_build (tree t,
12074                        tree args,
12075                        tsubst_flags_t complain,
12076                        tree in_decl,
12077                        bool function_p,
12078                        bool integral_constant_expression_p)
12079 {
12080 #define RECUR(NODE)                                             \
12081   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12082                          /*function_p=*/false,                  \
12083                          integral_constant_expression_p)
12084
12085   tree op1;
12086
12087   if (t == NULL_TREE || t == error_mark_node)
12088     return t;
12089
12090   switch (TREE_CODE (t))
12091     {
12092     case USING_DECL:
12093       t = DECL_NAME (t);
12094       /* Fall through.  */
12095     case IDENTIFIER_NODE:
12096       {
12097         tree decl;
12098         cp_id_kind idk;
12099         bool non_integral_constant_expression_p;
12100         const char *error_msg;
12101
12102         if (IDENTIFIER_TYPENAME_P (t))
12103           {
12104             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12105             t = mangle_conv_op_name_for_type (new_type);
12106           }
12107
12108         /* Look up the name.  */
12109         decl = lookup_name (t);
12110
12111         /* By convention, expressions use ERROR_MARK_NODE to indicate
12112            failure, not NULL_TREE.  */
12113         if (decl == NULL_TREE)
12114           decl = error_mark_node;
12115
12116         decl = finish_id_expression (t, decl, NULL_TREE,
12117                                      &idk,
12118                                      integral_constant_expression_p,
12119                                      /*allow_non_integral_constant_expression_p=*/false,
12120                                      &non_integral_constant_expression_p,
12121                                      /*template_p=*/false,
12122                                      /*done=*/true,
12123                                      /*address_p=*/false,
12124                                      /*template_arg_p=*/false,
12125                                      &error_msg,
12126                                      input_location);
12127         if (error_msg)
12128           error (error_msg);
12129         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12130           decl = unqualified_name_lookup_error (decl);
12131         return decl;
12132       }
12133
12134     case TEMPLATE_ID_EXPR:
12135       {
12136         tree object;
12137         tree templ = RECUR (TREE_OPERAND (t, 0));
12138         tree targs = TREE_OPERAND (t, 1);
12139
12140         if (targs)
12141           targs = tsubst_template_args (targs, args, complain, in_decl);
12142
12143         if (TREE_CODE (templ) == COMPONENT_REF)
12144           {
12145             object = TREE_OPERAND (templ, 0);
12146             templ = TREE_OPERAND (templ, 1);
12147           }
12148         else
12149           object = NULL_TREE;
12150         templ = lookup_template_function (templ, targs);
12151
12152         if (object)
12153           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12154                          object, templ, NULL_TREE);
12155         else
12156           return baselink_for_fns (templ);
12157       }
12158
12159     case INDIRECT_REF:
12160       {
12161         tree r = RECUR (TREE_OPERAND (t, 0));
12162
12163         if (REFERENCE_REF_P (t))
12164           {
12165             /* A type conversion to reference type will be enclosed in
12166                such an indirect ref, but the substitution of the cast
12167                will have also added such an indirect ref.  */
12168             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12169               r = convert_from_reference (r);
12170           }
12171         else
12172           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12173         return r;
12174       }
12175
12176     case NOP_EXPR:
12177       return build_nop
12178         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12179          RECUR (TREE_OPERAND (t, 0)));
12180
12181     case CAST_EXPR:
12182     case REINTERPRET_CAST_EXPR:
12183     case CONST_CAST_EXPR:
12184     case DYNAMIC_CAST_EXPR:
12185     case STATIC_CAST_EXPR:
12186       {
12187         tree type;
12188         tree op;
12189
12190         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12191         if (integral_constant_expression_p
12192             && !cast_valid_in_integral_constant_expression_p (type))
12193           {
12194             if (complain & tf_error)
12195               error ("a cast to a type other than an integral or "
12196                      "enumeration type cannot appear in a constant-expression");
12197             return error_mark_node; 
12198           }
12199
12200         op = RECUR (TREE_OPERAND (t, 0));
12201
12202         switch (TREE_CODE (t))
12203           {
12204           case CAST_EXPR:
12205             return build_functional_cast (type, op, complain);
12206           case REINTERPRET_CAST_EXPR:
12207             return build_reinterpret_cast (type, op, complain);
12208           case CONST_CAST_EXPR:
12209             return build_const_cast (type, op, complain);
12210           case DYNAMIC_CAST_EXPR:
12211             return build_dynamic_cast (type, op, complain);
12212           case STATIC_CAST_EXPR:
12213             return build_static_cast (type, op, complain);
12214           default:
12215             gcc_unreachable ();
12216           }
12217       }
12218
12219     case POSTDECREMENT_EXPR:
12220     case POSTINCREMENT_EXPR:
12221       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12222                                                 args, complain, in_decl);
12223       return build_x_unary_op (TREE_CODE (t), op1, complain);
12224
12225     case PREDECREMENT_EXPR:
12226     case PREINCREMENT_EXPR:
12227     case NEGATE_EXPR:
12228     case BIT_NOT_EXPR:
12229     case ABS_EXPR:
12230     case TRUTH_NOT_EXPR:
12231     case UNARY_PLUS_EXPR:  /* Unary + */
12232     case REALPART_EXPR:
12233     case IMAGPART_EXPR:
12234       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12235                                complain);
12236
12237     case ADDR_EXPR:
12238       op1 = TREE_OPERAND (t, 0);
12239       if (TREE_CODE (op1) == SCOPE_REF)
12240         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12241                                    /*done=*/true, /*address_p=*/true);
12242       else
12243         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12244                                                   in_decl);
12245       if (TREE_CODE (op1) == LABEL_DECL)
12246         return finish_label_address_expr (DECL_NAME (op1),
12247                                           EXPR_LOCATION (op1));
12248       return build_x_unary_op (ADDR_EXPR, op1, complain);
12249
12250     case PLUS_EXPR:
12251     case MINUS_EXPR:
12252     case MULT_EXPR:
12253     case TRUNC_DIV_EXPR:
12254     case CEIL_DIV_EXPR:
12255     case FLOOR_DIV_EXPR:
12256     case ROUND_DIV_EXPR:
12257     case EXACT_DIV_EXPR:
12258     case BIT_AND_EXPR:
12259     case BIT_IOR_EXPR:
12260     case BIT_XOR_EXPR:
12261     case TRUNC_MOD_EXPR:
12262     case FLOOR_MOD_EXPR:
12263     case TRUTH_ANDIF_EXPR:
12264     case TRUTH_ORIF_EXPR:
12265     case TRUTH_AND_EXPR:
12266     case TRUTH_OR_EXPR:
12267     case RSHIFT_EXPR:
12268     case LSHIFT_EXPR:
12269     case RROTATE_EXPR:
12270     case LROTATE_EXPR:
12271     case EQ_EXPR:
12272     case NE_EXPR:
12273     case MAX_EXPR:
12274     case MIN_EXPR:
12275     case LE_EXPR:
12276     case GE_EXPR:
12277     case LT_EXPR:
12278     case GT_EXPR:
12279     case MEMBER_REF:
12280     case DOTSTAR_EXPR:
12281       return build_x_binary_op
12282         (TREE_CODE (t),
12283          RECUR (TREE_OPERAND (t, 0)),
12284          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12285           ? ERROR_MARK
12286           : TREE_CODE (TREE_OPERAND (t, 0))),
12287          RECUR (TREE_OPERAND (t, 1)),
12288          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12289           ? ERROR_MARK
12290           : TREE_CODE (TREE_OPERAND (t, 1))),
12291          /*overloaded_p=*/NULL,
12292          complain);
12293
12294     case SCOPE_REF:
12295       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12296                                   /*address_p=*/false);
12297     case ARRAY_REF:
12298       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12299                                                 args, complain, in_decl);
12300       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12301
12302     case SIZEOF_EXPR:
12303       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12304         return tsubst_copy (t, args, complain, in_decl);
12305       /* Fall through */
12306       
12307     case ALIGNOF_EXPR:
12308       op1 = TREE_OPERAND (t, 0);
12309       if (!args)
12310         {
12311           /* When there are no ARGS, we are trying to evaluate a
12312              non-dependent expression from the parser.  Trying to do
12313              the substitutions may not work.  */
12314           if (!TYPE_P (op1))
12315             op1 = TREE_TYPE (op1);
12316         }
12317       else
12318         {
12319           ++cp_unevaluated_operand;
12320           ++c_inhibit_evaluation_warnings;
12321           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12322                                        /*function_p=*/false,
12323                                        /*integral_constant_expression_p=*/false);
12324           --cp_unevaluated_operand;
12325           --c_inhibit_evaluation_warnings;
12326         }
12327       if (TYPE_P (op1))
12328         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12329                                            complain & tf_error);
12330       else
12331         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12332                                            complain & tf_error);
12333
12334     case NOEXCEPT_EXPR:
12335       op1 = TREE_OPERAND (t, 0);
12336       ++cp_unevaluated_operand;
12337       ++c_inhibit_evaluation_warnings;
12338       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12339                                    /*function_p=*/false,
12340                                    /*integral_constant_expression_p=*/false);
12341       --cp_unevaluated_operand;
12342       --c_inhibit_evaluation_warnings;
12343       return finish_noexcept_expr (op1, complain);
12344
12345     case MODOP_EXPR:
12346       {
12347         tree r = build_x_modify_expr
12348           (RECUR (TREE_OPERAND (t, 0)),
12349            TREE_CODE (TREE_OPERAND (t, 1)),
12350            RECUR (TREE_OPERAND (t, 2)),
12351            complain);
12352         /* TREE_NO_WARNING must be set if either the expression was
12353            parenthesized or it uses an operator such as >>= rather
12354            than plain assignment.  In the former case, it was already
12355            set and must be copied.  In the latter case,
12356            build_x_modify_expr sets it and it must not be reset
12357            here.  */
12358         if (TREE_NO_WARNING (t))
12359           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12360         return r;
12361       }
12362
12363     case ARROW_EXPR:
12364       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12365                                                 args, complain, in_decl);
12366       /* Remember that there was a reference to this entity.  */
12367       if (DECL_P (op1))
12368         mark_used (op1);
12369       return build_x_arrow (op1);
12370
12371     case NEW_EXPR:
12372       {
12373         tree placement = RECUR (TREE_OPERAND (t, 0));
12374         tree init = RECUR (TREE_OPERAND (t, 3));
12375         VEC(tree,gc) *placement_vec;
12376         VEC(tree,gc) *init_vec;
12377         tree ret;
12378
12379         if (placement == NULL_TREE)
12380           placement_vec = NULL;
12381         else
12382           {
12383             placement_vec = make_tree_vector ();
12384             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12385               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12386           }
12387
12388         /* If there was an initializer in the original tree, but it
12389            instantiated to an empty list, then we should pass a
12390            non-NULL empty vector to tell build_new that it was an
12391            empty initializer() rather than no initializer.  This can
12392            only happen when the initializer is a pack expansion whose
12393            parameter packs are of length zero.  */
12394         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12395           init_vec = NULL;
12396         else
12397           {
12398             init_vec = make_tree_vector ();
12399             if (init == void_zero_node)
12400               gcc_assert (init_vec != NULL);
12401             else
12402               {
12403                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12404                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12405               }
12406           }
12407
12408         ret = build_new (&placement_vec,
12409                          RECUR (TREE_OPERAND (t, 1)),
12410                          RECUR (TREE_OPERAND (t, 2)),
12411                          &init_vec,
12412                          NEW_EXPR_USE_GLOBAL (t),
12413                          complain);
12414
12415         if (placement_vec != NULL)
12416           release_tree_vector (placement_vec);
12417         if (init_vec != NULL)
12418           release_tree_vector (init_vec);
12419
12420         return ret;
12421       }
12422
12423     case DELETE_EXPR:
12424      return delete_sanity
12425        (RECUR (TREE_OPERAND (t, 0)),
12426         RECUR (TREE_OPERAND (t, 1)),
12427         DELETE_EXPR_USE_VEC (t),
12428         DELETE_EXPR_USE_GLOBAL (t));
12429
12430     case COMPOUND_EXPR:
12431       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12432                                     RECUR (TREE_OPERAND (t, 1)),
12433                                     complain);
12434
12435     case CALL_EXPR:
12436       {
12437         tree function;
12438         VEC(tree,gc) *call_args;
12439         unsigned int nargs, i;
12440         bool qualified_p;
12441         bool koenig_p;
12442         tree ret;
12443
12444         function = CALL_EXPR_FN (t);
12445         /* When we parsed the expression,  we determined whether or
12446            not Koenig lookup should be performed.  */
12447         koenig_p = KOENIG_LOOKUP_P (t);
12448         if (TREE_CODE (function) == SCOPE_REF)
12449           {
12450             qualified_p = true;
12451             function = tsubst_qualified_id (function, args, complain, in_decl,
12452                                             /*done=*/false,
12453                                             /*address_p=*/false);
12454           }
12455         else
12456           {
12457             if (TREE_CODE (function) == COMPONENT_REF)
12458               {
12459                 tree op = TREE_OPERAND (function, 1);
12460
12461                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12462                                || (BASELINK_P (op)
12463                                    && BASELINK_QUALIFIED_P (op)));
12464               }
12465             else
12466               qualified_p = false;
12467
12468             function = tsubst_copy_and_build (function, args, complain,
12469                                               in_decl,
12470                                               !qualified_p,
12471                                               integral_constant_expression_p);
12472
12473             if (BASELINK_P (function))
12474               qualified_p = true;
12475           }
12476
12477         nargs = call_expr_nargs (t);
12478         call_args = make_tree_vector ();
12479         for (i = 0; i < nargs; ++i)
12480           {
12481             tree arg = CALL_EXPR_ARG (t, i);
12482
12483             if (!PACK_EXPANSION_P (arg))
12484               VEC_safe_push (tree, gc, call_args,
12485                              RECUR (CALL_EXPR_ARG (t, i)));
12486             else
12487               {
12488                 /* Expand the pack expansion and push each entry onto
12489                    CALL_ARGS.  */
12490                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12491                 if (TREE_CODE (arg) == TREE_VEC)
12492                   {
12493                     unsigned int len, j;
12494
12495                     len = TREE_VEC_LENGTH (arg);
12496                     for (j = 0; j < len; ++j)
12497                       {
12498                         tree value = TREE_VEC_ELT (arg, j);
12499                         if (value != NULL_TREE)
12500                           value = convert_from_reference (value);
12501                         VEC_safe_push (tree, gc, call_args, value);
12502                       }
12503                   }
12504                 else
12505                   {
12506                     /* A partial substitution.  Add one entry.  */
12507                     VEC_safe_push (tree, gc, call_args, arg);
12508                   }
12509               }
12510           }
12511
12512         /* We do not perform argument-dependent lookup if normal
12513            lookup finds a non-function, in accordance with the
12514            expected resolution of DR 218.  */
12515         if (koenig_p
12516             && ((is_overloaded_fn (function)
12517                  /* If lookup found a member function, the Koenig lookup is
12518                     not appropriate, even if an unqualified-name was used
12519                     to denote the function.  */
12520                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12521                 || TREE_CODE (function) == IDENTIFIER_NODE)
12522             /* Only do this when substitution turns a dependent call
12523                into a non-dependent call.  */
12524             && type_dependent_expression_p_push (t)
12525             && !any_type_dependent_arguments_p (call_args))
12526           function = perform_koenig_lookup (function, call_args);
12527
12528         if (TREE_CODE (function) == IDENTIFIER_NODE)
12529           {
12530             unqualified_name_lookup_error (function);
12531             release_tree_vector (call_args);
12532             return error_mark_node;
12533           }
12534
12535         /* Remember that there was a reference to this entity.  */
12536         if (DECL_P (function))
12537           mark_used (function);
12538
12539         if (TREE_CODE (function) == OFFSET_REF)
12540           ret = build_offset_ref_call_from_tree (function, &call_args);
12541         else if (TREE_CODE (function) == COMPONENT_REF)
12542           {
12543             tree instance = TREE_OPERAND (function, 0);
12544             tree fn = TREE_OPERAND (function, 1);
12545
12546             if (processing_template_decl
12547                 && (type_dependent_expression_p (instance)
12548                     || (!BASELINK_P (fn)
12549                         && TREE_CODE (fn) != FIELD_DECL)
12550                     || type_dependent_expression_p (fn)
12551                     || any_type_dependent_arguments_p (call_args)))
12552               ret = build_nt_call_vec (function, call_args);
12553             else if (!BASELINK_P (fn))
12554               ret = finish_call_expr (function, &call_args,
12555                                        /*disallow_virtual=*/false,
12556                                        /*koenig_p=*/false,
12557                                        complain);
12558             else
12559               ret = (build_new_method_call
12560                       (instance, fn,
12561                        &call_args, NULL_TREE,
12562                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12563                        /*fn_p=*/NULL,
12564                        complain));
12565           }
12566         else
12567           ret = finish_call_expr (function, &call_args,
12568                                   /*disallow_virtual=*/qualified_p,
12569                                   koenig_p,
12570                                   complain);
12571
12572         release_tree_vector (call_args);
12573
12574         return ret;
12575       }
12576
12577     case COND_EXPR:
12578       return build_x_conditional_expr
12579         (RECUR (TREE_OPERAND (t, 0)),
12580          RECUR (TREE_OPERAND (t, 1)),
12581          RECUR (TREE_OPERAND (t, 2)),
12582          complain);
12583
12584     case PSEUDO_DTOR_EXPR:
12585       return finish_pseudo_destructor_expr
12586         (RECUR (TREE_OPERAND (t, 0)),
12587          RECUR (TREE_OPERAND (t, 1)),
12588          RECUR (TREE_OPERAND (t, 2)));
12589
12590     case TREE_LIST:
12591       {
12592         tree purpose, value, chain;
12593
12594         if (t == void_list_node)
12595           return t;
12596
12597         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12598             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12599           {
12600             /* We have pack expansions, so expand those and
12601                create a new list out of it.  */
12602             tree purposevec = NULL_TREE;
12603             tree valuevec = NULL_TREE;
12604             tree chain;
12605             int i, len = -1;
12606
12607             /* Expand the argument expressions.  */
12608             if (TREE_PURPOSE (t))
12609               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12610                                                  complain, in_decl);
12611             if (TREE_VALUE (t))
12612               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12613                                                complain, in_decl);
12614
12615             /* Build the rest of the list.  */
12616             chain = TREE_CHAIN (t);
12617             if (chain && chain != void_type_node)
12618               chain = RECUR (chain);
12619
12620             /* Determine the number of arguments.  */
12621             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12622               {
12623                 len = TREE_VEC_LENGTH (purposevec);
12624                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12625               }
12626             else if (TREE_CODE (valuevec) == TREE_VEC)
12627               len = TREE_VEC_LENGTH (valuevec);
12628             else
12629               {
12630                 /* Since we only performed a partial substitution into
12631                    the argument pack, we only return a single list
12632                    node.  */
12633                 if (purposevec == TREE_PURPOSE (t)
12634                     && valuevec == TREE_VALUE (t)
12635                     && chain == TREE_CHAIN (t))
12636                   return t;
12637
12638                 return tree_cons (purposevec, valuevec, chain);
12639               }
12640             
12641             /* Convert the argument vectors into a TREE_LIST */
12642             i = len;
12643             while (i > 0)
12644               {
12645                 /* Grab the Ith values.  */
12646                 i--;
12647                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12648                                      : NULL_TREE;
12649                 value 
12650                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12651                              : NULL_TREE;
12652
12653                 /* Build the list (backwards).  */
12654                 chain = tree_cons (purpose, value, chain);
12655               }
12656
12657             return chain;
12658           }
12659
12660         purpose = TREE_PURPOSE (t);
12661         if (purpose)
12662           purpose = RECUR (purpose);
12663         value = TREE_VALUE (t);
12664         if (value)
12665           value = RECUR (value);
12666         chain = TREE_CHAIN (t);
12667         if (chain && chain != void_type_node)
12668           chain = RECUR (chain);
12669         if (purpose == TREE_PURPOSE (t)
12670             && value == TREE_VALUE (t)
12671             && chain == TREE_CHAIN (t))
12672           return t;
12673         return tree_cons (purpose, value, chain);
12674       }
12675
12676     case COMPONENT_REF:
12677       {
12678         tree object;
12679         tree object_type;
12680         tree member;
12681
12682         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12683                                                      args, complain, in_decl);
12684         /* Remember that there was a reference to this entity.  */
12685         if (DECL_P (object))
12686           mark_used (object);
12687         object_type = TREE_TYPE (object);
12688
12689         member = TREE_OPERAND (t, 1);
12690         if (BASELINK_P (member))
12691           member = tsubst_baselink (member,
12692                                     non_reference (TREE_TYPE (object)),
12693                                     args, complain, in_decl);
12694         else
12695           member = tsubst_copy (member, args, complain, in_decl);
12696         if (member == error_mark_node)
12697           return error_mark_node;
12698
12699         if (object_type && !CLASS_TYPE_P (object_type))
12700           {
12701             if (SCALAR_TYPE_P (object_type))
12702               {
12703                 tree s = NULL_TREE;
12704                 tree dtor = member;
12705
12706                 if (TREE_CODE (dtor) == SCOPE_REF)
12707                   {
12708                     s = TREE_OPERAND (dtor, 0);
12709                     dtor = TREE_OPERAND (dtor, 1);
12710                   }
12711                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12712                   {
12713                     dtor = TREE_OPERAND (dtor, 0);
12714                     if (TYPE_P (dtor))
12715                       return finish_pseudo_destructor_expr (object, s, dtor);
12716                   }
12717               }
12718           }
12719         else if (TREE_CODE (member) == SCOPE_REF
12720                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12721           {
12722             tree tmpl;
12723             tree args;
12724
12725             /* Lookup the template functions now that we know what the
12726                scope is.  */
12727             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12728             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12729             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12730                                             /*is_type_p=*/false,
12731                                             /*complain=*/false);
12732             if (BASELINK_P (member))
12733               {
12734                 BASELINK_FUNCTIONS (member)
12735                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12736                               args);
12737                 member = (adjust_result_of_qualified_name_lookup
12738                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12739                            object_type));
12740               }
12741             else
12742               {
12743                 qualified_name_lookup_error (object_type, tmpl, member,
12744                                              input_location);
12745                 return error_mark_node;
12746               }
12747           }
12748         else if (TREE_CODE (member) == SCOPE_REF
12749                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12750                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12751           {
12752             if (complain & tf_error)
12753               {
12754                 if (TYPE_P (TREE_OPERAND (member, 0)))
12755                   error ("%qT is not a class or namespace",
12756                          TREE_OPERAND (member, 0));
12757                 else
12758                   error ("%qD is not a class or namespace",
12759                          TREE_OPERAND (member, 0));
12760               }
12761             return error_mark_node;
12762           }
12763         else if (TREE_CODE (member) == FIELD_DECL)
12764           return finish_non_static_data_member (member, object, NULL_TREE);
12765
12766         return finish_class_member_access_expr (object, member,
12767                                                 /*template_p=*/false,
12768                                                 complain);
12769       }
12770
12771     case THROW_EXPR:
12772       return build_throw
12773         (RECUR (TREE_OPERAND (t, 0)));
12774
12775     case CONSTRUCTOR:
12776       {
12777         VEC(constructor_elt,gc) *n;
12778         constructor_elt *ce;
12779         unsigned HOST_WIDE_INT idx;
12780         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12781         bool process_index_p;
12782         int newlen;
12783         bool need_copy_p = false;
12784         tree r;
12785
12786         if (type == error_mark_node)
12787           return error_mark_node;
12788
12789         /* digest_init will do the wrong thing if we let it.  */
12790         if (type && TYPE_PTRMEMFUNC_P (type))
12791           return t;
12792
12793         /* We do not want to process the index of aggregate
12794            initializers as they are identifier nodes which will be
12795            looked up by digest_init.  */
12796         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12797
12798         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12799         newlen = VEC_length (constructor_elt, n);
12800         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
12801           {
12802             if (ce->index && process_index_p)
12803               ce->index = RECUR (ce->index);
12804
12805             if (PACK_EXPANSION_P (ce->value))
12806               {
12807                 /* Substitute into the pack expansion.  */
12808                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12809                                                   in_decl);
12810
12811                 if (ce->value == error_mark_node)
12812                   ;
12813                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12814                   /* Just move the argument into place.  */
12815                   ce->value = TREE_VEC_ELT (ce->value, 0);
12816                 else
12817                   {
12818                     /* Update the length of the final CONSTRUCTOR
12819                        arguments vector, and note that we will need to
12820                        copy.*/
12821                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12822                     need_copy_p = true;
12823                   }
12824               }
12825             else
12826               ce->value = RECUR (ce->value);
12827           }
12828
12829         if (need_copy_p)
12830           {
12831             VEC(constructor_elt,gc) *old_n = n;
12832
12833             n = VEC_alloc (constructor_elt, gc, newlen);
12834             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
12835               {
12836                 if (TREE_CODE (ce->value) == TREE_VEC)
12837                   {
12838                     int i, len = TREE_VEC_LENGTH (ce->value);
12839                     for (i = 0; i < len; ++i)
12840                       CONSTRUCTOR_APPEND_ELT (n, 0,
12841                                               TREE_VEC_ELT (ce->value, i));
12842                   }
12843                 else
12844                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12845               }
12846           }
12847
12848         r = build_constructor (init_list_type_node, n);
12849         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12850
12851         if (TREE_HAS_CONSTRUCTOR (t))
12852           return finish_compound_literal (type, r);
12853
12854         return r;
12855       }
12856
12857     case TYPEID_EXPR:
12858       {
12859         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12860         if (TYPE_P (operand_0))
12861           return get_typeid (operand_0);
12862         return build_typeid (operand_0);
12863       }
12864
12865     case VAR_DECL:
12866       if (!args)
12867         return t;
12868       /* Fall through */
12869
12870     case PARM_DECL:
12871       {
12872         tree r = tsubst_copy (t, args, complain, in_decl);
12873
12874         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12875           /* If the original type was a reference, we'll be wrapped in
12876              the appropriate INDIRECT_REF.  */
12877           r = convert_from_reference (r);
12878         return r;
12879       }
12880
12881     case VA_ARG_EXPR:
12882       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12883                              tsubst_copy (TREE_TYPE (t), args, complain,
12884                                           in_decl));
12885
12886     case OFFSETOF_EXPR:
12887       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12888
12889     case TRAIT_EXPR:
12890       {
12891         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12892                                   complain, in_decl);
12893
12894         tree type2 = TRAIT_EXPR_TYPE2 (t);
12895         if (type2)
12896           type2 = tsubst_copy (type2, args, complain, in_decl);
12897         
12898         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12899       }
12900
12901     case STMT_EXPR:
12902       {
12903         tree old_stmt_expr = cur_stmt_expr;
12904         tree stmt_expr = begin_stmt_expr ();
12905
12906         cur_stmt_expr = stmt_expr;
12907         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12908                      integral_constant_expression_p);
12909         stmt_expr = finish_stmt_expr (stmt_expr, false);
12910         cur_stmt_expr = old_stmt_expr;
12911
12912         /* If the resulting list of expression statement is empty,
12913            fold it further into void_zero_node.  */
12914         if (empty_expr_stmt_p (stmt_expr))
12915           stmt_expr = void_zero_node;
12916
12917         return stmt_expr;
12918       }
12919
12920     case CONST_DECL:
12921       t = tsubst_copy (t, args, complain, in_decl);
12922       /* As in finish_id_expression, we resolve enumeration constants
12923          to their underlying values.  */
12924       if (TREE_CODE (t) == CONST_DECL)
12925         {
12926           used_types_insert (TREE_TYPE (t));
12927           return DECL_INITIAL (t);
12928         }
12929       return t;
12930
12931     case LAMBDA_EXPR:
12932       {
12933         tree r = build_lambda_expr ();
12934
12935         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12936         TREE_TYPE (r) = type;
12937         CLASSTYPE_LAMBDA_EXPR (type) = r;
12938
12939         LAMBDA_EXPR_LOCATION (r)
12940           = LAMBDA_EXPR_LOCATION (t);
12941         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12942           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12943         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12944         LAMBDA_EXPR_DISCRIMINATOR (r)
12945           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12946         LAMBDA_EXPR_CAPTURE_LIST (r)
12947           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12948         LAMBDA_EXPR_THIS_CAPTURE (r)
12949           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12950         LAMBDA_EXPR_EXTRA_SCOPE (r)
12951           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12952
12953         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12954         determine_visibility (TYPE_NAME (type));
12955         /* Now that we know visibility, instantiate the type so we have a
12956            declaration of the op() for later calls to lambda_function.  */
12957         complete_type (type);
12958
12959         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12960         if (type)
12961           apply_lambda_return_type (r, type);
12962
12963         return build_lambda_object (r);
12964       }
12965
12966     default:
12967       /* Handle Objective-C++ constructs, if appropriate.  */
12968       {
12969         tree subst
12970           = objcp_tsubst_copy_and_build (t, args, complain,
12971                                          in_decl, /*function_p=*/false);
12972         if (subst)
12973           return subst;
12974       }
12975       return tsubst_copy (t, args, complain, in_decl);
12976     }
12977
12978 #undef RECUR
12979 }
12980
12981 /* Verify that the instantiated ARGS are valid. For type arguments,
12982    make sure that the type's linkage is ok. For non-type arguments,
12983    make sure they are constants if they are integral or enumerations.
12984    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12985
12986 static bool
12987 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12988 {
12989   if (ARGUMENT_PACK_P (t))
12990     {
12991       tree vec = ARGUMENT_PACK_ARGS (t);
12992       int len = TREE_VEC_LENGTH (vec);
12993       bool result = false;
12994       int i;
12995
12996       for (i = 0; i < len; ++i)
12997         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12998           result = true;
12999       return result;
13000     }
13001   else if (TYPE_P (t))
13002     {
13003       /* [basic.link]: A name with no linkage (notably, the name
13004          of a class or enumeration declared in a local scope)
13005          shall not be used to declare an entity with linkage.
13006          This implies that names with no linkage cannot be used as
13007          template arguments
13008
13009          DR 757 relaxes this restriction for C++0x.  */
13010       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
13011                  : no_linkage_check (t, /*relaxed_p=*/false));
13012
13013       if (nt)
13014         {
13015           /* DR 488 makes use of a type with no linkage cause
13016              type deduction to fail.  */
13017           if (complain & tf_error)
13018             {
13019               if (TYPE_ANONYMOUS_P (nt))
13020                 error ("%qT is/uses anonymous type", t);
13021               else
13022                 error ("template argument for %qD uses local type %qT",
13023                        tmpl, t);
13024             }
13025           return true;
13026         }
13027       /* In order to avoid all sorts of complications, we do not
13028          allow variably-modified types as template arguments.  */
13029       else if (variably_modified_type_p (t, NULL_TREE))
13030         {
13031           if (complain & tf_error)
13032             error ("%qT is a variably modified type", t);
13033           return true;
13034         }
13035     }
13036   /* A non-type argument of integral or enumerated type must be a
13037      constant.  */
13038   else if (TREE_TYPE (t)
13039            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
13040            && !TREE_CONSTANT (t))
13041     {
13042       if (complain & tf_error)
13043         error ("integral expression %qE is not constant", t);
13044       return true;
13045     }
13046   return false;
13047 }
13048
13049 static bool
13050 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
13051 {
13052   int ix, len = DECL_NTPARMS (tmpl);
13053   bool result = false;
13054
13055   for (ix = 0; ix != len; ix++)
13056     {
13057       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
13058         result = true;
13059     }
13060   if (result && (complain & tf_error))
13061     error ("  trying to instantiate %qD", tmpl);
13062   return result;
13063 }
13064
13065 /* Instantiate the indicated variable or function template TMPL with
13066    the template arguments in TARG_PTR.  */
13067
13068 tree
13069 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
13070 {
13071   tree targ_ptr = orig_args;
13072   tree fndecl;
13073   tree gen_tmpl;
13074   tree spec;
13075   HOST_WIDE_INT saved_processing_template_decl;
13076
13077   if (tmpl == error_mark_node)
13078     return error_mark_node;
13079
13080   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
13081
13082   /* If this function is a clone, handle it specially.  */
13083   if (DECL_CLONED_FUNCTION_P (tmpl))
13084     {
13085       tree spec;
13086       tree clone;
13087
13088       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
13089          DECL_CLONED_FUNCTION.  */
13090       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
13091                                    targ_ptr, complain);
13092       if (spec == error_mark_node)
13093         return error_mark_node;
13094
13095       /* Look for the clone.  */
13096       FOR_EACH_CLONE (clone, spec)
13097         if (DECL_NAME (clone) == DECL_NAME (tmpl))
13098           return clone;
13099       /* We should always have found the clone by now.  */
13100       gcc_unreachable ();
13101       return NULL_TREE;
13102     }
13103
13104   /* Check to see if we already have this specialization.  */
13105   gen_tmpl = most_general_template (tmpl);
13106   if (tmpl != gen_tmpl)
13107     /* The TMPL is a partial instantiation.  To get a full set of
13108        arguments we must add the arguments used to perform the
13109        partial instantiation.  */
13110     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13111                                             targ_ptr);
13112
13113   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13114      but it doesn't seem to be on the hot path.  */
13115   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13116
13117   gcc_assert (tmpl == gen_tmpl
13118               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13119                   == spec)
13120               || fndecl == NULL_TREE);
13121
13122   if (spec != NULL_TREE)
13123     return spec;
13124
13125   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13126                                complain))
13127     return error_mark_node;
13128
13129   /* We are building a FUNCTION_DECL, during which the access of its
13130      parameters and return types have to be checked.  However this
13131      FUNCTION_DECL which is the desired context for access checking
13132      is not built yet.  We solve this chicken-and-egg problem by
13133      deferring all checks until we have the FUNCTION_DECL.  */
13134   push_deferring_access_checks (dk_deferred);
13135
13136   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13137      (because, for example, we have encountered a non-dependent
13138      function call in the body of a template function and must now
13139      determine which of several overloaded functions will be called),
13140      within the instantiation itself we are not processing a
13141      template.  */  
13142   saved_processing_template_decl = processing_template_decl;
13143   processing_template_decl = 0;
13144   /* Substitute template parameters to obtain the specialization.  */
13145   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13146                    targ_ptr, complain, gen_tmpl);
13147   processing_template_decl = saved_processing_template_decl;
13148   if (fndecl == error_mark_node)
13149     return error_mark_node;
13150
13151   /* Now we know the specialization, compute access previously
13152      deferred.  */
13153   push_access_scope (fndecl);
13154
13155   /* Some typedefs referenced from within the template code need to be access
13156      checked at template instantiation time, i.e now. These types were
13157      added to the template at parsing time. Let's get those and perfom
13158      the acces checks then.  */
13159   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13160   perform_deferred_access_checks ();
13161   pop_access_scope (fndecl);
13162   pop_deferring_access_checks ();
13163
13164   /* The DECL_TI_TEMPLATE should always be the immediate parent
13165      template, not the most general template.  */
13166   DECL_TI_TEMPLATE (fndecl) = tmpl;
13167
13168   /* If we've just instantiated the main entry point for a function,
13169      instantiate all the alternate entry points as well.  We do this
13170      by cloning the instantiation of the main entry point, not by
13171      instantiating the template clones.  */
13172   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
13173     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13174
13175   return fndecl;
13176 }
13177
13178 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13179    NARGS elements of the arguments that are being used when calling
13180    it.  TARGS is a vector into which the deduced template arguments
13181    are placed.
13182
13183    Return zero for success, 2 for an incomplete match that doesn't resolve
13184    all the types, and 1 for complete failure.  An error message will be
13185    printed only for an incomplete match.
13186
13187    If FN is a conversion operator, or we are trying to produce a specific
13188    specialization, RETURN_TYPE is the return type desired.
13189
13190    The EXPLICIT_TARGS are explicit template arguments provided via a
13191    template-id.
13192
13193    The parameter STRICT is one of:
13194
13195    DEDUCE_CALL:
13196      We are deducing arguments for a function call, as in
13197      [temp.deduct.call].
13198
13199    DEDUCE_CONV:
13200      We are deducing arguments for a conversion function, as in
13201      [temp.deduct.conv].
13202
13203    DEDUCE_EXACT:
13204      We are deducing arguments when doing an explicit instantiation
13205      as in [temp.explicit], when determining an explicit specialization
13206      as in [temp.expl.spec], or when taking the address of a function
13207      template, as in [temp.deduct.funcaddr].  */
13208
13209 int
13210 fn_type_unification (tree fn,
13211                      tree explicit_targs,
13212                      tree targs,
13213                      const tree *args,
13214                      unsigned int nargs,
13215                      tree return_type,
13216                      unification_kind_t strict,
13217                      int flags)
13218 {
13219   tree parms;
13220   tree fntype;
13221   int result;
13222   bool incomplete_argument_packs_p = false;
13223
13224   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13225
13226   fntype = TREE_TYPE (fn);
13227   if (explicit_targs)
13228     {
13229       /* [temp.deduct]
13230
13231          The specified template arguments must match the template
13232          parameters in kind (i.e., type, nontype, template), and there
13233          must not be more arguments than there are parameters;
13234          otherwise type deduction fails.
13235
13236          Nontype arguments must match the types of the corresponding
13237          nontype template parameters, or must be convertible to the
13238          types of the corresponding nontype parameters as specified in
13239          _temp.arg.nontype_, otherwise type deduction fails.
13240
13241          All references in the function type of the function template
13242          to the corresponding template parameters are replaced by the
13243          specified template argument values.  If a substitution in a
13244          template parameter or in the function type of the function
13245          template results in an invalid type, type deduction fails.  */
13246       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13247       int i, len = TREE_VEC_LENGTH (tparms);
13248       tree converted_args;
13249       bool incomplete = false;
13250
13251       if (explicit_targs == error_mark_node)
13252         return 1;
13253
13254       converted_args
13255         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13256                                   /*require_all_args=*/false,
13257                                   /*use_default_args=*/false));
13258       if (converted_args == error_mark_node)
13259         return 1;
13260
13261       /* Substitute the explicit args into the function type.  This is
13262          necessary so that, for instance, explicitly declared function
13263          arguments can match null pointed constants.  If we were given
13264          an incomplete set of explicit args, we must not do semantic
13265          processing during substitution as we could create partial
13266          instantiations.  */
13267       for (i = 0; i < len; i++)
13268         {
13269           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13270           bool parameter_pack = false;
13271
13272           /* Dig out the actual parm.  */
13273           if (TREE_CODE (parm) == TYPE_DECL
13274               || TREE_CODE (parm) == TEMPLATE_DECL)
13275             {
13276               parm = TREE_TYPE (parm);
13277               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13278             }
13279           else if (TREE_CODE (parm) == PARM_DECL)
13280             {
13281               parm = DECL_INITIAL (parm);
13282               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13283             }
13284
13285           if (parameter_pack)
13286             {
13287               int level, idx;
13288               tree targ;
13289               template_parm_level_and_index (parm, &level, &idx);
13290
13291               /* Mark the argument pack as "incomplete". We could
13292                  still deduce more arguments during unification.  */
13293               targ = TMPL_ARG (converted_args, level, idx);
13294               if (targ)
13295                 {
13296                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13297                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13298                     = ARGUMENT_PACK_ARGS (targ);
13299                 }
13300
13301               /* We have some incomplete argument packs.  */
13302               incomplete_argument_packs_p = true;
13303             }
13304         }
13305
13306       if (incomplete_argument_packs_p)
13307         /* Any substitution is guaranteed to be incomplete if there
13308            are incomplete argument packs, because we can still deduce
13309            more arguments.  */
13310         incomplete = 1;
13311       else
13312         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13313
13314       processing_template_decl += incomplete;
13315       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13316       processing_template_decl -= incomplete;
13317
13318       if (fntype == error_mark_node)
13319         return 1;
13320
13321       /* Place the explicitly specified arguments in TARGS.  */
13322       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13323         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13324     }
13325
13326   /* Never do unification on the 'this' parameter.  */
13327   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13328
13329   if (return_type)
13330     {
13331       tree *new_args;
13332
13333       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13334       new_args = XALLOCAVEC (tree, nargs + 1);
13335       new_args[0] = return_type;
13336       memcpy (new_args + 1, args, nargs * sizeof (tree));
13337       args = new_args;
13338       ++nargs;
13339     }
13340
13341   /* We allow incomplete unification without an error message here
13342      because the standard doesn't seem to explicitly prohibit it.  Our
13343      callers must be ready to deal with unification failures in any
13344      event.  */
13345   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13346                                   targs, parms, args, nargs, /*subr=*/0,
13347                                   strict, flags);
13348
13349   if (result == 0 && incomplete_argument_packs_p)
13350     {
13351       int i, len = NUM_TMPL_ARGS (targs);
13352
13353       /* Clear the "incomplete" flags on all argument packs.  */
13354       for (i = 0; i < len; i++)
13355         {
13356           tree arg = TREE_VEC_ELT (targs, i);
13357           if (ARGUMENT_PACK_P (arg))
13358             {
13359               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13360               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13361             }
13362         }
13363     }
13364
13365   /* Now that we have bindings for all of the template arguments,
13366      ensure that the arguments deduced for the template template
13367      parameters have compatible template parameter lists.  We cannot
13368      check this property before we have deduced all template
13369      arguments, because the template parameter types of a template
13370      template parameter might depend on prior template parameters
13371      deduced after the template template parameter.  The following
13372      ill-formed example illustrates this issue:
13373
13374        template<typename T, template<T> class C> void f(C<5>, T);
13375
13376        template<int N> struct X {};
13377
13378        void g() {
13379          f(X<5>(), 5l); // error: template argument deduction fails
13380        }
13381
13382      The template parameter list of 'C' depends on the template type
13383      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13384      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13385      time that we deduce 'C'.  */
13386   if (result == 0
13387       && !template_template_parm_bindings_ok_p 
13388            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13389     return 1;
13390
13391   if (result == 0)
13392     /* All is well so far.  Now, check:
13393
13394        [temp.deduct]
13395
13396        When all template arguments have been deduced, all uses of
13397        template parameters in nondeduced contexts are replaced with
13398        the corresponding deduced argument values.  If the
13399        substitution results in an invalid type, as described above,
13400        type deduction fails.  */
13401     {
13402       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13403       if (substed == error_mark_node)
13404         return 1;
13405
13406       /* If we're looking for an exact match, check that what we got
13407          is indeed an exact match.  It might not be if some template
13408          parameters are used in non-deduced contexts.  */
13409       if (strict == DEDUCE_EXACT)
13410         {
13411           unsigned int i;
13412
13413           tree sarg
13414             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13415           if (return_type)
13416             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13417           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13418             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13419               return 1;
13420         }
13421     }
13422
13423   return result;
13424 }
13425
13426 /* Adjust types before performing type deduction, as described in
13427    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13428    sections are symmetric.  PARM is the type of a function parameter
13429    or the return type of the conversion function.  ARG is the type of
13430    the argument passed to the call, or the type of the value
13431    initialized with the result of the conversion function.
13432    ARG_EXPR is the original argument expression, which may be null.  */
13433
13434 static int
13435 maybe_adjust_types_for_deduction (unification_kind_t strict,
13436                                   tree* parm,
13437                                   tree* arg,
13438                                   tree arg_expr)
13439 {
13440   int result = 0;
13441
13442   switch (strict)
13443     {
13444     case DEDUCE_CALL:
13445       break;
13446
13447     case DEDUCE_CONV:
13448       {
13449         /* Swap PARM and ARG throughout the remainder of this
13450            function; the handling is precisely symmetric since PARM
13451            will initialize ARG rather than vice versa.  */
13452         tree* temp = parm;
13453         parm = arg;
13454         arg = temp;
13455         break;
13456       }
13457
13458     case DEDUCE_EXACT:
13459       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13460          too, but here handle it by stripping the reference from PARM
13461          rather than by adding it to ARG.  */
13462       if (TREE_CODE (*parm) == REFERENCE_TYPE
13463           && TYPE_REF_IS_RVALUE (*parm)
13464           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13465           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13466           && TREE_CODE (*arg) == REFERENCE_TYPE
13467           && !TYPE_REF_IS_RVALUE (*arg))
13468         *parm = TREE_TYPE (*parm);
13469       /* Nothing else to do in this case.  */
13470       return 0;
13471
13472     default:
13473       gcc_unreachable ();
13474     }
13475
13476   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13477     {
13478       /* [temp.deduct.call]
13479
13480          If P is not a reference type:
13481
13482          --If A is an array type, the pointer type produced by the
13483          array-to-pointer standard conversion (_conv.array_) is
13484          used in place of A for type deduction; otherwise,
13485
13486          --If A is a function type, the pointer type produced by
13487          the function-to-pointer standard conversion
13488          (_conv.func_) is used in place of A for type deduction;
13489          otherwise,
13490
13491          --If A is a cv-qualified type, the top level
13492          cv-qualifiers of A's type are ignored for type
13493          deduction.  */
13494       if (TREE_CODE (*arg) == ARRAY_TYPE)
13495         *arg = build_pointer_type (TREE_TYPE (*arg));
13496       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13497         *arg = build_pointer_type (*arg);
13498       else
13499         *arg = TYPE_MAIN_VARIANT (*arg);
13500     }
13501
13502   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13503      of the form T&&, where T is a template parameter, and the argument
13504      is an lvalue, T is deduced as A& */
13505   if (TREE_CODE (*parm) == REFERENCE_TYPE
13506       && TYPE_REF_IS_RVALUE (*parm)
13507       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13508       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13509       && arg_expr && real_lvalue_p (arg_expr))
13510     *arg = build_reference_type (*arg);
13511
13512   /* [temp.deduct.call]
13513
13514      If P is a cv-qualified type, the top level cv-qualifiers
13515      of P's type are ignored for type deduction.  If P is a
13516      reference type, the type referred to by P is used for
13517      type deduction.  */
13518   *parm = TYPE_MAIN_VARIANT (*parm);
13519   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13520     {
13521       *parm = TREE_TYPE (*parm);
13522       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13523     }
13524
13525   /* DR 322. For conversion deduction, remove a reference type on parm
13526      too (which has been swapped into ARG).  */
13527   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13528     *arg = TREE_TYPE (*arg);
13529
13530   return result;
13531 }
13532
13533 /* Most parms like fn_type_unification.
13534
13535    If SUBR is 1, we're being called recursively (to unify the
13536    arguments of a function or method parameter of a function
13537    template). */
13538
13539 static int
13540 type_unification_real (tree tparms,
13541                        tree targs,
13542                        tree xparms,
13543                        const tree *xargs,
13544                        unsigned int xnargs,
13545                        int subr,
13546                        unification_kind_t strict,
13547                        int flags)
13548 {
13549   tree parm, arg, arg_expr;
13550   int i;
13551   int ntparms = TREE_VEC_LENGTH (tparms);
13552   int sub_strict;
13553   int saw_undeduced = 0;
13554   tree parms;
13555   const tree *args;
13556   unsigned int nargs;
13557   unsigned int ia;
13558
13559   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13560   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13561   gcc_assert (ntparms > 0);
13562
13563   /* Reset the number of non-defaulted template arguments contained
13564      in in TARGS.  */
13565   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13566
13567   switch (strict)
13568     {
13569     case DEDUCE_CALL:
13570       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13571                     | UNIFY_ALLOW_DERIVED);
13572       break;
13573
13574     case DEDUCE_CONV:
13575       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13576       break;
13577
13578     case DEDUCE_EXACT:
13579       sub_strict = UNIFY_ALLOW_NONE;
13580       break;
13581
13582     default:
13583       gcc_unreachable ();
13584     }
13585
13586  again:
13587   parms = xparms;
13588   args = xargs;
13589   nargs = xnargs;
13590
13591   ia = 0;
13592   while (parms && parms != void_list_node
13593          && ia < nargs)
13594     {
13595       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13596         break;
13597
13598       parm = TREE_VALUE (parms);
13599       parms = TREE_CHAIN (parms);
13600       arg = args[ia];
13601       ++ia;
13602       arg_expr = NULL;
13603
13604       if (arg == error_mark_node)
13605         return 1;
13606       if (arg == unknown_type_node)
13607         /* We can't deduce anything from this, but we might get all the
13608            template args from other function args.  */
13609         continue;
13610
13611       /* Conversions will be performed on a function argument that
13612          corresponds with a function parameter that contains only
13613          non-deducible template parameters and explicitly specified
13614          template parameters.  */
13615       if (!uses_template_parms (parm))
13616         {
13617           tree type;
13618
13619           if (!TYPE_P (arg))
13620             type = TREE_TYPE (arg);
13621           else
13622             type = arg;
13623
13624           if (same_type_p (parm, type))
13625             continue;
13626           if (strict != DEDUCE_EXACT
13627               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13628                                   flags))
13629             continue;
13630
13631           return 1;
13632         }
13633
13634       if (!TYPE_P (arg))
13635         {
13636           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13637           if (type_unknown_p (arg))
13638             {
13639               /* [temp.deduct.type] 
13640
13641                  A template-argument can be deduced from a pointer to
13642                  function or pointer to member function argument if
13643                  the set of overloaded functions does not contain
13644                  function templates and at most one of a set of
13645                  overloaded functions provides a unique match.  */
13646               if (resolve_overloaded_unification
13647                   (tparms, targs, parm, arg, strict, sub_strict))
13648                 continue;
13649
13650               return 1;
13651             }
13652           arg_expr = arg;
13653           arg = unlowered_expr_type (arg);
13654           if (arg == error_mark_node)
13655             return 1;
13656         }
13657
13658       {
13659         int arg_strict = sub_strict;
13660
13661         if (!subr)
13662           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13663                                                           arg_expr);
13664
13665         if (arg == init_list_type_node && arg_expr)
13666           arg = arg_expr;
13667         if (unify (tparms, targs, parm, arg, arg_strict))
13668           return 1;
13669       }
13670     }
13671
13672
13673   if (parms 
13674       && parms != void_list_node
13675       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13676     {
13677       /* Unify the remaining arguments with the pack expansion type.  */
13678       tree argvec;
13679       tree parmvec = make_tree_vec (1);
13680
13681       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13682       argvec = make_tree_vec (nargs - ia);
13683       for (i = 0; ia < nargs; ++ia, ++i)
13684         TREE_VEC_ELT (argvec, i) = args[ia];
13685
13686       /* Copy the parameter into parmvec.  */
13687       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13688       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13689                                 /*call_args_p=*/true, /*subr=*/subr))
13690         return 1;
13691
13692       /* Advance to the end of the list of parameters.  */
13693       parms = TREE_CHAIN (parms);
13694     }
13695
13696   /* Fail if we've reached the end of the parm list, and more args
13697      are present, and the parm list isn't variadic.  */
13698   if (ia < nargs && parms == void_list_node)
13699     return 1;
13700   /* Fail if parms are left and they don't have default values.  */
13701   if (parms && parms != void_list_node
13702       && TREE_PURPOSE (parms) == NULL_TREE)
13703     return 1;
13704
13705   if (!subr)
13706     for (i = 0; i < ntparms; i++)
13707       if (!TREE_VEC_ELT (targs, i))
13708         {
13709           tree tparm;
13710
13711           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13712             continue;
13713
13714           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13715
13716           /* If this is an undeduced nontype parameter that depends on
13717              a type parameter, try another pass; its type may have been
13718              deduced from a later argument than the one from which
13719              this parameter can be deduced.  */
13720           if (TREE_CODE (tparm) == PARM_DECL
13721               && uses_template_parms (TREE_TYPE (tparm))
13722               && !saw_undeduced++)
13723             goto again;
13724
13725           /* Core issue #226 (C++0x) [temp.deduct]:
13726
13727                If a template argument has not been deduced, its
13728                default template argument, if any, is used. 
13729
13730              When we are in C++98 mode, TREE_PURPOSE will either
13731              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13732              to explicitly check cxx_dialect here.  */
13733           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13734             {
13735               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13736               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13737               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13738               arg = convert_template_argument (parm, arg, targs, tf_none,
13739                                                i, NULL_TREE);
13740               if (arg == error_mark_node)
13741                 return 1;
13742               else
13743                 {
13744                   TREE_VEC_ELT (targs, i) = arg;
13745                   /* The position of the first default template argument,
13746                      is also the number of non-defaulted arguments in TARGS.
13747                      Record that.  */
13748                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13749                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
13750                   continue;
13751                 }
13752             }
13753
13754           /* If the type parameter is a parameter pack, then it will
13755              be deduced to an empty parameter pack.  */
13756           if (template_parameter_pack_p (tparm))
13757             {
13758               tree arg;
13759
13760               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13761                 {
13762                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13763                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13764                   TREE_CONSTANT (arg) = 1;
13765                 }
13766               else
13767                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13768
13769               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13770
13771               TREE_VEC_ELT (targs, i) = arg;
13772               continue;
13773             }
13774
13775           return 2;
13776         }
13777 #ifdef ENABLE_CHECKING
13778   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13779     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
13780 #endif
13781
13782   return 0;
13783 }
13784
13785 /* Subroutine of type_unification_real.  Args are like the variables
13786    at the call site.  ARG is an overloaded function (or template-id);
13787    we try deducing template args from each of the overloads, and if
13788    only one succeeds, we go with that.  Modifies TARGS and returns
13789    true on success.  */
13790
13791 static bool
13792 resolve_overloaded_unification (tree tparms,
13793                                 tree targs,
13794                                 tree parm,
13795                                 tree arg,
13796                                 unification_kind_t strict,
13797                                 int sub_strict)
13798 {
13799   tree tempargs = copy_node (targs);
13800   int good = 0;
13801   tree goodfn = NULL_TREE;
13802   bool addr_p;
13803
13804   if (TREE_CODE (arg) == ADDR_EXPR)
13805     {
13806       arg = TREE_OPERAND (arg, 0);
13807       addr_p = true;
13808     }
13809   else
13810     addr_p = false;
13811
13812   if (TREE_CODE (arg) == COMPONENT_REF)
13813     /* Handle `&x' where `x' is some static or non-static member
13814        function name.  */
13815     arg = TREE_OPERAND (arg, 1);
13816
13817   if (TREE_CODE (arg) == OFFSET_REF)
13818     arg = TREE_OPERAND (arg, 1);
13819
13820   /* Strip baselink information.  */
13821   if (BASELINK_P (arg))
13822     arg = BASELINK_FUNCTIONS (arg);
13823
13824   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13825     {
13826       /* If we got some explicit template args, we need to plug them into
13827          the affected templates before we try to unify, in case the
13828          explicit args will completely resolve the templates in question.  */
13829
13830       tree expl_subargs = TREE_OPERAND (arg, 1);
13831       arg = TREE_OPERAND (arg, 0);
13832
13833       for (; arg; arg = OVL_NEXT (arg))
13834         {
13835           tree fn = OVL_CURRENT (arg);
13836           tree subargs, elem;
13837
13838           if (TREE_CODE (fn) != TEMPLATE_DECL)
13839             continue;
13840
13841           ++processing_template_decl;
13842           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13843                                   expl_subargs, /*check_ret=*/false);
13844           if (subargs)
13845             {
13846               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13847               if (try_one_overload (tparms, targs, tempargs, parm,
13848                                     elem, strict, sub_strict, addr_p)
13849                   && (!goodfn || !decls_match (goodfn, elem)))
13850                 {
13851                   goodfn = elem;
13852                   ++good;
13853                 }
13854             }
13855           --processing_template_decl;
13856         }
13857     }
13858   else if (TREE_CODE (arg) != OVERLOAD
13859            && TREE_CODE (arg) != FUNCTION_DECL)
13860     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13861        -- but the deduction does not succeed because the expression is
13862        not just the function on its own.  */
13863     return false;
13864   else
13865     for (; arg; arg = OVL_NEXT (arg))
13866       if (try_one_overload (tparms, targs, tempargs, parm,
13867                             TREE_TYPE (OVL_CURRENT (arg)),
13868                             strict, sub_strict, addr_p)
13869           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13870         {
13871           goodfn = OVL_CURRENT (arg);
13872           ++good;
13873         }
13874
13875   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13876      to function or pointer to member function argument if the set of
13877      overloaded functions does not contain function templates and at most
13878      one of a set of overloaded functions provides a unique match.
13879
13880      So if we found multiple possibilities, we return success but don't
13881      deduce anything.  */
13882
13883   if (good == 1)
13884     {
13885       int i = TREE_VEC_LENGTH (targs);
13886       for (; i--; )
13887         if (TREE_VEC_ELT (tempargs, i))
13888           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13889     }
13890   if (good)
13891     return true;
13892
13893   return false;
13894 }
13895
13896 /* Core DR 115: In contexts where deduction is done and fails, or in
13897    contexts where deduction is not done, if a template argument list is
13898    specified and it, along with any default template arguments, identifies
13899    a single function template specialization, then the template-id is an
13900    lvalue for the function template specialization.  */
13901
13902 tree
13903 resolve_nondeduced_context (tree orig_expr)
13904 {
13905   tree expr, offset, baselink;
13906   bool addr;
13907
13908   if (!type_unknown_p (orig_expr))
13909     return orig_expr;
13910
13911   expr = orig_expr;
13912   addr = false;
13913   offset = NULL_TREE;
13914   baselink = NULL_TREE;
13915
13916   if (TREE_CODE (expr) == ADDR_EXPR)
13917     {
13918       expr = TREE_OPERAND (expr, 0);
13919       addr = true;
13920     }
13921   if (TREE_CODE (expr) == OFFSET_REF)
13922     {
13923       offset = expr;
13924       expr = TREE_OPERAND (expr, 1);
13925     }
13926   if (TREE_CODE (expr) == BASELINK)
13927     {
13928       baselink = expr;
13929       expr = BASELINK_FUNCTIONS (expr);
13930     }
13931
13932   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13933     {
13934       int good = 0;
13935       tree goodfn = NULL_TREE;
13936
13937       /* If we got some explicit template args, we need to plug them into
13938          the affected templates before we try to unify, in case the
13939          explicit args will completely resolve the templates in question.  */
13940
13941       tree expl_subargs = TREE_OPERAND (expr, 1);
13942       tree arg = TREE_OPERAND (expr, 0);
13943       tree badfn = NULL_TREE;
13944       tree badargs = NULL_TREE;
13945
13946       for (; arg; arg = OVL_NEXT (arg))
13947         {
13948           tree fn = OVL_CURRENT (arg);
13949           tree subargs, elem;
13950
13951           if (TREE_CODE (fn) != TEMPLATE_DECL)
13952             continue;
13953
13954           ++processing_template_decl;
13955           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13956                                   expl_subargs, /*check_ret=*/false);
13957           if (subargs && !any_dependent_template_arguments_p (subargs))
13958             {
13959               elem = instantiate_template (fn, subargs, tf_none);
13960               if (elem == error_mark_node)
13961                 {
13962                   badfn = fn;
13963                   badargs = subargs;
13964                 }
13965               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13966                 {
13967                   goodfn = elem;
13968                   ++good;
13969                 }
13970             }
13971           --processing_template_decl;
13972         }
13973       if (good == 1)
13974         {
13975           expr = goodfn;
13976           if (baselink)
13977             expr = build_baselink (BASELINK_BINFO (baselink),
13978                                    BASELINK_ACCESS_BINFO (baselink),
13979                                    expr, BASELINK_OPTYPE (baselink));
13980           if (offset)
13981             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13982                            TREE_OPERAND (offset, 0), expr);
13983           if (addr)
13984             expr = build_address (expr);
13985           return expr;
13986         }
13987       else if (good == 0 && badargs)
13988         /* There were no good options and at least one bad one, so let the
13989            user know what the problem is.  */
13990         instantiate_template (badfn, badargs, tf_warning_or_error);
13991     }
13992   return orig_expr;
13993 }
13994
13995 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13996    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13997    different overloads deduce different arguments for a given parm.
13998    ADDR_P is true if the expression for which deduction is being
13999    performed was of the form "& fn" rather than simply "fn".
14000
14001    Returns 1 on success.  */
14002
14003 static int
14004 try_one_overload (tree tparms,
14005                   tree orig_targs,
14006                   tree targs,
14007                   tree parm,
14008                   tree arg,
14009                   unification_kind_t strict,
14010                   int sub_strict,
14011                   bool addr_p)
14012 {
14013   int nargs;
14014   tree tempargs;
14015   int i;
14016
14017   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14018      to function or pointer to member function argument if the set of
14019      overloaded functions does not contain function templates and at most
14020      one of a set of overloaded functions provides a unique match.
14021
14022      So if this is a template, just return success.  */
14023
14024   if (uses_template_parms (arg))
14025     return 1;
14026
14027   if (TREE_CODE (arg) == METHOD_TYPE)
14028     arg = build_ptrmemfunc_type (build_pointer_type (arg));
14029   else if (addr_p)
14030     arg = build_pointer_type (arg);
14031
14032   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
14033
14034   /* We don't copy orig_targs for this because if we have already deduced
14035      some template args from previous args, unify would complain when we
14036      try to deduce a template parameter for the same argument, even though
14037      there isn't really a conflict.  */
14038   nargs = TREE_VEC_LENGTH (targs);
14039   tempargs = make_tree_vec (nargs);
14040
14041   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
14042     return 0;
14043
14044   /* First make sure we didn't deduce anything that conflicts with
14045      explicitly specified args.  */
14046   for (i = nargs; i--; )
14047     {
14048       tree elt = TREE_VEC_ELT (tempargs, i);
14049       tree oldelt = TREE_VEC_ELT (orig_targs, i);
14050
14051       if (!elt)
14052         /*NOP*/;
14053       else if (uses_template_parms (elt))
14054         /* Since we're unifying against ourselves, we will fill in
14055            template args used in the function parm list with our own
14056            template parms.  Discard them.  */
14057         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
14058       else if (oldelt && !template_args_equal (oldelt, elt))
14059         return 0;
14060     }
14061
14062   for (i = nargs; i--; )
14063     {
14064       tree elt = TREE_VEC_ELT (tempargs, i);
14065
14066       if (elt)
14067         TREE_VEC_ELT (targs, i) = elt;
14068     }
14069
14070   return 1;
14071 }
14072
14073 /* PARM is a template class (perhaps with unbound template
14074    parameters).  ARG is a fully instantiated type.  If ARG can be
14075    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
14076    TARGS are as for unify.  */
14077
14078 static tree
14079 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
14080 {
14081   tree copy_of_targs;
14082
14083   if (!CLASSTYPE_TEMPLATE_INFO (arg)
14084       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
14085           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
14086     return NULL_TREE;
14087
14088   /* We need to make a new template argument vector for the call to
14089      unify.  If we used TARGS, we'd clutter it up with the result of
14090      the attempted unification, even if this class didn't work out.
14091      We also don't want to commit ourselves to all the unifications
14092      we've already done, since unification is supposed to be done on
14093      an argument-by-argument basis.  In other words, consider the
14094      following pathological case:
14095
14096        template <int I, int J, int K>
14097        struct S {};
14098
14099        template <int I, int J>
14100        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
14101
14102        template <int I, int J, int K>
14103        void f(S<I, J, K>, S<I, I, I>);
14104
14105        void g() {
14106          S<0, 0, 0> s0;
14107          S<0, 1, 2> s2;
14108
14109          f(s0, s2);
14110        }
14111
14112      Now, by the time we consider the unification involving `s2', we
14113      already know that we must have `f<0, 0, 0>'.  But, even though
14114      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14115      because there are two ways to unify base classes of S<0, 1, 2>
14116      with S<I, I, I>.  If we kept the already deduced knowledge, we
14117      would reject the possibility I=1.  */
14118   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14119
14120   /* If unification failed, we're done.  */
14121   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14122              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14123     return NULL_TREE;
14124
14125   return arg;
14126 }
14127
14128 /* Given a template type PARM and a class type ARG, find the unique
14129    base type in ARG that is an instance of PARM.  We do not examine
14130    ARG itself; only its base-classes.  If there is not exactly one
14131    appropriate base class, return NULL_TREE.  PARM may be the type of
14132    a partial specialization, as well as a plain template type.  Used
14133    by unify.  */
14134
14135 static tree
14136 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14137 {
14138   tree rval = NULL_TREE;
14139   tree binfo;
14140
14141   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14142
14143   binfo = TYPE_BINFO (complete_type (arg));
14144   if (!binfo)
14145     /* The type could not be completed.  */
14146     return NULL_TREE;
14147
14148   /* Walk in inheritance graph order.  The search order is not
14149      important, and this avoids multiple walks of virtual bases.  */
14150   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14151     {
14152       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14153
14154       if (r)
14155         {
14156           /* If there is more than one satisfactory baseclass, then:
14157
14158                [temp.deduct.call]
14159
14160               If they yield more than one possible deduced A, the type
14161               deduction fails.
14162
14163              applies.  */
14164           if (rval && !same_type_p (r, rval))
14165             return NULL_TREE;
14166
14167           rval = r;
14168         }
14169     }
14170
14171   return rval;
14172 }
14173
14174 /* Returns the level of DECL, which declares a template parameter.  */
14175
14176 static int
14177 template_decl_level (tree decl)
14178 {
14179   switch (TREE_CODE (decl))
14180     {
14181     case TYPE_DECL:
14182     case TEMPLATE_DECL:
14183       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14184
14185     case PARM_DECL:
14186       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14187
14188     default:
14189       gcc_unreachable ();
14190     }
14191   return 0;
14192 }
14193
14194 /* Decide whether ARG can be unified with PARM, considering only the
14195    cv-qualifiers of each type, given STRICT as documented for unify.
14196    Returns nonzero iff the unification is OK on that basis.  */
14197
14198 static int
14199 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14200 {
14201   int arg_quals = cp_type_quals (arg);
14202   int parm_quals = cp_type_quals (parm);
14203
14204   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14205       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14206     {
14207       /*  Although a CVR qualifier is ignored when being applied to a
14208           substituted template parameter ([8.3.2]/1 for example), that
14209           does not allow us to unify "const T" with "int&" because both
14210           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
14211           It is ok when we're allowing additional CV qualifiers
14212           at the outer level [14.8.2.1]/3,1st bullet.  */
14213       if ((TREE_CODE (arg) == REFERENCE_TYPE
14214            || TREE_CODE (arg) == FUNCTION_TYPE
14215            || TREE_CODE (arg) == METHOD_TYPE)
14216           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14217         return 0;
14218
14219       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14220           && (parm_quals & TYPE_QUAL_RESTRICT))
14221         return 0;
14222     }
14223
14224   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14225       && (arg_quals & parm_quals) != parm_quals)
14226     return 0;
14227
14228   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14229       && (parm_quals & arg_quals) != arg_quals)
14230     return 0;
14231
14232   return 1;
14233 }
14234
14235 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14236 void 
14237 template_parm_level_and_index (tree parm, int* level, int* index)
14238 {
14239   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14240       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14241       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14242     {
14243       *index = TEMPLATE_TYPE_IDX (parm);
14244       *level = TEMPLATE_TYPE_LEVEL (parm);
14245     }
14246   else
14247     {
14248       *index = TEMPLATE_PARM_IDX (parm);
14249       *level = TEMPLATE_PARM_LEVEL (parm);
14250     }
14251 }
14252
14253 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14254    expansion at the end of PACKED_PARMS. Returns 0 if the type
14255    deduction succeeds, 1 otherwise. STRICT is the same as in
14256    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14257    call argument list. We'll need to adjust the arguments to make them
14258    types. SUBR tells us if this is from a recursive call to
14259    type_unification_real.  */
14260 int
14261 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14262                       tree packed_args, int strict, bool call_args_p,
14263                       bool subr)
14264 {
14265   tree parm 
14266     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14267   tree pattern = PACK_EXPANSION_PATTERN (parm);
14268   tree pack, packs = NULL_TREE;
14269   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14270   int len = TREE_VEC_LENGTH (packed_args);
14271
14272   /* Determine the parameter packs we will be deducing from the
14273      pattern, and record their current deductions.  */
14274   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14275        pack; pack = TREE_CHAIN (pack))
14276     {
14277       tree parm_pack = TREE_VALUE (pack);
14278       int idx, level;
14279
14280       /* Determine the index and level of this parameter pack.  */
14281       template_parm_level_and_index (parm_pack, &level, &idx);
14282
14283       /* Keep track of the parameter packs and their corresponding
14284          argument packs.  */
14285       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14286       TREE_TYPE (packs) = make_tree_vec (len - start);
14287     }
14288   
14289   /* Loop through all of the arguments that have not yet been
14290      unified and unify each with the pattern.  */
14291   for (i = start; i < len; i++)
14292     {
14293       tree parm = pattern;
14294
14295       /* For each parameter pack, clear out the deduced value so that
14296          we can deduce it again.  */
14297       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14298         {
14299           int idx, level;
14300           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14301
14302           TMPL_ARG (targs, level, idx) = NULL_TREE;
14303         }
14304
14305       /* Unify the pattern with the current argument.  */
14306       {
14307         tree arg = TREE_VEC_ELT (packed_args, i);
14308         tree arg_expr = NULL_TREE;
14309         int arg_strict = strict;
14310         bool skip_arg_p = false;
14311
14312         if (call_args_p)
14313           {
14314             int sub_strict;
14315
14316             /* This mirrors what we do in type_unification_real.  */
14317             switch (strict)
14318               {
14319               case DEDUCE_CALL:
14320                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14321                               | UNIFY_ALLOW_MORE_CV_QUAL
14322                               | UNIFY_ALLOW_DERIVED);
14323                 break;
14324                 
14325               case DEDUCE_CONV:
14326                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14327                 break;
14328                 
14329               case DEDUCE_EXACT:
14330                 sub_strict = UNIFY_ALLOW_NONE;
14331                 break;
14332                 
14333               default:
14334                 gcc_unreachable ();
14335               }
14336
14337             if (!TYPE_P (arg))
14338               {
14339                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14340                 if (type_unknown_p (arg))
14341                   {
14342                     /* [temp.deduct.type] A template-argument can be
14343                        deduced from a pointer to function or pointer
14344                        to member function argument if the set of
14345                        overloaded functions does not contain function
14346                        templates and at most one of a set of
14347                        overloaded functions provides a unique
14348                        match.  */
14349
14350                     if (resolve_overloaded_unification
14351                         (tparms, targs, parm, arg,
14352                          (unification_kind_t) strict,
14353                          sub_strict)
14354                         != 0)
14355                       return 1;
14356                     skip_arg_p = true;
14357                   }
14358
14359                 if (!skip_arg_p)
14360                   {
14361                     arg_expr = arg;
14362                     arg = unlowered_expr_type (arg);
14363                     if (arg == error_mark_node)
14364                       return 1;
14365                   }
14366               }
14367       
14368             arg_strict = sub_strict;
14369
14370             if (!subr)
14371               arg_strict |= 
14372                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14373                                                   &parm, &arg, arg_expr);
14374           }
14375
14376         if (!skip_arg_p)
14377           {
14378             /* For deduction from an init-list we need the actual list.  */
14379             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14380               arg = arg_expr;
14381             if (unify (tparms, targs, parm, arg, arg_strict))
14382               return 1;
14383           }
14384       }
14385
14386       /* For each parameter pack, collect the deduced value.  */
14387       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14388         {
14389           int idx, level;
14390           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14391
14392           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14393             TMPL_ARG (targs, level, idx);
14394         }
14395     }
14396
14397   /* Verify that the results of unification with the parameter packs
14398      produce results consistent with what we've seen before, and make
14399      the deduced argument packs available.  */
14400   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14401     {
14402       tree old_pack = TREE_VALUE (pack);
14403       tree new_args = TREE_TYPE (pack);
14404       int i, len = TREE_VEC_LENGTH (new_args);
14405       int idx, level;
14406       bool nondeduced_p = false;
14407
14408       /* By default keep the original deduced argument pack.
14409          If necessary, more specific code is going to update the
14410          resulting deduced argument later down in this function.  */
14411       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14412       TMPL_ARG (targs, level, idx) = old_pack;
14413
14414       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14415          actually deduce anything.  */
14416       for (i = 0; i < len && !nondeduced_p; ++i)
14417         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14418           nondeduced_p = true;
14419       if (nondeduced_p)
14420         continue;
14421
14422       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14423         {
14424           /* Prepend the explicit arguments onto NEW_ARGS.  */
14425           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14426           tree old_args = new_args;
14427           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14428           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14429
14430           /* Copy the explicit arguments.  */
14431           new_args = make_tree_vec (len);
14432           for (i = 0; i < explicit_len; i++)
14433             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14434
14435           /* Copy the deduced arguments.  */
14436           for (; i < len; i++)
14437             TREE_VEC_ELT (new_args, i) =
14438               TREE_VEC_ELT (old_args, i - explicit_len);
14439         }
14440
14441       if (!old_pack)
14442         {
14443           tree result;
14444           /* Build the deduced *_ARGUMENT_PACK.  */
14445           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14446             {
14447               result = make_node (NONTYPE_ARGUMENT_PACK);
14448               TREE_TYPE (result) = 
14449                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14450               TREE_CONSTANT (result) = 1;
14451             }
14452           else
14453             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14454
14455           SET_ARGUMENT_PACK_ARGS (result, new_args);
14456
14457           /* Note the deduced argument packs for this parameter
14458              pack.  */
14459           TMPL_ARG (targs, level, idx) = result;
14460         }
14461       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14462                && (ARGUMENT_PACK_ARGS (old_pack) 
14463                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14464         {
14465           /* We only had the explicitly-provided arguments before, but
14466              now we have a complete set of arguments.  */
14467           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14468
14469           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14470           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14471           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14472         }
14473       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14474                                     new_args))
14475         /* Inconsistent unification of this parameter pack.  */
14476         return 1;
14477     }
14478
14479   return 0;
14480 }
14481
14482 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14483    set of template parameters to a template.  TARGS is the bindings
14484    for those template parameters, as determined thus far; TARGS may
14485    include template arguments for outer levels of template parameters
14486    as well.  PARM is a parameter to a template function, or a
14487    subcomponent of that parameter; ARG is the corresponding argument.
14488    This function attempts to match PARM with ARG in a manner
14489    consistent with the existing assignments in TARGS.  If more values
14490    are deduced, then TARGS is updated.
14491
14492    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14493    parameter STRICT is a bitwise or of the following flags:
14494
14495      UNIFY_ALLOW_NONE:
14496        Require an exact match between PARM and ARG.
14497      UNIFY_ALLOW_MORE_CV_QUAL:
14498        Allow the deduced ARG to be more cv-qualified (by qualification
14499        conversion) than ARG.
14500      UNIFY_ALLOW_LESS_CV_QUAL:
14501        Allow the deduced ARG to be less cv-qualified than ARG.
14502      UNIFY_ALLOW_DERIVED:
14503        Allow the deduced ARG to be a template base class of ARG,
14504        or a pointer to a template base class of the type pointed to by
14505        ARG.
14506      UNIFY_ALLOW_INTEGER:
14507        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14508        case for more information.
14509      UNIFY_ALLOW_OUTER_LEVEL:
14510        This is the outermost level of a deduction. Used to determine validity
14511        of qualification conversions. A valid qualification conversion must
14512        have const qualified pointers leading up to the inner type which
14513        requires additional CV quals, except at the outer level, where const
14514        is not required [conv.qual]. It would be normal to set this flag in
14515        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14516      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14517        This is the outermost level of a deduction, and PARM can be more CV
14518        qualified at this point.
14519      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14520        This is the outermost level of a deduction, and PARM can be less CV
14521        qualified at this point.  */
14522
14523 static int
14524 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14525 {
14526   int idx;
14527   tree targ;
14528   tree tparm;
14529   int strict_in = strict;
14530
14531   /* I don't think this will do the right thing with respect to types.
14532      But the only case I've seen it in so far has been array bounds, where
14533      signedness is the only information lost, and I think that will be
14534      okay.  */
14535   while (TREE_CODE (parm) == NOP_EXPR)
14536     parm = TREE_OPERAND (parm, 0);
14537
14538   if (arg == error_mark_node)
14539     return 1;
14540   if (arg == unknown_type_node
14541       || arg == init_list_type_node)
14542     /* We can't deduce anything from this, but we might get all the
14543        template args from other function args.  */
14544     return 0;
14545
14546   /* If PARM uses template parameters, then we can't bail out here,
14547      even if ARG == PARM, since we won't record unifications for the
14548      template parameters.  We might need them if we're trying to
14549      figure out which of two things is more specialized.  */
14550   if (arg == parm && !uses_template_parms (parm))
14551     return 0;
14552
14553   /* Handle init lists early, so the rest of the function can assume
14554      we're dealing with a type. */
14555   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14556     {
14557       tree elt, elttype;
14558       unsigned i;
14559       tree orig_parm = parm;
14560
14561       /* Replace T with std::initializer_list<T> for deduction.  */
14562       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14563           && flag_deduce_init_list)
14564         parm = listify (parm);
14565
14566       if (!is_std_init_list (parm))
14567         /* We can only deduce from an initializer list argument if the
14568            parameter is std::initializer_list; otherwise this is a
14569            non-deduced context. */
14570         return 0;
14571
14572       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14573
14574       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14575         {
14576           int elt_strict = strict;
14577
14578           if (elt == error_mark_node)
14579             return 1;
14580
14581           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14582             {
14583               tree type = TREE_TYPE (elt);
14584               /* It should only be possible to get here for a call.  */
14585               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14586               elt_strict |= maybe_adjust_types_for_deduction
14587                 (DEDUCE_CALL, &elttype, &type, elt);
14588               elt = type;
14589             }
14590
14591           if (unify (tparms, targs, elttype, elt, elt_strict))
14592             return 1;
14593         }
14594
14595       /* If the std::initializer_list<T> deduction worked, replace the
14596          deduced A with std::initializer_list<A>.  */
14597       if (orig_parm != parm)
14598         {
14599           idx = TEMPLATE_TYPE_IDX (orig_parm);
14600           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14601           targ = listify (targ);
14602           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14603         }
14604       return 0;
14605     }
14606
14607   /* Immediately reject some pairs that won't unify because of
14608      cv-qualification mismatches.  */
14609   if (TREE_CODE (arg) == TREE_CODE (parm)
14610       && TYPE_P (arg)
14611       /* It is the elements of the array which hold the cv quals of an array
14612          type, and the elements might be template type parms. We'll check
14613          when we recurse.  */
14614       && TREE_CODE (arg) != ARRAY_TYPE
14615       /* We check the cv-qualifiers when unifying with template type
14616          parameters below.  We want to allow ARG `const T' to unify with
14617          PARM `T' for example, when computing which of two templates
14618          is more specialized, for example.  */
14619       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14620       && !check_cv_quals_for_unify (strict_in, arg, parm))
14621     return 1;
14622
14623   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14624       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14625     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14626   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14627   strict &= ~UNIFY_ALLOW_DERIVED;
14628   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14629   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14630
14631   switch (TREE_CODE (parm))
14632     {
14633     case TYPENAME_TYPE:
14634     case SCOPE_REF:
14635     case UNBOUND_CLASS_TEMPLATE:
14636       /* In a type which contains a nested-name-specifier, template
14637          argument values cannot be deduced for template parameters used
14638          within the nested-name-specifier.  */
14639       return 0;
14640
14641     case TEMPLATE_TYPE_PARM:
14642     case TEMPLATE_TEMPLATE_PARM:
14643     case BOUND_TEMPLATE_TEMPLATE_PARM:
14644       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14645       if (tparm == error_mark_node)
14646         return 1;
14647
14648       if (TEMPLATE_TYPE_LEVEL (parm)
14649           != template_decl_level (tparm))
14650         /* The PARM is not one we're trying to unify.  Just check
14651            to see if it matches ARG.  */
14652         return (TREE_CODE (arg) == TREE_CODE (parm)
14653                 && same_type_p (parm, arg)) ? 0 : 1;
14654       idx = TEMPLATE_TYPE_IDX (parm);
14655       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14656       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14657
14658       /* Check for mixed types and values.  */
14659       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14660            && TREE_CODE (tparm) != TYPE_DECL)
14661           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14662               && TREE_CODE (tparm) != TEMPLATE_DECL))
14663         return 1;
14664
14665       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14666         {
14667           /* ARG must be constructed from a template class or a template
14668              template parameter.  */
14669           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14670               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14671             return 1;
14672
14673           {
14674             tree parmvec = TYPE_TI_ARGS (parm);
14675             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14676             tree parm_parms 
14677               = DECL_INNERMOST_TEMPLATE_PARMS
14678                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14679             int i, len;
14680             int parm_variadic_p = 0;
14681
14682             /* The resolution to DR150 makes clear that default
14683                arguments for an N-argument may not be used to bind T
14684                to a template template parameter with fewer than N
14685                parameters.  It is not safe to permit the binding of
14686                default arguments as an extension, as that may change
14687                the meaning of a conforming program.  Consider:
14688
14689                   struct Dense { static const unsigned int dim = 1; };
14690
14691                   template <template <typename> class View,
14692                             typename Block>
14693                   void operator+(float, View<Block> const&);
14694
14695                   template <typename Block,
14696                             unsigned int Dim = Block::dim>
14697                   struct Lvalue_proxy { operator float() const; };
14698
14699                   void
14700                   test_1d (void) {
14701                     Lvalue_proxy<Dense> p;
14702                     float b;
14703                     b + p;
14704                   }
14705
14706               Here, if Lvalue_proxy is permitted to bind to View, then
14707               the global operator+ will be used; if they are not, the
14708               Lvalue_proxy will be converted to float.  */
14709             if (coerce_template_parms (parm_parms,
14710                                        argvec,
14711                                        TYPE_TI_TEMPLATE (parm),
14712                                        tf_none,
14713                                        /*require_all_args=*/true,
14714                                        /*use_default_args=*/false)
14715                 == error_mark_node)
14716               return 1;
14717
14718             /* Deduce arguments T, i from TT<T> or TT<i>.
14719                We check each element of PARMVEC and ARGVEC individually
14720                rather than the whole TREE_VEC since they can have
14721                different number of elements.  */
14722
14723             parmvec = expand_template_argument_pack (parmvec);
14724             argvec = expand_template_argument_pack (argvec);
14725
14726             len = TREE_VEC_LENGTH (parmvec);
14727
14728             /* Check if the parameters end in a pack, making them
14729                variadic.  */
14730             if (len > 0
14731                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14732               parm_variadic_p = 1;
14733             
14734             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14735               return 1;
14736
14737              for (i = 0; i < len - parm_variadic_p; ++i)
14738               {
14739                 if (unify (tparms, targs,
14740                            TREE_VEC_ELT (parmvec, i),
14741                            TREE_VEC_ELT (argvec, i),
14742                            UNIFY_ALLOW_NONE))
14743                   return 1;
14744               }
14745
14746             if (parm_variadic_p
14747                 && unify_pack_expansion (tparms, targs,
14748                                          parmvec, argvec,
14749                                          UNIFY_ALLOW_NONE,
14750                                          /*call_args_p=*/false,
14751                                          /*subr=*/false))
14752               return 1;
14753           }
14754           arg = TYPE_TI_TEMPLATE (arg);
14755
14756           /* Fall through to deduce template name.  */
14757         }
14758
14759       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14760           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14761         {
14762           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14763
14764           /* Simple cases: Value already set, does match or doesn't.  */
14765           if (targ != NULL_TREE && template_args_equal (targ, arg))
14766             return 0;
14767           else if (targ)
14768             return 1;
14769         }
14770       else
14771         {
14772           /* If PARM is `const T' and ARG is only `int', we don't have
14773              a match unless we are allowing additional qualification.
14774              If ARG is `const int' and PARM is just `T' that's OK;
14775              that binds `const int' to `T'.  */
14776           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14777                                          arg, parm))
14778             return 1;
14779
14780           /* Consider the case where ARG is `const volatile int' and
14781              PARM is `const T'.  Then, T should be `volatile int'.  */
14782           arg = cp_build_qualified_type_real
14783             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14784           if (arg == error_mark_node)
14785             return 1;
14786
14787           /* Simple cases: Value already set, does match or doesn't.  */
14788           if (targ != NULL_TREE && same_type_p (targ, arg))
14789             return 0;
14790           else if (targ)
14791             return 1;
14792
14793           /* Make sure that ARG is not a variable-sized array.  (Note
14794              that were talking about variable-sized arrays (like
14795              `int[n]'), rather than arrays of unknown size (like
14796              `int[]').)  We'll get very confused by such a type since
14797              the bound of the array will not be computable in an
14798              instantiation.  Besides, such types are not allowed in
14799              ISO C++, so we can do as we please here.  */
14800           if (variably_modified_type_p (arg, NULL_TREE))
14801             return 1;
14802
14803           /* Strip typedefs as in convert_template_argument.  */
14804           arg = strip_typedefs (arg);
14805         }
14806
14807       /* If ARG is a parameter pack or an expansion, we cannot unify
14808          against it unless PARM is also a parameter pack.  */
14809       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14810           && !template_parameter_pack_p (parm))
14811         return 1;
14812
14813       /* If the argument deduction results is a METHOD_TYPE,
14814          then there is a problem.
14815          METHOD_TYPE doesn't map to any real C++ type the result of
14816          the deduction can not be of that type.  */
14817       if (TREE_CODE (arg) == METHOD_TYPE)
14818         return 1;
14819
14820       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14821       return 0;
14822
14823     case TEMPLATE_PARM_INDEX:
14824       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14825       if (tparm == error_mark_node)
14826         return 1;
14827
14828       if (TEMPLATE_PARM_LEVEL (parm)
14829           != template_decl_level (tparm))
14830         /* The PARM is not one we're trying to unify.  Just check
14831            to see if it matches ARG.  */
14832         return !(TREE_CODE (arg) == TREE_CODE (parm)
14833                  && cp_tree_equal (parm, arg));
14834
14835       idx = TEMPLATE_PARM_IDX (parm);
14836       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14837
14838       if (targ)
14839         return !cp_tree_equal (targ, arg);
14840
14841       /* [temp.deduct.type] If, in the declaration of a function template
14842          with a non-type template-parameter, the non-type
14843          template-parameter is used in an expression in the function
14844          parameter-list and, if the corresponding template-argument is
14845          deduced, the template-argument type shall match the type of the
14846          template-parameter exactly, except that a template-argument
14847          deduced from an array bound may be of any integral type.
14848          The non-type parameter might use already deduced type parameters.  */
14849       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14850       if (!TREE_TYPE (arg))
14851         /* Template-parameter dependent expression.  Just accept it for now.
14852            It will later be processed in convert_template_argument.  */
14853         ;
14854       else if (same_type_p (TREE_TYPE (arg), tparm))
14855         /* OK */;
14856       else if ((strict & UNIFY_ALLOW_INTEGER)
14857                && (TREE_CODE (tparm) == INTEGER_TYPE
14858                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14859         /* Convert the ARG to the type of PARM; the deduced non-type
14860            template argument must exactly match the types of the
14861            corresponding parameter.  */
14862         arg = fold (build_nop (tparm, arg));
14863       else if (uses_template_parms (tparm))
14864         /* We haven't deduced the type of this parameter yet.  Try again
14865            later.  */
14866         return 0;
14867       else
14868         return 1;
14869
14870       /* If ARG is a parameter pack or an expansion, we cannot unify
14871          against it unless PARM is also a parameter pack.  */
14872       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14873           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14874         return 1;
14875
14876       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14877       return 0;
14878
14879     case PTRMEM_CST:
14880      {
14881         /* A pointer-to-member constant can be unified only with
14882          another constant.  */
14883       if (TREE_CODE (arg) != PTRMEM_CST)
14884         return 1;
14885
14886       /* Just unify the class member. It would be useless (and possibly
14887          wrong, depending on the strict flags) to unify also
14888          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14889          arg refer to the same variable, even if through different
14890          classes. For instance:
14891
14892          struct A { int x; };
14893          struct B : A { };
14894
14895          Unification of &A::x and &B::x must succeed.  */
14896       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14897                     PTRMEM_CST_MEMBER (arg), strict);
14898      }
14899
14900     case POINTER_TYPE:
14901       {
14902         if (TREE_CODE (arg) != POINTER_TYPE)
14903           return 1;
14904
14905         /* [temp.deduct.call]
14906
14907            A can be another pointer or pointer to member type that can
14908            be converted to the deduced A via a qualification
14909            conversion (_conv.qual_).
14910
14911            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14912            This will allow for additional cv-qualification of the
14913            pointed-to types if appropriate.  */
14914
14915         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14916           /* The derived-to-base conversion only persists through one
14917              level of pointers.  */
14918           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14919
14920         return unify (tparms, targs, TREE_TYPE (parm),
14921                       TREE_TYPE (arg), strict);
14922       }
14923
14924     case REFERENCE_TYPE:
14925       if (TREE_CODE (arg) != REFERENCE_TYPE)
14926         return 1;
14927       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14928                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14929
14930     case ARRAY_TYPE:
14931       if (TREE_CODE (arg) != ARRAY_TYPE)
14932         return 1;
14933       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14934           != (TYPE_DOMAIN (arg) == NULL_TREE))
14935         return 1;
14936       if (TYPE_DOMAIN (parm) != NULL_TREE)
14937         {
14938           tree parm_max;
14939           tree arg_max;
14940           bool parm_cst;
14941           bool arg_cst;
14942
14943           /* Our representation of array types uses "N - 1" as the
14944              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14945              not an integer constant.  We cannot unify arbitrarily
14946              complex expressions, so we eliminate the MINUS_EXPRs
14947              here.  */
14948           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14949           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14950           if (!parm_cst)
14951             {
14952               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14953               parm_max = TREE_OPERAND (parm_max, 0);
14954             }
14955           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14956           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14957           if (!arg_cst)
14958             {
14959               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14960                  trying to unify the type of a variable with the type
14961                  of a template parameter.  For example:
14962
14963                    template <unsigned int N>
14964                    void f (char (&) [N]);
14965                    int g(); 
14966                    void h(int i) {
14967                      char a[g(i)];
14968                      f(a); 
14969                    }
14970
14971                 Here, the type of the ARG will be "int [g(i)]", and
14972                 may be a SAVE_EXPR, etc.  */
14973               if (TREE_CODE (arg_max) != MINUS_EXPR)
14974                 return 1;
14975               arg_max = TREE_OPERAND (arg_max, 0);
14976             }
14977
14978           /* If only one of the bounds used a MINUS_EXPR, compensate
14979              by adding one to the other bound.  */
14980           if (parm_cst && !arg_cst)
14981             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14982                                     integer_type_node,
14983                                     parm_max,
14984                                     integer_one_node);
14985           else if (arg_cst && !parm_cst)
14986             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14987                                    integer_type_node,
14988                                    arg_max,
14989                                    integer_one_node);
14990
14991           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14992             return 1;
14993         }
14994       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14995                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14996
14997     case REAL_TYPE:
14998     case COMPLEX_TYPE:
14999     case VECTOR_TYPE:
15000     case INTEGER_TYPE:
15001     case BOOLEAN_TYPE:
15002     case ENUMERAL_TYPE:
15003     case VOID_TYPE:
15004       if (TREE_CODE (arg) != TREE_CODE (parm))
15005         return 1;
15006
15007       /* We have already checked cv-qualification at the top of the
15008          function.  */
15009       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
15010         return 1;
15011
15012       /* As far as unification is concerned, this wins.  Later checks
15013          will invalidate it if necessary.  */
15014       return 0;
15015
15016       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
15017       /* Type INTEGER_CST can come from ordinary constant template args.  */
15018     case INTEGER_CST:
15019       while (TREE_CODE (arg) == NOP_EXPR)
15020         arg = TREE_OPERAND (arg, 0);
15021
15022       if (TREE_CODE (arg) != INTEGER_CST)
15023         return 1;
15024       return !tree_int_cst_equal (parm, arg);
15025
15026     case TREE_VEC:
15027       {
15028         int i;
15029         if (TREE_CODE (arg) != TREE_VEC)
15030           return 1;
15031         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
15032           return 1;
15033         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
15034           if (unify (tparms, targs,
15035                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
15036                      UNIFY_ALLOW_NONE))
15037             return 1;
15038         return 0;
15039       }
15040
15041     case RECORD_TYPE:
15042     case UNION_TYPE:
15043       if (TREE_CODE (arg) != TREE_CODE (parm))
15044         return 1;
15045
15046       if (TYPE_PTRMEMFUNC_P (parm))
15047         {
15048           if (!TYPE_PTRMEMFUNC_P (arg))
15049             return 1;
15050
15051           return unify (tparms, targs,
15052                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
15053                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
15054                         strict);
15055         }
15056
15057       if (CLASSTYPE_TEMPLATE_INFO (parm))
15058         {
15059           tree t = NULL_TREE;
15060
15061           if (strict_in & UNIFY_ALLOW_DERIVED)
15062             {
15063               /* First, we try to unify the PARM and ARG directly.  */
15064               t = try_class_unification (tparms, targs,
15065                                          parm, arg);
15066
15067               if (!t)
15068                 {
15069                   /* Fallback to the special case allowed in
15070                      [temp.deduct.call]:
15071
15072                        If P is a class, and P has the form
15073                        template-id, then A can be a derived class of
15074                        the deduced A.  Likewise, if P is a pointer to
15075                        a class of the form template-id, A can be a
15076                        pointer to a derived class pointed to by the
15077                        deduced A.  */
15078                   t = get_template_base (tparms, targs, parm, arg);
15079
15080                   if (!t)
15081                     return 1;
15082                 }
15083             }
15084           else if (CLASSTYPE_TEMPLATE_INFO (arg)
15085                    && (CLASSTYPE_TI_TEMPLATE (parm)
15086                        == CLASSTYPE_TI_TEMPLATE (arg)))
15087             /* Perhaps PARM is something like S<U> and ARG is S<int>.
15088                Then, we should unify `int' and `U'.  */
15089             t = arg;
15090           else
15091             /* There's no chance of unification succeeding.  */
15092             return 1;
15093
15094           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
15095                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
15096         }
15097       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
15098         return 1;
15099       return 0;
15100
15101     case METHOD_TYPE:
15102     case FUNCTION_TYPE:
15103       {
15104         unsigned int nargs;
15105         tree *args;
15106         tree a;
15107         unsigned int i;
15108
15109         if (TREE_CODE (arg) != TREE_CODE (parm))
15110           return 1;
15111
15112         /* CV qualifications for methods can never be deduced, they must
15113            match exactly.  We need to check them explicitly here,
15114            because type_unification_real treats them as any other
15115            cv-qualified parameter.  */
15116         if (TREE_CODE (parm) == METHOD_TYPE
15117             && (!check_cv_quals_for_unify
15118                 (UNIFY_ALLOW_NONE,
15119                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
15120                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
15121           return 1;
15122
15123         if (unify (tparms, targs, TREE_TYPE (parm),
15124                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15125           return 1;
15126
15127         nargs = list_length (TYPE_ARG_TYPES (arg));
15128         args = XALLOCAVEC (tree, nargs);
15129         for (a = TYPE_ARG_TYPES (arg), i = 0;
15130              a != NULL_TREE && a != void_list_node;
15131              a = TREE_CHAIN (a), ++i)
15132           args[i] = TREE_VALUE (a);
15133         nargs = i;
15134
15135         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15136                                       args, nargs, 1, DEDUCE_EXACT,
15137                                       LOOKUP_NORMAL);
15138       }
15139
15140     case OFFSET_TYPE:
15141       /* Unify a pointer to member with a pointer to member function, which
15142          deduces the type of the member as a function type. */
15143       if (TYPE_PTRMEMFUNC_P (arg))
15144         {
15145           tree method_type;
15146           tree fntype;
15147
15148           /* Check top-level cv qualifiers */
15149           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15150             return 1;
15151
15152           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15153                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15154             return 1;
15155
15156           /* Determine the type of the function we are unifying against. */
15157           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15158           fntype =
15159             build_function_type (TREE_TYPE (method_type),
15160                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15161
15162           /* Extract the cv-qualifiers of the member function from the
15163              implicit object parameter and place them on the function
15164              type to be restored later. */
15165           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
15166           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15167         }
15168
15169       if (TREE_CODE (arg) != OFFSET_TYPE)
15170         return 1;
15171       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15172                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15173         return 1;
15174       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15175                     strict);
15176
15177     case CONST_DECL:
15178       if (DECL_TEMPLATE_PARM_P (parm))
15179         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15180       if (arg != integral_constant_value (parm))
15181         return 1;
15182       return 0;
15183
15184     case FIELD_DECL:
15185     case TEMPLATE_DECL:
15186       /* Matched cases are handled by the ARG == PARM test above.  */
15187       return 1;
15188
15189     case VAR_DECL:
15190       /* A non-type template parameter that is a variable should be a
15191          an integral constant, in which case, it whould have been
15192          folded into its (constant) value. So we should not be getting
15193          a variable here.  */
15194       gcc_unreachable ();
15195
15196     case TYPE_ARGUMENT_PACK:
15197     case NONTYPE_ARGUMENT_PACK:
15198       {
15199         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15200         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15201         int i, len = TREE_VEC_LENGTH (packed_parms);
15202         int argslen = TREE_VEC_LENGTH (packed_args);
15203         int parm_variadic_p = 0;
15204
15205         for (i = 0; i < len; ++i)
15206           {
15207             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15208               {
15209                 if (i == len - 1)
15210                   /* We can unify against something with a trailing
15211                      parameter pack.  */
15212                   parm_variadic_p = 1;
15213                 else
15214                   /* Since there is something following the pack
15215                      expansion, we cannot unify this template argument
15216                      list.  */
15217                   return 0;
15218               }
15219           }
15220           
15221
15222         /* If we don't have enough arguments to satisfy the parameters
15223            (not counting the pack expression at the end), or we have
15224            too many arguments for a parameter list that doesn't end in
15225            a pack expression, we can't unify.  */
15226         if (argslen < (len - parm_variadic_p)
15227             || (argslen > len && !parm_variadic_p))
15228           return 1;
15229
15230         /* Unify all of the parameters that precede the (optional)
15231            pack expression.  */
15232         for (i = 0; i < len - parm_variadic_p; ++i)
15233           {
15234             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15235                        TREE_VEC_ELT (packed_args, i), strict))
15236               return 1;
15237           }
15238
15239         if (parm_variadic_p)
15240           return unify_pack_expansion (tparms, targs, 
15241                                        packed_parms, packed_args,
15242                                        strict, /*call_args_p=*/false,
15243                                        /*subr=*/false);
15244         return 0;
15245       }
15246
15247       break;
15248
15249     case TYPEOF_TYPE:
15250     case DECLTYPE_TYPE:
15251       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15252          nodes.  */
15253       return 0;
15254
15255     case ERROR_MARK:
15256       /* Unification fails if we hit an error node.  */
15257       return 1;
15258
15259     default:
15260       gcc_assert (EXPR_P (parm));
15261
15262       /* We must be looking at an expression.  This can happen with
15263          something like:
15264
15265            template <int I>
15266            void foo(S<I>, S<I + 2>);
15267
15268          This is a "nondeduced context":
15269
15270            [deduct.type]
15271
15272            The nondeduced contexts are:
15273
15274            --A type that is a template-id in which one or more of
15275              the template-arguments is an expression that references
15276              a template-parameter.
15277
15278          In these cases, we assume deduction succeeded, but don't
15279          actually infer any unifications.  */
15280
15281       if (!uses_template_parms (parm)
15282           && !template_args_equal (parm, arg))
15283         return 1;
15284       else
15285         return 0;
15286     }
15287 }
15288 \f
15289 /* Note that DECL can be defined in this translation unit, if
15290    required.  */
15291
15292 static void
15293 mark_definable (tree decl)
15294 {
15295   tree clone;
15296   DECL_NOT_REALLY_EXTERN (decl) = 1;
15297   FOR_EACH_CLONE (clone, decl)
15298     DECL_NOT_REALLY_EXTERN (clone) = 1;
15299 }
15300
15301 /* Called if RESULT is explicitly instantiated, or is a member of an
15302    explicitly instantiated class.  */
15303
15304 void
15305 mark_decl_instantiated (tree result, int extern_p)
15306 {
15307   SET_DECL_EXPLICIT_INSTANTIATION (result);
15308
15309   /* If this entity has already been written out, it's too late to
15310      make any modifications.  */
15311   if (TREE_ASM_WRITTEN (result))
15312     return;
15313
15314   if (TREE_CODE (result) != FUNCTION_DECL)
15315     /* The TREE_PUBLIC flag for function declarations will have been
15316        set correctly by tsubst.  */
15317     TREE_PUBLIC (result) = 1;
15318
15319   /* This might have been set by an earlier implicit instantiation.  */
15320   DECL_COMDAT (result) = 0;
15321
15322   if (extern_p)
15323     DECL_NOT_REALLY_EXTERN (result) = 0;
15324   else
15325     {
15326       mark_definable (result);
15327       /* Always make artificials weak.  */
15328       if (DECL_ARTIFICIAL (result) && flag_weak)
15329         comdat_linkage (result);
15330       /* For WIN32 we also want to put explicit instantiations in
15331          linkonce sections.  */
15332       else if (TREE_PUBLIC (result))
15333         maybe_make_one_only (result);
15334     }
15335
15336   /* If EXTERN_P, then this function will not be emitted -- unless
15337      followed by an explicit instantiation, at which point its linkage
15338      will be adjusted.  If !EXTERN_P, then this function will be
15339      emitted here.  In neither circumstance do we want
15340      import_export_decl to adjust the linkage.  */
15341   DECL_INTERFACE_KNOWN (result) = 1;
15342 }
15343
15344 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15345    important template arguments.  If any are missing, we check whether
15346    they're important by using error_mark_node for substituting into any
15347    args that were used for partial ordering (the ones between ARGS and END)
15348    and seeing if it bubbles up.  */
15349
15350 static bool
15351 check_undeduced_parms (tree targs, tree args, tree end)
15352 {
15353   bool found = false;
15354   int i;
15355   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15356     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15357       {
15358         found = true;
15359         TREE_VEC_ELT (targs, i) = error_mark_node;
15360       }
15361   if (found)
15362     {
15363       for (; args != end; args = TREE_CHAIN (args))
15364         {
15365           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15366           if (substed == error_mark_node)
15367             return true;
15368         }
15369     }
15370   return false;
15371 }
15372
15373 /* Given two function templates PAT1 and PAT2, return:
15374
15375    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15376    -1 if PAT2 is more specialized than PAT1.
15377    0 if neither is more specialized.
15378
15379    LEN indicates the number of parameters we should consider
15380    (defaulted parameters should not be considered).
15381
15382    The 1998 std underspecified function template partial ordering, and
15383    DR214 addresses the issue.  We take pairs of arguments, one from
15384    each of the templates, and deduce them against each other.  One of
15385    the templates will be more specialized if all the *other*
15386    template's arguments deduce against its arguments and at least one
15387    of its arguments *does* *not* deduce against the other template's
15388    corresponding argument.  Deduction is done as for class templates.
15389    The arguments used in deduction have reference and top level cv
15390    qualifiers removed.  Iff both arguments were originally reference
15391    types *and* deduction succeeds in both directions, the template
15392    with the more cv-qualified argument wins for that pairing (if
15393    neither is more cv-qualified, they both are equal).  Unlike regular
15394    deduction, after all the arguments have been deduced in this way,
15395    we do *not* verify the deduced template argument values can be
15396    substituted into non-deduced contexts.
15397
15398    The logic can be a bit confusing here, because we look at deduce1 and
15399    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15400    can find template arguments for pat1 to make arg1 look like arg2, that
15401    means that arg2 is at least as specialized as arg1.  */
15402
15403 int
15404 more_specialized_fn (tree pat1, tree pat2, int len)
15405 {
15406   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15407   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15408   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15409   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15410   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15411   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15412   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15413   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15414   tree origs1, origs2;
15415   bool lose1 = false;
15416   bool lose2 = false;
15417
15418   /* Remove the this parameter from non-static member functions.  If
15419      one is a non-static member function and the other is not a static
15420      member function, remove the first parameter from that function
15421      also.  This situation occurs for operator functions where we
15422      locate both a member function (with this pointer) and non-member
15423      operator (with explicit first operand).  */
15424   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15425     {
15426       len--; /* LEN is the number of significant arguments for DECL1 */
15427       args1 = TREE_CHAIN (args1);
15428       if (!DECL_STATIC_FUNCTION_P (decl2))
15429         args2 = TREE_CHAIN (args2);
15430     }
15431   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15432     {
15433       args2 = TREE_CHAIN (args2);
15434       if (!DECL_STATIC_FUNCTION_P (decl1))
15435         {
15436           len--;
15437           args1 = TREE_CHAIN (args1);
15438         }
15439     }
15440
15441   /* If only one is a conversion operator, they are unordered.  */
15442   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15443     return 0;
15444
15445   /* Consider the return type for a conversion function */
15446   if (DECL_CONV_FN_P (decl1))
15447     {
15448       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15449       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15450       len++;
15451     }
15452
15453   processing_template_decl++;
15454
15455   origs1 = args1;
15456   origs2 = args2;
15457
15458   while (len--
15459          /* Stop when an ellipsis is seen.  */
15460          && args1 != NULL_TREE && args2 != NULL_TREE)
15461     {
15462       tree arg1 = TREE_VALUE (args1);
15463       tree arg2 = TREE_VALUE (args2);
15464       int deduce1, deduce2;
15465       int quals1 = -1;
15466       int quals2 = -1;
15467
15468       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15469           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15470         {
15471           /* When both arguments are pack expansions, we need only
15472              unify the patterns themselves.  */
15473           arg1 = PACK_EXPANSION_PATTERN (arg1);
15474           arg2 = PACK_EXPANSION_PATTERN (arg2);
15475
15476           /* This is the last comparison we need to do.  */
15477           len = 0;
15478         }
15479
15480       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15481         {
15482           arg1 = TREE_TYPE (arg1);
15483           quals1 = cp_type_quals (arg1);
15484         }
15485
15486       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15487         {
15488           arg2 = TREE_TYPE (arg2);
15489           quals2 = cp_type_quals (arg2);
15490         }
15491
15492       if ((quals1 < 0) != (quals2 < 0))
15493         {
15494           /* Only of the args is a reference, see if we should apply
15495              array/function pointer decay to it.  This is not part of
15496              DR214, but is, IMHO, consistent with the deduction rules
15497              for the function call itself, and with our earlier
15498              implementation of the underspecified partial ordering
15499              rules.  (nathan).  */
15500           if (quals1 >= 0)
15501             {
15502               switch (TREE_CODE (arg1))
15503                 {
15504                 case ARRAY_TYPE:
15505                   arg1 = TREE_TYPE (arg1);
15506                   /* FALLTHROUGH. */
15507                 case FUNCTION_TYPE:
15508                   arg1 = build_pointer_type (arg1);
15509                   break;
15510
15511                 default:
15512                   break;
15513                 }
15514             }
15515           else
15516             {
15517               switch (TREE_CODE (arg2))
15518                 {
15519                 case ARRAY_TYPE:
15520                   arg2 = TREE_TYPE (arg2);
15521                   /* FALLTHROUGH. */
15522                 case FUNCTION_TYPE:
15523                   arg2 = build_pointer_type (arg2);
15524                   break;
15525
15526                 default:
15527                   break;
15528                 }
15529             }
15530         }
15531
15532       arg1 = TYPE_MAIN_VARIANT (arg1);
15533       arg2 = TYPE_MAIN_VARIANT (arg2);
15534
15535       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15536         {
15537           int i, len2 = list_length (args2);
15538           tree parmvec = make_tree_vec (1);
15539           tree argvec = make_tree_vec (len2);
15540           tree ta = args2;
15541
15542           /* Setup the parameter vector, which contains only ARG1.  */
15543           TREE_VEC_ELT (parmvec, 0) = arg1;
15544
15545           /* Setup the argument vector, which contains the remaining
15546              arguments.  */
15547           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15548             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15549
15550           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15551                                            argvec, UNIFY_ALLOW_NONE, 
15552                                            /*call_args_p=*/false, 
15553                                            /*subr=*/0);
15554
15555           /* We cannot deduce in the other direction, because ARG1 is
15556              a pack expansion but ARG2 is not.  */
15557           deduce2 = 0;
15558         }
15559       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15560         {
15561           int i, len1 = list_length (args1);
15562           tree parmvec = make_tree_vec (1);
15563           tree argvec = make_tree_vec (len1);
15564           tree ta = args1;
15565
15566           /* Setup the parameter vector, which contains only ARG1.  */
15567           TREE_VEC_ELT (parmvec, 0) = arg2;
15568
15569           /* Setup the argument vector, which contains the remaining
15570              arguments.  */
15571           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15572             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15573
15574           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15575                                            argvec, UNIFY_ALLOW_NONE, 
15576                                            /*call_args_p=*/false, 
15577                                            /*subr=*/0);
15578
15579           /* We cannot deduce in the other direction, because ARG2 is
15580              a pack expansion but ARG1 is not.*/
15581           deduce1 = 0;
15582         }
15583
15584       else
15585         {
15586           /* The normal case, where neither argument is a pack
15587              expansion.  */
15588           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15589           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15590         }
15591
15592       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15593          arg2, then arg2 is not as specialized as arg1.  */
15594       if (!deduce1)
15595         lose2 = true;
15596       if (!deduce2)
15597         lose1 = true;
15598
15599       /* "If, for a given type, deduction succeeds in both directions
15600          (i.e., the types are identical after the transformations above)
15601          and if the type from the argument template is more cv-qualified
15602          than the type from the parameter template (as described above)
15603          that type is considered to be more specialized than the other. If
15604          neither type is more cv-qualified than the other then neither type
15605          is more specialized than the other."  */
15606
15607       if (deduce1 && deduce2
15608           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
15609         {
15610           if ((quals1 & quals2) == quals2)
15611             lose2 = true;
15612           if ((quals1 & quals2) == quals1)
15613             lose1 = true;
15614         }
15615
15616       if (lose1 && lose2)
15617         /* We've failed to deduce something in either direction.
15618            These must be unordered.  */
15619         break;
15620
15621       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15622           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15623         /* We have already processed all of the arguments in our
15624            handing of the pack expansion type.  */
15625         len = 0;
15626
15627       args1 = TREE_CHAIN (args1);
15628       args2 = TREE_CHAIN (args2);
15629     }
15630
15631   /* "In most cases, all template parameters must have values in order for
15632      deduction to succeed, but for partial ordering purposes a template
15633      parameter may remain without a value provided it is not used in the
15634      types being used for partial ordering."
15635
15636      Thus, if we are missing any of the targs1 we need to substitute into
15637      origs1, then pat2 is not as specialized as pat1.  This can happen when
15638      there is a nondeduced context.  */
15639   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15640     lose2 = true;
15641   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15642     lose1 = true;
15643
15644   processing_template_decl--;
15645
15646   /* All things being equal, if the next argument is a pack expansion
15647      for one function but not for the other, prefer the
15648      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15649   if (lose1 == lose2
15650       && args1 && TREE_VALUE (args1)
15651       && args2 && TREE_VALUE (args2))
15652     {
15653       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15654       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15655     }
15656
15657   if (lose1 == lose2)
15658     return 0;
15659   else if (!lose1)
15660     return 1;
15661   else
15662     return -1;
15663 }
15664
15665 /* Determine which of two partial specializations is more specialized.
15666
15667    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15668    to the first partial specialization.  The TREE_VALUE is the
15669    innermost set of template parameters for the partial
15670    specialization.  PAT2 is similar, but for the second template.
15671
15672    Return 1 if the first partial specialization is more specialized;
15673    -1 if the second is more specialized; 0 if neither is more
15674    specialized.
15675
15676    See [temp.class.order] for information about determining which of
15677    two templates is more specialized.  */
15678
15679 static int
15680 more_specialized_class (tree pat1, tree pat2)
15681 {
15682   tree targs;
15683   tree tmpl1, tmpl2;
15684   int winner = 0;
15685   bool any_deductions = false;
15686
15687   tmpl1 = TREE_TYPE (pat1);
15688   tmpl2 = TREE_TYPE (pat2);
15689
15690   /* Just like what happens for functions, if we are ordering between
15691      different class template specializations, we may encounter dependent
15692      types in the arguments, and we need our dependency check functions
15693      to behave correctly.  */
15694   ++processing_template_decl;
15695   targs = get_class_bindings (TREE_VALUE (pat1),
15696                               CLASSTYPE_TI_ARGS (tmpl1),
15697                               CLASSTYPE_TI_ARGS (tmpl2));
15698   if (targs)
15699     {
15700       --winner;
15701       any_deductions = true;
15702     }
15703
15704   targs = get_class_bindings (TREE_VALUE (pat2),
15705                               CLASSTYPE_TI_ARGS (tmpl2),
15706                               CLASSTYPE_TI_ARGS (tmpl1));
15707   if (targs)
15708     {
15709       ++winner;
15710       any_deductions = true;
15711     }
15712   --processing_template_decl;
15713
15714   /* In the case of a tie where at least one of the class templates
15715      has a parameter pack at the end, the template with the most
15716      non-packed parameters wins.  */
15717   if (winner == 0
15718       && any_deductions
15719       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15720           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15721     {
15722       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15723       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15724       int len1 = TREE_VEC_LENGTH (args1);
15725       int len2 = TREE_VEC_LENGTH (args2);
15726
15727       /* We don't count the pack expansion at the end.  */
15728       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15729         --len1;
15730       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15731         --len2;
15732
15733       if (len1 > len2)
15734         return 1;
15735       else if (len1 < len2)
15736         return -1;
15737     }
15738
15739   return winner;
15740 }
15741
15742 /* Return the template arguments that will produce the function signature
15743    DECL from the function template FN, with the explicit template
15744    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15745    also match.  Return NULL_TREE if no satisfactory arguments could be
15746    found.  */
15747
15748 static tree
15749 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15750 {
15751   int ntparms = DECL_NTPARMS (fn);
15752   tree targs = make_tree_vec (ntparms);
15753   tree decl_type;
15754   tree decl_arg_types;
15755   tree *args;
15756   unsigned int nargs, ix;
15757   tree arg;
15758
15759   /* Substitute the explicit template arguments into the type of DECL.
15760      The call to fn_type_unification will handle substitution into the
15761      FN.  */
15762   decl_type = TREE_TYPE (decl);
15763   if (explicit_args && uses_template_parms (decl_type))
15764     {
15765       tree tmpl;
15766       tree converted_args;
15767
15768       if (DECL_TEMPLATE_INFO (decl))
15769         tmpl = DECL_TI_TEMPLATE (decl);
15770       else
15771         /* We can get here for some invalid specializations.  */
15772         return NULL_TREE;
15773
15774       converted_args
15775         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15776                                  explicit_args, NULL_TREE,
15777                                  tf_none,
15778                                  /*require_all_args=*/false,
15779                                  /*use_default_args=*/false);
15780       if (converted_args == error_mark_node)
15781         return NULL_TREE;
15782
15783       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15784       if (decl_type == error_mark_node)
15785         return NULL_TREE;
15786     }
15787
15788   /* Never do unification on the 'this' parameter.  */
15789   decl_arg_types = skip_artificial_parms_for (decl, 
15790                                               TYPE_ARG_TYPES (decl_type));
15791
15792   nargs = list_length (decl_arg_types);
15793   args = XALLOCAVEC (tree, nargs);
15794   for (arg = decl_arg_types, ix = 0;
15795        arg != NULL_TREE && arg != void_list_node;
15796        arg = TREE_CHAIN (arg), ++ix)
15797     args[ix] = TREE_VALUE (arg);
15798
15799   if (fn_type_unification (fn, explicit_args, targs,
15800                            args, ix,
15801                            (check_rettype || DECL_CONV_FN_P (fn)
15802                             ? TREE_TYPE (decl_type) : NULL_TREE),
15803                            DEDUCE_EXACT, LOOKUP_NORMAL))
15804     return NULL_TREE;
15805
15806   return targs;
15807 }
15808
15809 /* Return the innermost template arguments that, when applied to a
15810    template specialization whose innermost template parameters are
15811    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15812    ARGS.
15813
15814    For example, suppose we have:
15815
15816      template <class T, class U> struct S {};
15817      template <class T> struct S<T*, int> {};
15818
15819    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15820    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15821    int}.  The resulting vector will be {double}, indicating that `T'
15822    is bound to `double'.  */
15823
15824 static tree
15825 get_class_bindings (tree tparms, tree spec_args, tree args)
15826 {
15827   int i, ntparms = TREE_VEC_LENGTH (tparms);
15828   tree deduced_args;
15829   tree innermost_deduced_args;
15830
15831   innermost_deduced_args = make_tree_vec (ntparms);
15832   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15833     {
15834       deduced_args = copy_node (args);
15835       SET_TMPL_ARGS_LEVEL (deduced_args,
15836                            TMPL_ARGS_DEPTH (deduced_args),
15837                            innermost_deduced_args);
15838     }
15839   else
15840     deduced_args = innermost_deduced_args;
15841
15842   if (unify (tparms, deduced_args,
15843              INNERMOST_TEMPLATE_ARGS (spec_args),
15844              INNERMOST_TEMPLATE_ARGS (args),
15845              UNIFY_ALLOW_NONE))
15846     return NULL_TREE;
15847
15848   for (i =  0; i < ntparms; ++i)
15849     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15850       return NULL_TREE;
15851
15852   /* Verify that nondeduced template arguments agree with the type
15853      obtained from argument deduction.
15854
15855      For example:
15856
15857        struct A { typedef int X; };
15858        template <class T, class U> struct C {};
15859        template <class T> struct C<T, typename T::X> {};
15860
15861      Then with the instantiation `C<A, int>', we can deduce that
15862      `T' is `A' but unify () does not check whether `typename T::X'
15863      is `int'.  */
15864   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15865   if (spec_args == error_mark_node
15866       /* We only need to check the innermost arguments; the other
15867          arguments will always agree.  */
15868       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15869                               INNERMOST_TEMPLATE_ARGS (args)))
15870     return NULL_TREE;
15871
15872   /* Now that we have bindings for all of the template arguments,
15873      ensure that the arguments deduced for the template template
15874      parameters have compatible template parameter lists.  See the use
15875      of template_template_parm_bindings_ok_p in fn_type_unification
15876      for more information.  */
15877   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15878     return NULL_TREE;
15879
15880   return deduced_args;
15881 }
15882
15883 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15884    Return the TREE_LIST node with the most specialized template, if
15885    any.  If there is no most specialized template, the error_mark_node
15886    is returned.
15887
15888    Note that this function does not look at, or modify, the
15889    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15890    returned is one of the elements of INSTANTIATIONS, callers may
15891    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15892    and retrieve it from the value returned.  */
15893
15894 tree
15895 most_specialized_instantiation (tree templates)
15896 {
15897   tree fn, champ;
15898
15899   ++processing_template_decl;
15900
15901   champ = templates;
15902   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15903     {
15904       int fate = 0;
15905
15906       if (get_bindings (TREE_VALUE (champ),
15907                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15908                         NULL_TREE, /*check_ret=*/false))
15909         fate--;
15910
15911       if (get_bindings (TREE_VALUE (fn),
15912                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15913                         NULL_TREE, /*check_ret=*/false))
15914         fate++;
15915
15916       if (fate == -1)
15917         champ = fn;
15918       else if (!fate)
15919         {
15920           /* Equally specialized, move to next function.  If there
15921              is no next function, nothing's most specialized.  */
15922           fn = TREE_CHAIN (fn);
15923           champ = fn;
15924           if (!fn)
15925             break;
15926         }
15927     }
15928
15929   if (champ)
15930     /* Now verify that champ is better than everything earlier in the
15931        instantiation list.  */
15932     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15933       if (get_bindings (TREE_VALUE (champ),
15934                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15935                         NULL_TREE, /*check_ret=*/false)
15936           || !get_bindings (TREE_VALUE (fn),
15937                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15938                             NULL_TREE, /*check_ret=*/false))
15939         {
15940           champ = NULL_TREE;
15941           break;
15942         }
15943
15944   processing_template_decl--;
15945
15946   if (!champ)
15947     return error_mark_node;
15948
15949   return champ;
15950 }
15951
15952 /* If DECL is a specialization of some template, return the most
15953    general such template.  Otherwise, returns NULL_TREE.
15954
15955    For example, given:
15956
15957      template <class T> struct S { template <class U> void f(U); };
15958
15959    if TMPL is `template <class U> void S<int>::f(U)' this will return
15960    the full template.  This function will not trace past partial
15961    specializations, however.  For example, given in addition:
15962
15963      template <class T> struct S<T*> { template <class U> void f(U); };
15964
15965    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15966    `template <class T> template <class U> S<T*>::f(U)'.  */
15967
15968 tree
15969 most_general_template (tree decl)
15970 {
15971   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15972      an immediate specialization.  */
15973   if (TREE_CODE (decl) == FUNCTION_DECL)
15974     {
15975       if (DECL_TEMPLATE_INFO (decl)) {
15976         decl = DECL_TI_TEMPLATE (decl);
15977
15978         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15979            template friend.  */
15980         if (TREE_CODE (decl) != TEMPLATE_DECL)
15981           return NULL_TREE;
15982       } else
15983         return NULL_TREE;
15984     }
15985
15986   /* Look for more and more general templates.  */
15987   while (DECL_TEMPLATE_INFO (decl))
15988     {
15989       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15990          (See cp-tree.h for details.)  */
15991       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15992         break;
15993
15994       if (CLASS_TYPE_P (TREE_TYPE (decl))
15995           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15996         break;
15997
15998       /* Stop if we run into an explicitly specialized class template.  */
15999       if (!DECL_NAMESPACE_SCOPE_P (decl)
16000           && DECL_CONTEXT (decl)
16001           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
16002         break;
16003
16004       decl = DECL_TI_TEMPLATE (decl);
16005     }
16006
16007   return decl;
16008 }
16009
16010 /* Return the most specialized of the class template partial
16011    specializations of TMPL which can produce TYPE, a specialization of
16012    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
16013    a _TYPE node corresponding to the partial specialization, while the
16014    TREE_PURPOSE is the set of template arguments that must be
16015    substituted into the TREE_TYPE in order to generate TYPE.
16016
16017    If the choice of partial specialization is ambiguous, a diagnostic
16018    is issued, and the error_mark_node is returned.  If there are no
16019    partial specializations of TMPL matching TYPE, then NULL_TREE is
16020    returned.  */
16021
16022 static tree
16023 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
16024 {
16025   tree list = NULL_TREE;
16026   tree t;
16027   tree champ;
16028   int fate;
16029   bool ambiguous_p;
16030   tree args;
16031   tree outer_args = NULL_TREE;
16032
16033   tmpl = most_general_template (tmpl);
16034   args = CLASSTYPE_TI_ARGS (type);
16035
16036   /* For determining which partial specialization to use, only the
16037      innermost args are interesting.  */
16038   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16039     {
16040       outer_args = strip_innermost_template_args (args, 1);
16041       args = INNERMOST_TEMPLATE_ARGS (args);
16042     }
16043
16044   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
16045     {
16046       tree partial_spec_args;
16047       tree spec_args;
16048       tree parms = TREE_VALUE (t);
16049
16050       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
16051
16052       ++processing_template_decl;
16053
16054       if (outer_args)
16055         {
16056           int i;
16057
16058           /* Discard the outer levels of args, and then substitute in the
16059              template args from the enclosing class.  */
16060           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
16061           partial_spec_args = tsubst_template_args
16062             (partial_spec_args, outer_args, tf_none, NULL_TREE);
16063
16064           /* PARMS already refers to just the innermost parms, but the
16065              template parms in partial_spec_args had their levels lowered
16066              by tsubst, so we need to do the same for the parm list.  We
16067              can't just tsubst the TREE_VEC itself, as tsubst wants to
16068              treat a TREE_VEC as an argument vector.  */
16069           parms = copy_node (parms);
16070           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
16071             TREE_VEC_ELT (parms, i) =
16072               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
16073
16074         }
16075
16076       partial_spec_args =
16077           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16078                                  add_to_template_args (outer_args,
16079                                                        partial_spec_args),
16080                                  tmpl, tf_none,
16081                                  /*require_all_args=*/true,
16082                                  /*use_default_args=*/true);
16083
16084       --processing_template_decl;
16085
16086       if (partial_spec_args == error_mark_node)
16087         return error_mark_node;
16088
16089       spec_args = get_class_bindings (parms,
16090                                       partial_spec_args,
16091                                       args);
16092       if (spec_args)
16093         {
16094           if (outer_args)
16095             spec_args = add_to_template_args (outer_args, spec_args);
16096           list = tree_cons (spec_args, TREE_VALUE (t), list);
16097           TREE_TYPE (list) = TREE_TYPE (t);
16098         }
16099     }
16100
16101   if (! list)
16102     return NULL_TREE;
16103
16104   ambiguous_p = false;
16105   t = list;
16106   champ = t;
16107   t = TREE_CHAIN (t);
16108   for (; t; t = TREE_CHAIN (t))
16109     {
16110       fate = more_specialized_class (champ, t);
16111       if (fate == 1)
16112         ;
16113       else
16114         {
16115           if (fate == 0)
16116             {
16117               t = TREE_CHAIN (t);
16118               if (! t)
16119                 {
16120                   ambiguous_p = true;
16121                   break;
16122                 }
16123             }
16124           champ = t;
16125         }
16126     }
16127
16128   if (!ambiguous_p)
16129     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16130       {
16131         fate = more_specialized_class (champ, t);
16132         if (fate != 1)
16133           {
16134             ambiguous_p = true;
16135             break;
16136           }
16137       }
16138
16139   if (ambiguous_p)
16140     {
16141       const char *str;
16142       char *spaces = NULL;
16143       if (!(complain & tf_error))
16144         return error_mark_node;
16145       error ("ambiguous class template instantiation for %q#T", type);
16146       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
16147       for (t = list; t; t = TREE_CHAIN (t))
16148         {
16149           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16150           spaces = spaces ? spaces : get_spaces (str);
16151         }
16152       free (spaces);
16153       return error_mark_node;
16154     }
16155
16156   return champ;
16157 }
16158
16159 /* Explicitly instantiate DECL.  */
16160
16161 void
16162 do_decl_instantiation (tree decl, tree storage)
16163 {
16164   tree result = NULL_TREE;
16165   int extern_p = 0;
16166
16167   if (!decl || decl == error_mark_node)
16168     /* An error occurred, for which grokdeclarator has already issued
16169        an appropriate message.  */
16170     return;
16171   else if (! DECL_LANG_SPECIFIC (decl))
16172     {
16173       error ("explicit instantiation of non-template %q#D", decl);
16174       return;
16175     }
16176   else if (TREE_CODE (decl) == VAR_DECL)
16177     {
16178       /* There is an asymmetry here in the way VAR_DECLs and
16179          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16180          the latter, the DECL we get back will be marked as a
16181          template instantiation, and the appropriate
16182          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16183          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16184          should handle VAR_DECLs as it currently handles
16185          FUNCTION_DECLs.  */
16186       if (!DECL_CLASS_SCOPE_P (decl))
16187         {
16188           error ("%qD is not a static data member of a class template", decl);
16189           return;
16190         }
16191       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16192       if (!result || TREE_CODE (result) != VAR_DECL)
16193         {
16194           error ("no matching template for %qD found", decl);
16195           return;
16196         }
16197       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16198         {
16199           error ("type %qT for explicit instantiation %qD does not match "
16200                  "declared type %qT", TREE_TYPE (result), decl,
16201                  TREE_TYPE (decl));
16202           return;
16203         }
16204     }
16205   else if (TREE_CODE (decl) != FUNCTION_DECL)
16206     {
16207       error ("explicit instantiation of %q#D", decl);
16208       return;
16209     }
16210   else
16211     result = decl;
16212
16213   /* Check for various error cases.  Note that if the explicit
16214      instantiation is valid the RESULT will currently be marked as an
16215      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16216      until we get here.  */
16217
16218   if (DECL_TEMPLATE_SPECIALIZATION (result))
16219     {
16220       /* DR 259 [temp.spec].
16221
16222          Both an explicit instantiation and a declaration of an explicit
16223          specialization shall not appear in a program unless the explicit
16224          instantiation follows a declaration of the explicit specialization.
16225
16226          For a given set of template parameters, if an explicit
16227          instantiation of a template appears after a declaration of an
16228          explicit specialization for that template, the explicit
16229          instantiation has no effect.  */
16230       return;
16231     }
16232   else if (DECL_EXPLICIT_INSTANTIATION (result))
16233     {
16234       /* [temp.spec]
16235
16236          No program shall explicitly instantiate any template more
16237          than once.
16238
16239          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16240          the first instantiation was `extern' and the second is not,
16241          and EXTERN_P for the opposite case.  */
16242       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16243         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16244       /* If an "extern" explicit instantiation follows an ordinary
16245          explicit instantiation, the template is instantiated.  */
16246       if (extern_p)
16247         return;
16248     }
16249   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16250     {
16251       error ("no matching template for %qD found", result);
16252       return;
16253     }
16254   else if (!DECL_TEMPLATE_INFO (result))
16255     {
16256       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16257       return;
16258     }
16259
16260   if (storage == NULL_TREE)
16261     ;
16262   else if (storage == ridpointers[(int) RID_EXTERN])
16263     {
16264       if (!in_system_header && (cxx_dialect == cxx98))
16265         pedwarn (input_location, OPT_pedantic, 
16266                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16267                  "instantiations");
16268       extern_p = 1;
16269     }
16270   else
16271     error ("storage class %qD applied to template instantiation", storage);
16272
16273   check_explicit_instantiation_namespace (result);
16274   mark_decl_instantiated (result, extern_p);
16275   if (! extern_p)
16276     instantiate_decl (result, /*defer_ok=*/1,
16277                       /*expl_inst_class_mem_p=*/false);
16278 }
16279
16280 static void
16281 mark_class_instantiated (tree t, int extern_p)
16282 {
16283   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16284   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16285   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16286   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16287   if (! extern_p)
16288     {
16289       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16290       rest_of_type_compilation (t, 1);
16291     }
16292 }
16293
16294 /* Called from do_type_instantiation through binding_table_foreach to
16295    do recursive instantiation for the type bound in ENTRY.  */
16296 static void
16297 bt_instantiate_type_proc (binding_entry entry, void *data)
16298 {
16299   tree storage = *(tree *) data;
16300
16301   if (MAYBE_CLASS_TYPE_P (entry->type)
16302       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16303     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16304 }
16305
16306 /* Called from do_type_instantiation to instantiate a member
16307    (a member function or a static member variable) of an
16308    explicitly instantiated class template.  */
16309 static void
16310 instantiate_class_member (tree decl, int extern_p)
16311 {
16312   mark_decl_instantiated (decl, extern_p);
16313   if (! extern_p)
16314     instantiate_decl (decl, /*defer_ok=*/1,
16315                       /*expl_inst_class_mem_p=*/true);
16316 }
16317
16318 /* Perform an explicit instantiation of template class T.  STORAGE, if
16319    non-null, is the RID for extern, inline or static.  COMPLAIN is
16320    nonzero if this is called from the parser, zero if called recursively,
16321    since the standard is unclear (as detailed below).  */
16322
16323 void
16324 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16325 {
16326   int extern_p = 0;
16327   int nomem_p = 0;
16328   int static_p = 0;
16329   int previous_instantiation_extern_p = 0;
16330
16331   if (TREE_CODE (t) == TYPE_DECL)
16332     t = TREE_TYPE (t);
16333
16334   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16335     {
16336       error ("explicit instantiation of non-template type %qT", t);
16337       return;
16338     }
16339
16340   complete_type (t);
16341
16342   if (!COMPLETE_TYPE_P (t))
16343     {
16344       if (complain & tf_error)
16345         error ("explicit instantiation of %q#T before definition of template",
16346                t);
16347       return;
16348     }
16349
16350   if (storage != NULL_TREE)
16351     {
16352       if (!in_system_header)
16353         {
16354           if (storage == ridpointers[(int) RID_EXTERN])
16355             {
16356               if (cxx_dialect == cxx98)
16357                 pedwarn (input_location, OPT_pedantic, 
16358                          "ISO C++ 1998 forbids the use of %<extern%> on "
16359                          "explicit instantiations");
16360             }
16361           else
16362             pedwarn (input_location, OPT_pedantic, 
16363                      "ISO C++ forbids the use of %qE"
16364                      " on explicit instantiations", storage);
16365         }
16366
16367       if (storage == ridpointers[(int) RID_INLINE])
16368         nomem_p = 1;
16369       else if (storage == ridpointers[(int) RID_EXTERN])
16370         extern_p = 1;
16371       else if (storage == ridpointers[(int) RID_STATIC])
16372         static_p = 1;
16373       else
16374         {
16375           error ("storage class %qD applied to template instantiation",
16376                  storage);
16377           extern_p = 0;
16378         }
16379     }
16380
16381   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16382     {
16383       /* DR 259 [temp.spec].
16384
16385          Both an explicit instantiation and a declaration of an explicit
16386          specialization shall not appear in a program unless the explicit
16387          instantiation follows a declaration of the explicit specialization.
16388
16389          For a given set of template parameters, if an explicit
16390          instantiation of a template appears after a declaration of an
16391          explicit specialization for that template, the explicit
16392          instantiation has no effect.  */
16393       return;
16394     }
16395   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16396     {
16397       /* [temp.spec]
16398
16399          No program shall explicitly instantiate any template more
16400          than once.
16401
16402          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16403          instantiation was `extern'.  If EXTERN_P then the second is.
16404          These cases are OK.  */
16405       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16406
16407       if (!previous_instantiation_extern_p && !extern_p
16408           && (complain & tf_error))
16409         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16410
16411       /* If we've already instantiated the template, just return now.  */
16412       if (!CLASSTYPE_INTERFACE_ONLY (t))
16413         return;
16414     }
16415
16416   check_explicit_instantiation_namespace (TYPE_NAME (t));
16417   mark_class_instantiated (t, extern_p);
16418
16419   if (nomem_p)
16420     return;
16421
16422   {
16423     tree tmp;
16424
16425     /* In contrast to implicit instantiation, where only the
16426        declarations, and not the definitions, of members are
16427        instantiated, we have here:
16428
16429          [temp.explicit]
16430
16431          The explicit instantiation of a class template specialization
16432          implies the instantiation of all of its members not
16433          previously explicitly specialized in the translation unit
16434          containing the explicit instantiation.
16435
16436        Of course, we can't instantiate member template classes, since
16437        we don't have any arguments for them.  Note that the standard
16438        is unclear on whether the instantiation of the members are
16439        *explicit* instantiations or not.  However, the most natural
16440        interpretation is that it should be an explicit instantiation.  */
16441
16442     if (! static_p)
16443       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
16444         if (TREE_CODE (tmp) == FUNCTION_DECL
16445             && DECL_TEMPLATE_INSTANTIATION (tmp))
16446           instantiate_class_member (tmp, extern_p);
16447
16448     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
16449       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16450         instantiate_class_member (tmp, extern_p);
16451
16452     if (CLASSTYPE_NESTED_UTDS (t))
16453       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16454                              bt_instantiate_type_proc, &storage);
16455   }
16456 }
16457
16458 /* Given a function DECL, which is a specialization of TMPL, modify
16459    DECL to be a re-instantiation of TMPL with the same template
16460    arguments.  TMPL should be the template into which tsubst'ing
16461    should occur for DECL, not the most general template.
16462
16463    One reason for doing this is a scenario like this:
16464
16465      template <class T>
16466      void f(const T&, int i);
16467
16468      void g() { f(3, 7); }
16469
16470      template <class T>
16471      void f(const T& t, const int i) { }
16472
16473    Note that when the template is first instantiated, with
16474    instantiate_template, the resulting DECL will have no name for the
16475    first parameter, and the wrong type for the second.  So, when we go
16476    to instantiate the DECL, we regenerate it.  */
16477
16478 static void
16479 regenerate_decl_from_template (tree decl, tree tmpl)
16480 {
16481   /* The arguments used to instantiate DECL, from the most general
16482      template.  */
16483   tree args;
16484   tree code_pattern;
16485
16486   args = DECL_TI_ARGS (decl);
16487   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16488
16489   /* Make sure that we can see identifiers, and compute access
16490      correctly.  */
16491   push_access_scope (decl);
16492
16493   if (TREE_CODE (decl) == FUNCTION_DECL)
16494     {
16495       tree decl_parm;
16496       tree pattern_parm;
16497       tree specs;
16498       int args_depth;
16499       int parms_depth;
16500
16501       args_depth = TMPL_ARGS_DEPTH (args);
16502       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16503       if (args_depth > parms_depth)
16504         args = get_innermost_template_args (args, parms_depth);
16505
16506       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16507                                               args, tf_error, NULL_TREE);
16508       if (specs)
16509         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16510                                                     specs);
16511
16512       /* Merge parameter declarations.  */
16513       decl_parm = skip_artificial_parms_for (decl,
16514                                              DECL_ARGUMENTS (decl));
16515       pattern_parm
16516         = skip_artificial_parms_for (code_pattern,
16517                                      DECL_ARGUMENTS (code_pattern));
16518       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16519         {
16520           tree parm_type;
16521           tree attributes;
16522           
16523           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16524             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16525           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16526                               NULL_TREE);
16527           parm_type = type_decays_to (parm_type);
16528           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16529             TREE_TYPE (decl_parm) = parm_type;
16530           attributes = DECL_ATTRIBUTES (pattern_parm);
16531           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16532             {
16533               DECL_ATTRIBUTES (decl_parm) = attributes;
16534               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16535             }
16536           decl_parm = DECL_CHAIN (decl_parm);
16537           pattern_parm = DECL_CHAIN (pattern_parm);
16538         }
16539       /* Merge any parameters that match with the function parameter
16540          pack.  */
16541       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16542         {
16543           int i, len;
16544           tree expanded_types;
16545           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16546              the parameters in this function parameter pack.  */
16547           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16548                                                  args, tf_error, NULL_TREE);
16549           len = TREE_VEC_LENGTH (expanded_types);
16550           for (i = 0; i < len; i++)
16551             {
16552               tree parm_type;
16553               tree attributes;
16554           
16555               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16556                 /* Rename the parameter to include the index.  */
16557                 DECL_NAME (decl_parm) = 
16558                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16559               parm_type = TREE_VEC_ELT (expanded_types, i);
16560               parm_type = type_decays_to (parm_type);
16561               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16562                 TREE_TYPE (decl_parm) = parm_type;
16563               attributes = DECL_ATTRIBUTES (pattern_parm);
16564               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16565                 {
16566                   DECL_ATTRIBUTES (decl_parm) = attributes;
16567                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16568                 }
16569               decl_parm = DECL_CHAIN (decl_parm);
16570             }
16571         }
16572       /* Merge additional specifiers from the CODE_PATTERN.  */
16573       if (DECL_DECLARED_INLINE_P (code_pattern)
16574           && !DECL_DECLARED_INLINE_P (decl))
16575         DECL_DECLARED_INLINE_P (decl) = 1;
16576     }
16577   else if (TREE_CODE (decl) == VAR_DECL)
16578     {
16579       DECL_INITIAL (decl) =
16580         tsubst_expr (DECL_INITIAL (code_pattern), args,
16581                      tf_error, DECL_TI_TEMPLATE (decl),
16582                      /*integral_constant_expression_p=*/false);
16583       if (VAR_HAD_UNKNOWN_BOUND (decl))
16584         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
16585                                    tf_error, DECL_TI_TEMPLATE (decl));
16586     }
16587   else
16588     gcc_unreachable ();
16589
16590   pop_access_scope (decl);
16591 }
16592
16593 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16594    substituted to get DECL.  */
16595
16596 tree
16597 template_for_substitution (tree decl)
16598 {
16599   tree tmpl = DECL_TI_TEMPLATE (decl);
16600
16601   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16602      for the instantiation.  This is not always the most general
16603      template.  Consider, for example:
16604
16605         template <class T>
16606         struct S { template <class U> void f();
16607                    template <> void f<int>(); };
16608
16609      and an instantiation of S<double>::f<int>.  We want TD to be the
16610      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16611   while (/* An instantiation cannot have a definition, so we need a
16612             more general template.  */
16613          DECL_TEMPLATE_INSTANTIATION (tmpl)
16614            /* We must also deal with friend templates.  Given:
16615
16616                 template <class T> struct S {
16617                   template <class U> friend void f() {};
16618                 };
16619
16620               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16621               so far as the language is concerned, but that's still
16622               where we get the pattern for the instantiation from.  On
16623               other hand, if the definition comes outside the class, say:
16624
16625                 template <class T> struct S {
16626                   template <class U> friend void f();
16627                 };
16628                 template <class U> friend void f() {}
16629
16630               we don't need to look any further.  That's what the check for
16631               DECL_INITIAL is for.  */
16632           || (TREE_CODE (decl) == FUNCTION_DECL
16633               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16634               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16635     {
16636       /* The present template, TD, should not be a definition.  If it
16637          were a definition, we should be using it!  Note that we
16638          cannot restructure the loop to just keep going until we find
16639          a template with a definition, since that might go too far if
16640          a specialization was declared, but not defined.  */
16641       gcc_assert (TREE_CODE (decl) != VAR_DECL
16642                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16643
16644       /* Fetch the more general template.  */
16645       tmpl = DECL_TI_TEMPLATE (tmpl);
16646     }
16647
16648   return tmpl;
16649 }
16650
16651 /* Returns true if we need to instantiate this template instance even if we
16652    know we aren't going to emit it..  */
16653
16654 bool
16655 always_instantiate_p (tree decl)
16656 {
16657   /* We always instantiate inline functions so that we can inline them.  An
16658      explicit instantiation declaration prohibits implicit instantiation of
16659      non-inline functions.  With high levels of optimization, we would
16660      normally inline non-inline functions -- but we're not allowed to do
16661      that for "extern template" functions.  Therefore, we check
16662      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16663   return ((TREE_CODE (decl) == FUNCTION_DECL
16664            && DECL_DECLARED_INLINE_P (decl))
16665           /* And we need to instantiate static data members so that
16666              their initializers are available in integral constant
16667              expressions.  */
16668           || (TREE_CODE (decl) == VAR_DECL
16669               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16670 }
16671
16672 /* Produce the definition of D, a _DECL generated from a template.  If
16673    DEFER_OK is nonzero, then we don't have to actually do the
16674    instantiation now; we just have to do it sometime.  Normally it is
16675    an error if this is an explicit instantiation but D is undefined.
16676    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16677    explicitly instantiated class template.  */
16678
16679 tree
16680 instantiate_decl (tree d, int defer_ok,
16681                   bool expl_inst_class_mem_p)
16682 {
16683   tree tmpl = DECL_TI_TEMPLATE (d);
16684   tree gen_args;
16685   tree args;
16686   tree td;
16687   tree code_pattern;
16688   tree spec;
16689   tree gen_tmpl;
16690   bool pattern_defined;
16691   int need_push;
16692   location_t saved_loc = input_location;
16693   bool external_p;
16694
16695   /* This function should only be used to instantiate templates for
16696      functions and static member variables.  */
16697   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16698               || TREE_CODE (d) == VAR_DECL);
16699
16700   /* Variables are never deferred; if instantiation is required, they
16701      are instantiated right away.  That allows for better code in the
16702      case that an expression refers to the value of the variable --
16703      if the variable has a constant value the referring expression can
16704      take advantage of that fact.  */
16705   if (TREE_CODE (d) == VAR_DECL)
16706     defer_ok = 0;
16707
16708   /* Don't instantiate cloned functions.  Instead, instantiate the
16709      functions they cloned.  */
16710   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16711     d = DECL_CLONED_FUNCTION (d);
16712
16713   if (DECL_TEMPLATE_INSTANTIATED (d)
16714       || DECL_TEMPLATE_SPECIALIZATION (d))
16715     /* D has already been instantiated or explicitly specialized, so
16716        there's nothing for us to do here.
16717
16718        It might seem reasonable to check whether or not D is an explicit
16719        instantiation, and, if so, stop here.  But when an explicit
16720        instantiation is deferred until the end of the compilation,
16721        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16722        the instantiation.  */
16723     return d;
16724
16725   /* Check to see whether we know that this template will be
16726      instantiated in some other file, as with "extern template"
16727      extension.  */
16728   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16729
16730   /* In general, we do not instantiate such templates.  */
16731   if (external_p && !always_instantiate_p (d))
16732     return d;
16733
16734   gen_tmpl = most_general_template (tmpl);
16735   gen_args = DECL_TI_ARGS (d);
16736
16737   if (tmpl != gen_tmpl)
16738     /* We should already have the extra args.  */
16739     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16740                 == TMPL_ARGS_DEPTH (gen_args));
16741   /* And what's in the hash table should match D.  */
16742   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16743               || spec == NULL_TREE);
16744
16745   /* This needs to happen before any tsubsting.  */
16746   if (! push_tinst_level (d))
16747     return d;
16748
16749   timevar_push (TV_PARSE);
16750
16751   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16752      for the instantiation.  */
16753   td = template_for_substitution (d);
16754   code_pattern = DECL_TEMPLATE_RESULT (td);
16755
16756   /* We should never be trying to instantiate a member of a class
16757      template or partial specialization.  */
16758   gcc_assert (d != code_pattern);
16759
16760   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16761       || DECL_TEMPLATE_SPECIALIZATION (td))
16762     /* In the case of a friend template whose definition is provided
16763        outside the class, we may have too many arguments.  Drop the
16764        ones we don't need.  The same is true for specializations.  */
16765     args = get_innermost_template_args
16766       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16767   else
16768     args = gen_args;
16769
16770   if (TREE_CODE (d) == FUNCTION_DECL)
16771     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16772   else
16773     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16774
16775   /* We may be in the middle of deferred access check.  Disable it now.  */
16776   push_deferring_access_checks (dk_no_deferred);
16777
16778   /* Unless an explicit instantiation directive has already determined
16779      the linkage of D, remember that a definition is available for
16780      this entity.  */
16781   if (pattern_defined
16782       && !DECL_INTERFACE_KNOWN (d)
16783       && !DECL_NOT_REALLY_EXTERN (d))
16784     mark_definable (d);
16785
16786   input_location = DECL_SOURCE_LOCATION (d);
16787
16788   /* If D is a member of an explicitly instantiated class template,
16789      and no definition is available, treat it like an implicit
16790      instantiation.  */
16791   if (!pattern_defined && expl_inst_class_mem_p
16792       && DECL_EXPLICIT_INSTANTIATION (d))
16793     {
16794       DECL_NOT_REALLY_EXTERN (d) = 0;
16795       DECL_INTERFACE_KNOWN (d) = 0;
16796       SET_DECL_IMPLICIT_INSTANTIATION (d);
16797     }
16798
16799   /* Recheck the substitutions to obtain any warning messages
16800      about ignoring cv qualifiers.  Don't do this for artificial decls,
16801      as it breaks the context-sensitive substitution for lambda op(). */
16802   if (!defer_ok && !DECL_ARTIFICIAL (d))
16803     {
16804       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16805       tree type = TREE_TYPE (gen);
16806
16807       /* Make sure that we can see identifiers, and compute access
16808          correctly.  D is already the target FUNCTION_DECL with the
16809          right context.  */
16810       push_access_scope (d);
16811
16812       if (TREE_CODE (gen) == FUNCTION_DECL)
16813         {
16814           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16815           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16816                                           d);
16817           /* Don't simply tsubst the function type, as that will give
16818              duplicate warnings about poor parameter qualifications.
16819              The function arguments are the same as the decl_arguments
16820              without the top level cv qualifiers.  */
16821           type = TREE_TYPE (type);
16822         }
16823       tsubst (type, gen_args, tf_warning_or_error, d);
16824
16825       pop_access_scope (d);
16826     }
16827
16828   /* Defer all other templates, unless we have been explicitly
16829      forbidden from doing so.  */
16830   if (/* If there is no definition, we cannot instantiate the
16831          template.  */
16832       ! pattern_defined
16833       /* If it's OK to postpone instantiation, do so.  */
16834       || defer_ok
16835       /* If this is a static data member that will be defined
16836          elsewhere, we don't want to instantiate the entire data
16837          member, but we do want to instantiate the initializer so that
16838          we can substitute that elsewhere.  */
16839       || (external_p && TREE_CODE (d) == VAR_DECL))
16840     {
16841       /* The definition of the static data member is now required so
16842          we must substitute the initializer.  */
16843       if (TREE_CODE (d) == VAR_DECL
16844           && !DECL_INITIAL (d)
16845           && DECL_INITIAL (code_pattern))
16846         {
16847           tree ns;
16848           tree init;
16849
16850           ns = decl_namespace_context (d);
16851           push_nested_namespace (ns);
16852           push_nested_class (DECL_CONTEXT (d));
16853           init = tsubst_expr (DECL_INITIAL (code_pattern),
16854                               args,
16855                               tf_warning_or_error, NULL_TREE,
16856                               /*integral_constant_expression_p=*/false);
16857           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16858                           /*asmspec_tree=*/NULL_TREE,
16859                           LOOKUP_ONLYCONVERTING);
16860           pop_nested_class ();
16861           pop_nested_namespace (ns);
16862         }
16863
16864       /* We restore the source position here because it's used by
16865          add_pending_template.  */
16866       input_location = saved_loc;
16867
16868       if (at_eof && !pattern_defined
16869           && DECL_EXPLICIT_INSTANTIATION (d)
16870           && DECL_NOT_REALLY_EXTERN (d))
16871         /* [temp.explicit]
16872
16873            The definition of a non-exported function template, a
16874            non-exported member function template, or a non-exported
16875            member function or static data member of a class template
16876            shall be present in every translation unit in which it is
16877            explicitly instantiated.  */
16878         permerror (input_location,  "explicit instantiation of %qD "
16879                    "but no definition available", d);
16880
16881       /* ??? Historically, we have instantiated inline functions, even
16882          when marked as "extern template".  */
16883       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16884         add_pending_template (d);
16885       goto out;
16886     }
16887   /* Tell the repository that D is available in this translation unit
16888      -- and see if it is supposed to be instantiated here.  */
16889   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16890     {
16891       /* In a PCH file, despite the fact that the repository hasn't
16892          requested instantiation in the PCH it is still possible that
16893          an instantiation will be required in a file that includes the
16894          PCH.  */
16895       if (pch_file)
16896         add_pending_template (d);
16897       /* Instantiate inline functions so that the inliner can do its
16898          job, even though we'll not be emitting a copy of this
16899          function.  */
16900       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16901         goto out;
16902     }
16903
16904   need_push = !cfun || !global_bindings_p ();
16905   if (need_push)
16906     push_to_top_level ();
16907
16908   /* Mark D as instantiated so that recursive calls to
16909      instantiate_decl do not try to instantiate it again.  */
16910   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16911
16912   /* Regenerate the declaration in case the template has been modified
16913      by a subsequent redeclaration.  */
16914   regenerate_decl_from_template (d, td);
16915
16916   /* We already set the file and line above.  Reset them now in case
16917      they changed as a result of calling regenerate_decl_from_template.  */
16918   input_location = DECL_SOURCE_LOCATION (d);
16919
16920   if (TREE_CODE (d) == VAR_DECL)
16921     {
16922       tree init;
16923
16924       /* Clear out DECL_RTL; whatever was there before may not be right
16925          since we've reset the type of the declaration.  */
16926       SET_DECL_RTL (d, NULL);
16927       DECL_IN_AGGR_P (d) = 0;
16928
16929       /* The initializer is placed in DECL_INITIAL by
16930          regenerate_decl_from_template.  Pull it out so that
16931          cp_finish_decl can process it.  */
16932       init = DECL_INITIAL (d);
16933       DECL_INITIAL (d) = NULL_TREE;
16934       DECL_INITIALIZED_P (d) = 0;
16935
16936       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16937          initializer.  That function will defer actual emission until
16938          we have a chance to determine linkage.  */
16939       DECL_EXTERNAL (d) = 0;
16940
16941       /* Enter the scope of D so that access-checking works correctly.  */
16942       push_nested_class (DECL_CONTEXT (d));
16943       cp_finish_decl (d, init, false, NULL_TREE, 0);
16944       pop_nested_class ();
16945     }
16946   else if (TREE_CODE (d) == FUNCTION_DECL)
16947     {
16948       htab_t saved_local_specializations;
16949       tree subst_decl;
16950       tree tmpl_parm;
16951       tree spec_parm;
16952
16953       /* Save away the current list, in case we are instantiating one
16954          template from within the body of another.  */
16955       saved_local_specializations = local_specializations;
16956
16957       /* Set up the list of local specializations.  */
16958       local_specializations = htab_create (37,
16959                                            hash_local_specialization,
16960                                            eq_local_specializations,
16961                                            NULL);
16962
16963       /* Set up context.  */
16964       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16965
16966       /* Create substitution entries for the parameters.  */
16967       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16968       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16969       spec_parm = DECL_ARGUMENTS (d);
16970       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16971         {
16972           register_local_specialization (spec_parm, tmpl_parm);
16973           spec_parm = skip_artificial_parms_for (d, spec_parm);
16974           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16975         }
16976       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16977         {
16978           register_local_specialization (spec_parm, tmpl_parm);
16979           tmpl_parm = DECL_CHAIN (tmpl_parm);
16980           spec_parm = DECL_CHAIN (spec_parm);
16981         }
16982       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16983         {
16984           /* Register the (value) argument pack as a specialization of
16985              TMPL_PARM, then move on.  */
16986           tree argpack = make_fnparm_pack (spec_parm);
16987           register_local_specialization (argpack, tmpl_parm);
16988           tmpl_parm = DECL_CHAIN (tmpl_parm);
16989           spec_parm = NULL_TREE;
16990         }
16991       gcc_assert (!spec_parm);
16992
16993       /* Substitute into the body of the function.  */
16994       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16995                    tf_warning_or_error, tmpl,
16996                    /*integral_constant_expression_p=*/false);
16997
16998       /* Set the current input_location to the end of the function
16999          so that finish_function knows where we are.  */
17000       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
17001
17002       /* We don't need the local specializations any more.  */
17003       htab_delete (local_specializations);
17004       local_specializations = saved_local_specializations;
17005
17006       /* Finish the function.  */
17007       d = finish_function (0);
17008       expand_or_defer_fn (d);
17009     }
17010
17011   /* We're not deferring instantiation any more.  */
17012   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
17013
17014   if (need_push)
17015     pop_from_top_level ();
17016
17017 out:
17018   input_location = saved_loc;
17019   pop_deferring_access_checks ();
17020   pop_tinst_level ();
17021
17022   timevar_pop (TV_PARSE);
17023
17024   return d;
17025 }
17026
17027 /* Run through the list of templates that we wish we could
17028    instantiate, and instantiate any we can.  RETRIES is the
17029    number of times we retry pending template instantiation.  */
17030
17031 void
17032 instantiate_pending_templates (int retries)
17033 {
17034   int reconsider;
17035   location_t saved_loc = input_location;
17036
17037   /* Instantiating templates may trigger vtable generation.  This in turn
17038      may require further template instantiations.  We place a limit here
17039      to avoid infinite loop.  */
17040   if (pending_templates && retries >= max_tinst_depth)
17041     {
17042       tree decl = pending_templates->tinst->decl;
17043
17044       error ("template instantiation depth exceeds maximum of %d"
17045              " instantiating %q+D, possibly from virtual table generation"
17046              " (use -ftemplate-depth= to increase the maximum)",
17047              max_tinst_depth, decl);
17048       if (TREE_CODE (decl) == FUNCTION_DECL)
17049         /* Pretend that we defined it.  */
17050         DECL_INITIAL (decl) = error_mark_node;
17051       return;
17052     }
17053
17054   do
17055     {
17056       struct pending_template **t = &pending_templates;
17057       struct pending_template *last = NULL;
17058       reconsider = 0;
17059       while (*t)
17060         {
17061           tree instantiation = reopen_tinst_level ((*t)->tinst);
17062           bool complete = false;
17063
17064           if (TYPE_P (instantiation))
17065             {
17066               tree fn;
17067
17068               if (!COMPLETE_TYPE_P (instantiation))
17069                 {
17070                   instantiate_class_template (instantiation);
17071                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
17072                     for (fn = TYPE_METHODS (instantiation);
17073                          fn;
17074                          fn = TREE_CHAIN (fn))
17075                       if (! DECL_ARTIFICIAL (fn))
17076                         instantiate_decl (fn,
17077                                           /*defer_ok=*/0,
17078                                           /*expl_inst_class_mem_p=*/false);
17079                   if (COMPLETE_TYPE_P (instantiation))
17080                     reconsider = 1;
17081                 }
17082
17083               complete = COMPLETE_TYPE_P (instantiation);
17084             }
17085           else
17086             {
17087               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
17088                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
17089                 {
17090                   instantiation
17091                     = instantiate_decl (instantiation,
17092                                         /*defer_ok=*/0,
17093                                         /*expl_inst_class_mem_p=*/false);
17094                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
17095                     reconsider = 1;
17096                 }
17097
17098               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
17099                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
17100             }
17101
17102           if (complete)
17103             /* If INSTANTIATION has been instantiated, then we don't
17104                need to consider it again in the future.  */
17105             *t = (*t)->next;
17106           else
17107             {
17108               last = *t;
17109               t = &(*t)->next;
17110             }
17111           tinst_depth = 0;
17112           current_tinst_level = NULL;
17113         }
17114       last_pending_template = last;
17115     }
17116   while (reconsider);
17117
17118   input_location = saved_loc;
17119 }
17120
17121 /* Substitute ARGVEC into T, which is a list of initializers for
17122    either base class or a non-static data member.  The TREE_PURPOSEs
17123    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17124    instantiate_decl.  */
17125
17126 static tree
17127 tsubst_initializer_list (tree t, tree argvec)
17128 {
17129   tree inits = NULL_TREE;
17130
17131   for (; t; t = TREE_CHAIN (t))
17132     {
17133       tree decl;
17134       tree init;
17135       tree expanded_bases = NULL_TREE;
17136       tree expanded_arguments = NULL_TREE;
17137       int i, len = 1;
17138
17139       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17140         {
17141           tree expr;
17142           tree arg;
17143
17144           /* Expand the base class expansion type into separate base
17145              classes.  */
17146           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17147                                                  tf_warning_or_error,
17148                                                  NULL_TREE);
17149           if (expanded_bases == error_mark_node)
17150             continue;
17151           
17152           /* We'll be building separate TREE_LISTs of arguments for
17153              each base.  */
17154           len = TREE_VEC_LENGTH (expanded_bases);
17155           expanded_arguments = make_tree_vec (len);
17156           for (i = 0; i < len; i++)
17157             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17158
17159           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17160              expand each argument in the TREE_VALUE of t.  */
17161           expr = make_node (EXPR_PACK_EXPANSION);
17162           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17163             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17164
17165           if (TREE_VALUE (t) == void_type_node)
17166             /* VOID_TYPE_NODE is used to indicate
17167                value-initialization.  */
17168             {
17169               for (i = 0; i < len; i++)
17170                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17171             }
17172           else
17173             {
17174               /* Substitute parameter packs into each argument in the
17175                  TREE_LIST.  */
17176               in_base_initializer = 1;
17177               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17178                 {
17179                   tree expanded_exprs;
17180
17181                   /* Expand the argument.  */
17182                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17183                   expanded_exprs 
17184                     = tsubst_pack_expansion (expr, argvec,
17185                                              tf_warning_or_error,
17186                                              NULL_TREE);
17187                   if (expanded_exprs == error_mark_node)
17188                     continue;
17189
17190                   /* Prepend each of the expanded expressions to the
17191                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17192                   for (i = 0; i < len; i++)
17193                     {
17194                       TREE_VEC_ELT (expanded_arguments, i) = 
17195                         tree_cons (NULL_TREE, 
17196                                    TREE_VEC_ELT (expanded_exprs, i),
17197                                    TREE_VEC_ELT (expanded_arguments, i));
17198                     }
17199                 }
17200               in_base_initializer = 0;
17201
17202               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17203                  since we built them backwards.  */
17204               for (i = 0; i < len; i++)
17205                 {
17206                   TREE_VEC_ELT (expanded_arguments, i) = 
17207                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17208                 }
17209             }
17210         }
17211
17212       for (i = 0; i < len; ++i)
17213         {
17214           if (expanded_bases)
17215             {
17216               decl = TREE_VEC_ELT (expanded_bases, i);
17217               decl = expand_member_init (decl);
17218               init = TREE_VEC_ELT (expanded_arguments, i);
17219             }
17220           else
17221             {
17222               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17223                                   tf_warning_or_error, NULL_TREE);
17224
17225               decl = expand_member_init (decl);
17226               if (decl && !DECL_P (decl))
17227                 in_base_initializer = 1;
17228
17229               init = tsubst_expr (TREE_VALUE (t), argvec, 
17230                                   tf_warning_or_error, NULL_TREE,
17231                                   /*integral_constant_expression_p=*/false);
17232               in_base_initializer = 0;
17233             }
17234
17235           if (decl)
17236             {
17237               init = build_tree_list (decl, init);
17238               TREE_CHAIN (init) = inits;
17239               inits = init;
17240             }
17241         }
17242     }
17243   return inits;
17244 }
17245
17246 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17247
17248 static void
17249 set_current_access_from_decl (tree decl)
17250 {
17251   if (TREE_PRIVATE (decl))
17252     current_access_specifier = access_private_node;
17253   else if (TREE_PROTECTED (decl))
17254     current_access_specifier = access_protected_node;
17255   else
17256     current_access_specifier = access_public_node;
17257 }
17258
17259 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17260    is the instantiation (which should have been created with
17261    start_enum) and ARGS are the template arguments to use.  */
17262
17263 static void
17264 tsubst_enum (tree tag, tree newtag, tree args)
17265 {
17266   tree e;
17267
17268   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17269     {
17270       tree value;
17271       tree decl;
17272
17273       decl = TREE_VALUE (e);
17274       /* Note that in a template enum, the TREE_VALUE is the
17275          CONST_DECL, not the corresponding INTEGER_CST.  */
17276       value = tsubst_expr (DECL_INITIAL (decl),
17277                            args, tf_warning_or_error, NULL_TREE,
17278                            /*integral_constant_expression_p=*/true);
17279
17280       /* Give this enumeration constant the correct access.  */
17281       set_current_access_from_decl (decl);
17282
17283       /* Actually build the enumerator itself.  */
17284       build_enumerator (DECL_NAME (decl), value, newtag);
17285     }
17286
17287   finish_enum (newtag);
17288   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17289     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17290 }
17291
17292 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17293    its type -- but without substituting the innermost set of template
17294    arguments.  So, innermost set of template parameters will appear in
17295    the type.  */
17296
17297 tree
17298 get_mostly_instantiated_function_type (tree decl)
17299 {
17300   tree fn_type;
17301   tree tmpl;
17302   tree targs;
17303   tree tparms;
17304   int parm_depth;
17305
17306   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17307   targs = DECL_TI_ARGS (decl);
17308   tparms = DECL_TEMPLATE_PARMS (tmpl);
17309   parm_depth = TMPL_PARMS_DEPTH (tparms);
17310
17311   /* There should be as many levels of arguments as there are levels
17312      of parameters.  */
17313   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17314
17315   fn_type = TREE_TYPE (tmpl);
17316
17317   if (parm_depth == 1)
17318     /* No substitution is necessary.  */
17319     ;
17320   else
17321     {
17322       int i, save_access_control;
17323       tree partial_args;
17324
17325       /* Replace the innermost level of the TARGS with NULL_TREEs to
17326          let tsubst know not to substitute for those parameters.  */
17327       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17328       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17329         SET_TMPL_ARGS_LEVEL (partial_args, i,
17330                              TMPL_ARGS_LEVEL (targs, i));
17331       SET_TMPL_ARGS_LEVEL (partial_args,
17332                            TMPL_ARGS_DEPTH (targs),
17333                            make_tree_vec (DECL_NTPARMS (tmpl)));
17334
17335       /* Disable access control as this function is used only during
17336          name-mangling.  */
17337       save_access_control = flag_access_control;
17338       flag_access_control = 0;
17339
17340       ++processing_template_decl;
17341       /* Now, do the (partial) substitution to figure out the
17342          appropriate function type.  */
17343       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17344       --processing_template_decl;
17345
17346       /* Substitute into the template parameters to obtain the real
17347          innermost set of parameters.  This step is important if the
17348          innermost set of template parameters contains value
17349          parameters whose types depend on outer template parameters.  */
17350       TREE_VEC_LENGTH (partial_args)--;
17351       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17352
17353       flag_access_control = save_access_control;
17354     }
17355
17356   return fn_type;
17357 }
17358
17359 /* Return truthvalue if we're processing a template different from
17360    the last one involved in diagnostics.  */
17361 int
17362 problematic_instantiation_changed (void)
17363 {
17364   return last_template_error_tick != tinst_level_tick;
17365 }
17366
17367 /* Remember current template involved in diagnostics.  */
17368 void
17369 record_last_problematic_instantiation (void)
17370 {
17371   last_template_error_tick = tinst_level_tick;
17372 }
17373
17374 struct tinst_level *
17375 current_instantiation (void)
17376 {
17377   return current_tinst_level;
17378 }
17379
17380 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17381    type. Return zero for ok, nonzero for disallowed. Issue error and
17382    warning messages under control of COMPLAIN.  */
17383
17384 static int
17385 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17386 {
17387   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17388     return 0;
17389   else if (POINTER_TYPE_P (type))
17390     return 0;
17391   else if (TYPE_PTR_TO_MEMBER_P (type))
17392     return 0;
17393   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17394     return 0;
17395   else if (TREE_CODE (type) == TYPENAME_TYPE)
17396     return 0;
17397
17398   if (complain & tf_error)
17399     error ("%q#T is not a valid type for a template constant parameter", type);
17400   return 1;
17401 }
17402
17403 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17404    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17405
17406 static bool
17407 dependent_type_p_r (tree type)
17408 {
17409   tree scope;
17410
17411   /* [temp.dep.type]
17412
17413      A type is dependent if it is:
17414
17415      -- a template parameter. Template template parameters are types
17416         for us (since TYPE_P holds true for them) so we handle
17417         them here.  */
17418   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17419       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17420     return true;
17421   /* -- a qualified-id with a nested-name-specifier which contains a
17422         class-name that names a dependent type or whose unqualified-id
17423         names a dependent type.  */
17424   if (TREE_CODE (type) == TYPENAME_TYPE)
17425     return true;
17426   /* -- a cv-qualified type where the cv-unqualified type is
17427         dependent.  */
17428   type = TYPE_MAIN_VARIANT (type);
17429   /* -- a compound type constructed from any dependent type.  */
17430   if (TYPE_PTR_TO_MEMBER_P (type))
17431     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17432             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17433                                            (type)));
17434   else if (TREE_CODE (type) == POINTER_TYPE
17435            || TREE_CODE (type) == REFERENCE_TYPE)
17436     return dependent_type_p (TREE_TYPE (type));
17437   else if (TREE_CODE (type) == FUNCTION_TYPE
17438            || TREE_CODE (type) == METHOD_TYPE)
17439     {
17440       tree arg_type;
17441
17442       if (dependent_type_p (TREE_TYPE (type)))
17443         return true;
17444       for (arg_type = TYPE_ARG_TYPES (type);
17445            arg_type;
17446            arg_type = TREE_CHAIN (arg_type))
17447         if (dependent_type_p (TREE_VALUE (arg_type)))
17448           return true;
17449       return false;
17450     }
17451   /* -- an array type constructed from any dependent type or whose
17452         size is specified by a constant expression that is
17453         value-dependent.  */
17454   if (TREE_CODE (type) == ARRAY_TYPE)
17455     {
17456       if (TYPE_DOMAIN (type)
17457           && dependent_type_p (TYPE_DOMAIN (type)))
17458         return true;
17459       return dependent_type_p (TREE_TYPE (type));
17460     }
17461   else if (TREE_CODE (type) == INTEGER_TYPE
17462            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17463     {
17464       /* If this is the TYPE_DOMAIN of an array type, consider it
17465          dependent.  We already checked for value-dependence in
17466          compute_array_index_type.  */
17467       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17468     }
17469
17470   /* -- a template-id in which either the template name is a template
17471      parameter ...  */
17472   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17473     return true;
17474   /* ... or any of the template arguments is a dependent type or
17475         an expression that is type-dependent or value-dependent.  */
17476   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17477            && (any_dependent_template_arguments_p
17478                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17479     return true;
17480
17481   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17482      argument of the `typeof' expression is not type-dependent, then
17483      it should already been have resolved.  */
17484   if (TREE_CODE (type) == TYPEOF_TYPE
17485       || TREE_CODE (type) == DECLTYPE_TYPE)
17486     return true;
17487
17488   /* A template argument pack is dependent if any of its packed
17489      arguments are.  */
17490   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17491     {
17492       tree args = ARGUMENT_PACK_ARGS (type);
17493       int i, len = TREE_VEC_LENGTH (args);
17494       for (i = 0; i < len; ++i)
17495         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17496           return true;
17497     }
17498
17499   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17500      be template parameters.  */
17501   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17502     return true;
17503
17504   /* The standard does not specifically mention types that are local
17505      to template functions or local classes, but they should be
17506      considered dependent too.  For example:
17507
17508        template <int I> void f() {
17509          enum E { a = I };
17510          S<sizeof (E)> s;
17511        }
17512
17513      The size of `E' cannot be known until the value of `I' has been
17514      determined.  Therefore, `E' must be considered dependent.  */
17515   scope = TYPE_CONTEXT (type);
17516   if (scope && TYPE_P (scope))
17517     return dependent_type_p (scope);
17518   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17519     return type_dependent_expression_p (scope);
17520
17521   /* Other types are non-dependent.  */
17522   return false;
17523 }
17524
17525 /* Returns TRUE if TYPE is dependent, in the sense of
17526    [temp.dep.type].  */
17527
17528 bool
17529 dependent_type_p (tree type)
17530 {
17531   /* If there are no template parameters in scope, then there can't be
17532      any dependent types.  */
17533   if (!processing_template_decl)
17534     {
17535       /* If we are not processing a template, then nobody should be
17536          providing us with a dependent type.  */
17537       gcc_assert (type);
17538       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17539       return false;
17540     }
17541
17542   /* If the type is NULL, we have not computed a type for the entity
17543      in question; in that case, the type is dependent.  */
17544   if (!type)
17545     return true;
17546
17547   /* Erroneous types can be considered non-dependent.  */
17548   if (type == error_mark_node)
17549     return false;
17550
17551   /* If we have not already computed the appropriate value for TYPE,
17552      do so now.  */
17553   if (!TYPE_DEPENDENT_P_VALID (type))
17554     {
17555       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17556       TYPE_DEPENDENT_P_VALID (type) = 1;
17557     }
17558
17559   return TYPE_DEPENDENT_P (type);
17560 }
17561
17562 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17563    lookup.  In other words, a dependent type that is not the current
17564    instantiation.  */
17565
17566 bool
17567 dependent_scope_p (tree scope)
17568 {
17569   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17570           && !currently_open_class (scope));
17571 }
17572
17573 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17574    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17575    expression.  */
17576
17577 bool
17578 value_dependent_expression_p (tree expression)
17579 {
17580   if (!processing_template_decl)
17581     return false;
17582
17583   /* A name declared with a dependent type.  */
17584   if (DECL_P (expression) && type_dependent_expression_p (expression))
17585     return true;
17586
17587   switch (TREE_CODE (expression))
17588     {
17589     case IDENTIFIER_NODE:
17590       /* A name that has not been looked up -- must be dependent.  */
17591       return true;
17592
17593     case TEMPLATE_PARM_INDEX:
17594       /* A non-type template parm.  */
17595       return true;
17596
17597     case CONST_DECL:
17598       /* A non-type template parm.  */
17599       if (DECL_TEMPLATE_PARM_P (expression))
17600         return true;
17601       return value_dependent_expression_p (DECL_INITIAL (expression));
17602
17603     case VAR_DECL:
17604        /* A constant with integral or enumeration type and is initialized
17605           with an expression that is value-dependent.  */
17606       if (DECL_INITIAL (expression)
17607           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17608           && value_dependent_expression_p (DECL_INITIAL (expression)))
17609         return true;
17610       return false;
17611
17612     case DYNAMIC_CAST_EXPR:
17613     case STATIC_CAST_EXPR:
17614     case CONST_CAST_EXPR:
17615     case REINTERPRET_CAST_EXPR:
17616     case CAST_EXPR:
17617       /* These expressions are value-dependent if the type to which
17618          the cast occurs is dependent or the expression being casted
17619          is value-dependent.  */
17620       {
17621         tree type = TREE_TYPE (expression);
17622
17623         if (dependent_type_p (type))
17624           return true;
17625
17626         /* A functional cast has a list of operands.  */
17627         expression = TREE_OPERAND (expression, 0);
17628         if (!expression)
17629           {
17630             /* If there are no operands, it must be an expression such
17631                as "int()". This should not happen for aggregate types
17632                because it would form non-constant expressions.  */
17633             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17634
17635             return false;
17636           }
17637
17638         if (TREE_CODE (expression) == TREE_LIST)
17639           return any_value_dependent_elements_p (expression);
17640
17641         return value_dependent_expression_p (expression);
17642       }
17643
17644     case SIZEOF_EXPR:
17645     case ALIGNOF_EXPR:
17646       /* A `sizeof' expression is value-dependent if the operand is
17647          type-dependent or is a pack expansion.  */
17648       expression = TREE_OPERAND (expression, 0);
17649       if (PACK_EXPANSION_P (expression))
17650         return true;
17651       else if (TYPE_P (expression))
17652         return dependent_type_p (expression);
17653       return type_dependent_expression_p (expression);
17654
17655     case NOEXCEPT_EXPR:
17656       expression = TREE_OPERAND (expression, 0);
17657       /* FIXME why check value-dependency?  */
17658       return (type_dependent_expression_p (expression)
17659               || value_dependent_expression_p (expression));
17660
17661     case SCOPE_REF:
17662       {
17663         tree name = TREE_OPERAND (expression, 1);
17664         return value_dependent_expression_p (name);
17665       }
17666
17667     case COMPONENT_REF:
17668       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17669               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17670
17671     case CALL_EXPR:
17672       /* A CALL_EXPR may appear in a constant expression if it is a
17673          call to a builtin function, e.g., __builtin_constant_p.  All
17674          such calls are value-dependent.  */
17675       return true;
17676
17677     case NONTYPE_ARGUMENT_PACK:
17678       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17679          is value-dependent.  */
17680       {
17681         tree values = ARGUMENT_PACK_ARGS (expression);
17682         int i, len = TREE_VEC_LENGTH (values);
17683         
17684         for (i = 0; i < len; ++i)
17685           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17686             return true;
17687         
17688         return false;
17689       }
17690
17691     case TRAIT_EXPR:
17692       {
17693         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17694         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17695                 || (type2 ? dependent_type_p (type2) : false));
17696       }
17697
17698     case MODOP_EXPR:
17699       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17700               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17701
17702     case ADDR_EXPR:
17703       {
17704         tree op = TREE_OPERAND (expression, 0);
17705         return (value_dependent_expression_p (op)
17706                 || has_value_dependent_address (op));
17707       }
17708
17709     default:
17710       /* A constant expression is value-dependent if any subexpression is
17711          value-dependent.  */
17712       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17713         {
17714         case tcc_reference:
17715         case tcc_unary:
17716           return (value_dependent_expression_p
17717                   (TREE_OPERAND (expression, 0)));
17718
17719         case tcc_comparison:
17720         case tcc_binary:
17721           return ((value_dependent_expression_p
17722                    (TREE_OPERAND (expression, 0)))
17723                   || (value_dependent_expression_p
17724                       (TREE_OPERAND (expression, 1))));
17725
17726         case tcc_expression:
17727         case tcc_vl_exp:
17728           {
17729             int i;
17730             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17731               /* In some cases, some of the operands may be missing.
17732                  (For example, in the case of PREDECREMENT_EXPR, the
17733                  amount to increment by may be missing.)  That doesn't
17734                  make the expression dependent.  */
17735               if (TREE_OPERAND (expression, i)
17736                   && (value_dependent_expression_p
17737                       (TREE_OPERAND (expression, i))))
17738                 return true;
17739             return false;
17740           }
17741
17742         default:
17743           break;
17744         }
17745     }
17746
17747   /* The expression is not value-dependent.  */
17748   return false;
17749 }
17750
17751 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17752    [temp.dep.expr].  */
17753
17754 bool
17755 type_dependent_expression_p (tree expression)
17756 {
17757   if (!processing_template_decl)
17758     return false;
17759
17760   if (expression == error_mark_node)
17761     return false;
17762
17763   /* An unresolved name is always dependent.  */
17764   if (TREE_CODE (expression) == IDENTIFIER_NODE
17765       || TREE_CODE (expression) == USING_DECL)
17766     return true;
17767
17768   /* Some expression forms are never type-dependent.  */
17769   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17770       || TREE_CODE (expression) == SIZEOF_EXPR
17771       || TREE_CODE (expression) == ALIGNOF_EXPR
17772       || TREE_CODE (expression) == NOEXCEPT_EXPR
17773       || TREE_CODE (expression) == TRAIT_EXPR
17774       || TREE_CODE (expression) == TYPEID_EXPR
17775       || TREE_CODE (expression) == DELETE_EXPR
17776       || TREE_CODE (expression) == VEC_DELETE_EXPR
17777       || TREE_CODE (expression) == THROW_EXPR)
17778     return false;
17779
17780   /* The types of these expressions depends only on the type to which
17781      the cast occurs.  */
17782   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17783       || TREE_CODE (expression) == STATIC_CAST_EXPR
17784       || TREE_CODE (expression) == CONST_CAST_EXPR
17785       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17786       || TREE_CODE (expression) == CAST_EXPR)
17787     return dependent_type_p (TREE_TYPE (expression));
17788
17789   /* The types of these expressions depends only on the type created
17790      by the expression.  */
17791   if (TREE_CODE (expression) == NEW_EXPR
17792       || TREE_CODE (expression) == VEC_NEW_EXPR)
17793     {
17794       /* For NEW_EXPR tree nodes created inside a template, either
17795          the object type itself or a TREE_LIST may appear as the
17796          operand 1.  */
17797       tree type = TREE_OPERAND (expression, 1);
17798       if (TREE_CODE (type) == TREE_LIST)
17799         /* This is an array type.  We need to check array dimensions
17800            as well.  */
17801         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17802                || value_dependent_expression_p
17803                     (TREE_OPERAND (TREE_VALUE (type), 1));
17804       else
17805         return dependent_type_p (type);
17806     }
17807
17808   if (TREE_CODE (expression) == SCOPE_REF)
17809     {
17810       tree scope = TREE_OPERAND (expression, 0);
17811       tree name = TREE_OPERAND (expression, 1);
17812
17813       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
17814          contains an identifier associated by name lookup with one or more
17815          declarations declared with a dependent type, or...a
17816          nested-name-specifier or qualified-id that names a member of an
17817          unknown specialization.  */
17818       return (type_dependent_expression_p (name)
17819               || dependent_scope_p (scope));
17820     }
17821
17822   if (TREE_CODE (expression) == FUNCTION_DECL
17823       && DECL_LANG_SPECIFIC (expression)
17824       && DECL_TEMPLATE_INFO (expression)
17825       && (any_dependent_template_arguments_p
17826           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17827     return true;
17828
17829   if (TREE_CODE (expression) == TEMPLATE_DECL
17830       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17831     return false;
17832
17833   if (TREE_CODE (expression) == STMT_EXPR)
17834     expression = stmt_expr_value_expr (expression);
17835
17836   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17837     {
17838       tree elt;
17839       unsigned i;
17840
17841       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17842         {
17843           if (type_dependent_expression_p (elt))
17844             return true;
17845         }
17846       return false;
17847     }
17848
17849   /* A static data member of the current instantiation with incomplete
17850      array type is type-dependent, as the definition and specializations
17851      can have different bounds.  */
17852   if (TREE_CODE (expression) == VAR_DECL
17853       && DECL_CLASS_SCOPE_P (expression)
17854       && dependent_type_p (DECL_CONTEXT (expression))
17855       && VAR_HAD_UNKNOWN_BOUND (expression))
17856     return true;
17857
17858   if (TREE_TYPE (expression) == unknown_type_node)
17859     {
17860       if (TREE_CODE (expression) == ADDR_EXPR)
17861         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17862       if (TREE_CODE (expression) == COMPONENT_REF
17863           || TREE_CODE (expression) == OFFSET_REF)
17864         {
17865           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17866             return true;
17867           expression = TREE_OPERAND (expression, 1);
17868           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17869             return false;
17870         }
17871       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17872       if (TREE_CODE (expression) == SCOPE_REF)
17873         return false;
17874
17875       if (TREE_CODE (expression) == BASELINK)
17876         expression = BASELINK_FUNCTIONS (expression);
17877
17878       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17879         {
17880           if (any_dependent_template_arguments_p
17881               (TREE_OPERAND (expression, 1)))
17882             return true;
17883           expression = TREE_OPERAND (expression, 0);
17884         }
17885       gcc_assert (TREE_CODE (expression) == OVERLOAD
17886                   || TREE_CODE (expression) == FUNCTION_DECL);
17887
17888       while (expression)
17889         {
17890           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17891             return true;
17892           expression = OVL_NEXT (expression);
17893         }
17894       return false;
17895     }
17896
17897   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17898
17899   return (dependent_type_p (TREE_TYPE (expression)));
17900 }
17901
17902 /* Like type_dependent_expression_p, but it also works while not processing
17903    a template definition, i.e. during substitution or mangling.  */
17904
17905 bool
17906 type_dependent_expression_p_push (tree expr)
17907 {
17908   bool b;
17909   ++processing_template_decl;
17910   b = type_dependent_expression_p (expr);
17911   --processing_template_decl;
17912   return b;
17913 }
17914
17915 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17916
17917 bool
17918 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17919 {
17920   unsigned int i;
17921   tree arg;
17922
17923   FOR_EACH_VEC_ELT (tree, args, i, arg)
17924     {
17925       if (type_dependent_expression_p (arg))
17926         return true;
17927     }
17928   return false;
17929 }
17930
17931 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17932    expressions) contains any value-dependent expressions.  */
17933
17934 bool
17935 any_value_dependent_elements_p (const_tree list)
17936 {
17937   for (; list; list = TREE_CHAIN (list))
17938     if (value_dependent_expression_p (TREE_VALUE (list)))
17939       return true;
17940
17941   return false;
17942 }
17943
17944 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17945
17946 bool
17947 dependent_template_arg_p (tree arg)
17948 {
17949   if (!processing_template_decl)
17950     return false;
17951
17952   if (TREE_CODE (arg) == TEMPLATE_DECL
17953       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17954     return dependent_template_p (arg);
17955   else if (ARGUMENT_PACK_P (arg))
17956     {
17957       tree args = ARGUMENT_PACK_ARGS (arg);
17958       int i, len = TREE_VEC_LENGTH (args);
17959       for (i = 0; i < len; ++i)
17960         {
17961           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17962             return true;
17963         }
17964
17965       return false;
17966     }
17967   else if (TYPE_P (arg))
17968     return dependent_type_p (arg);
17969   else
17970     return (type_dependent_expression_p (arg)
17971             || value_dependent_expression_p (arg));
17972 }
17973
17974 /* Returns true if ARGS (a collection of template arguments) contains
17975    any types that require structural equality testing.  */
17976
17977 bool
17978 any_template_arguments_need_structural_equality_p (tree args)
17979 {
17980   int i;
17981   int j;
17982
17983   if (!args)
17984     return false;
17985   if (args == error_mark_node)
17986     return true;
17987
17988   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17989     {
17990       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17991       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17992         {
17993           tree arg = TREE_VEC_ELT (level, j);
17994           tree packed_args = NULL_TREE;
17995           int k, len = 1;
17996
17997           if (ARGUMENT_PACK_P (arg))
17998             {
17999               /* Look inside the argument pack.  */
18000               packed_args = ARGUMENT_PACK_ARGS (arg);
18001               len = TREE_VEC_LENGTH (packed_args);
18002             }
18003
18004           for (k = 0; k < len; ++k)
18005             {
18006               if (packed_args)
18007                 arg = TREE_VEC_ELT (packed_args, k);
18008
18009               if (error_operand_p (arg))
18010                 return true;
18011               else if (TREE_CODE (arg) == TEMPLATE_DECL
18012                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18013                 continue;
18014               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
18015                 return true;
18016               else if (!TYPE_P (arg) && TREE_TYPE (arg)
18017                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
18018                 return true;
18019             }
18020         }
18021     }
18022
18023   return false;
18024 }
18025
18026 /* Returns true if ARGS (a collection of template arguments) contains
18027    any dependent arguments.  */
18028
18029 bool
18030 any_dependent_template_arguments_p (const_tree args)
18031 {
18032   int i;
18033   int j;
18034
18035   if (!args)
18036     return false;
18037   if (args == error_mark_node)
18038     return true;
18039
18040   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18041     {
18042       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
18043       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18044         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
18045           return true;
18046     }
18047
18048   return false;
18049 }
18050
18051 /* Returns TRUE if the template TMPL is dependent.  */
18052
18053 bool
18054 dependent_template_p (tree tmpl)
18055 {
18056   if (TREE_CODE (tmpl) == OVERLOAD)
18057     {
18058       while (tmpl)
18059         {
18060           if (dependent_template_p (OVL_FUNCTION (tmpl)))
18061             return true;
18062           tmpl = OVL_CHAIN (tmpl);
18063         }
18064       return false;
18065     }
18066
18067   /* Template template parameters are dependent.  */
18068   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
18069       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
18070     return true;
18071   /* So are names that have not been looked up.  */
18072   if (TREE_CODE (tmpl) == SCOPE_REF
18073       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
18074     return true;
18075   /* So are member templates of dependent classes.  */
18076   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
18077     return dependent_type_p (DECL_CONTEXT (tmpl));
18078   return false;
18079 }
18080
18081 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
18082
18083 bool
18084 dependent_template_id_p (tree tmpl, tree args)
18085 {
18086   return (dependent_template_p (tmpl)
18087           || any_dependent_template_arguments_p (args));
18088 }
18089
18090 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
18091    is dependent.  */
18092
18093 bool
18094 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
18095 {
18096   int i;
18097
18098   if (!processing_template_decl)
18099     return false;
18100
18101   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
18102     {
18103       tree decl = TREE_VEC_ELT (declv, i);
18104       tree init = TREE_VEC_ELT (initv, i);
18105       tree cond = TREE_VEC_ELT (condv, i);
18106       tree incr = TREE_VEC_ELT (incrv, i);
18107
18108       if (type_dependent_expression_p (decl))
18109         return true;
18110
18111       if (init && type_dependent_expression_p (init))
18112         return true;
18113
18114       if (type_dependent_expression_p (cond))
18115         return true;
18116
18117       if (COMPARISON_CLASS_P (cond)
18118           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
18119               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
18120         return true;
18121
18122       if (TREE_CODE (incr) == MODOP_EXPR)
18123         {
18124           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18125               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18126             return true;
18127         }
18128       else if (type_dependent_expression_p (incr))
18129         return true;
18130       else if (TREE_CODE (incr) == MODIFY_EXPR)
18131         {
18132           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18133             return true;
18134           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18135             {
18136               tree t = TREE_OPERAND (incr, 1);
18137               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18138                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18139                 return true;
18140             }
18141         }
18142     }
18143
18144   return false;
18145 }
18146
18147 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18148    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18149    no such TYPE can be found.  Note that this function peers inside
18150    uninstantiated templates and therefore should be used only in
18151    extremely limited situations.  ONLY_CURRENT_P restricts this
18152    peering to the currently open classes hierarchy (which is required
18153    when comparing types).  */
18154
18155 tree
18156 resolve_typename_type (tree type, bool only_current_p)
18157 {
18158   tree scope;
18159   tree name;
18160   tree decl;
18161   int quals;
18162   tree pushed_scope;
18163   tree result;
18164
18165   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18166
18167   scope = TYPE_CONTEXT (type);
18168   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18169      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18170      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18171      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18172      identifier  of the TYPENAME_TYPE anymore.
18173      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18174      TYPENAME_TYPE instead, we avoid messing up with a possible
18175      typedef variant case.  */
18176   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18177
18178   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18179      it first before we can figure out what NAME refers to.  */
18180   if (TREE_CODE (scope) == TYPENAME_TYPE)
18181     scope = resolve_typename_type (scope, only_current_p);
18182   /* If we don't know what SCOPE refers to, then we cannot resolve the
18183      TYPENAME_TYPE.  */
18184   if (TREE_CODE (scope) == TYPENAME_TYPE)
18185     return type;
18186   /* If the SCOPE is a template type parameter, we have no way of
18187      resolving the name.  */
18188   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18189     return type;
18190   /* If the SCOPE is not the current instantiation, there's no reason
18191      to look inside it.  */
18192   if (only_current_p && !currently_open_class (scope))
18193     return type;
18194   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18195   if (typedef_variant_p (type))
18196     return type;
18197   /* If SCOPE isn't the template itself, it will not have a valid
18198      TYPE_FIELDS list.  */
18199   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18200     /* scope is either the template itself or a compatible instantiation
18201        like X<T>, so look up the name in the original template.  */
18202     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18203   else
18204     /* scope is a partial instantiation, so we can't do the lookup or we
18205        will lose the template arguments.  */
18206     return type;
18207   /* Enter the SCOPE so that name lookup will be resolved as if we
18208      were in the class definition.  In particular, SCOPE will no
18209      longer be considered a dependent type.  */
18210   pushed_scope = push_scope (scope);
18211   /* Look up the declaration.  */
18212   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18213
18214   result = NULL_TREE;
18215   
18216   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18217      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18218   if (!decl)
18219     /*nop*/;
18220   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18221            && TREE_CODE (decl) == TYPE_DECL)
18222     {
18223       result = TREE_TYPE (decl);
18224       if (result == error_mark_node)
18225         result = NULL_TREE;
18226     }
18227   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18228            && DECL_CLASS_TEMPLATE_P (decl))
18229     {
18230       tree tmpl;
18231       tree args;
18232       /* Obtain the template and the arguments.  */
18233       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18234       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18235       /* Instantiate the template.  */
18236       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18237                                       /*entering_scope=*/0,
18238                                       tf_error | tf_user);
18239       if (result == error_mark_node)
18240         result = NULL_TREE;
18241     }
18242   
18243   /* Leave the SCOPE.  */
18244   if (pushed_scope)
18245     pop_scope (pushed_scope);
18246
18247   /* If we failed to resolve it, return the original typename.  */
18248   if (!result)
18249     return type;
18250   
18251   /* If lookup found a typename type, resolve that too.  */
18252   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18253     {
18254       /* Ill-formed programs can cause infinite recursion here, so we
18255          must catch that.  */
18256       TYPENAME_IS_RESOLVING_P (type) = 1;
18257       result = resolve_typename_type (result, only_current_p);
18258       TYPENAME_IS_RESOLVING_P (type) = 0;
18259     }
18260   
18261   /* Qualify the resulting type.  */
18262   quals = cp_type_quals (type);
18263   if (quals)
18264     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18265
18266   return result;
18267 }
18268
18269 /* EXPR is an expression which is not type-dependent.  Return a proxy
18270    for EXPR that can be used to compute the types of larger
18271    expressions containing EXPR.  */
18272
18273 tree
18274 build_non_dependent_expr (tree expr)
18275 {
18276   tree inner_expr;
18277
18278   /* Preserve null pointer constants so that the type of things like
18279      "p == 0" where "p" is a pointer can be determined.  */
18280   if (null_ptr_cst_p (expr))
18281     return expr;
18282   /* Preserve OVERLOADs; the functions must be available to resolve
18283      types.  */
18284   inner_expr = expr;
18285   if (TREE_CODE (inner_expr) == STMT_EXPR)
18286     inner_expr = stmt_expr_value_expr (inner_expr);
18287   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18288     inner_expr = TREE_OPERAND (inner_expr, 0);
18289   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18290     inner_expr = TREE_OPERAND (inner_expr, 1);
18291   if (is_overloaded_fn (inner_expr)
18292       || TREE_CODE (inner_expr) == OFFSET_REF)
18293     return expr;
18294   /* There is no need to return a proxy for a variable.  */
18295   if (TREE_CODE (expr) == VAR_DECL)
18296     return expr;
18297   /* Preserve string constants; conversions from string constants to
18298      "char *" are allowed, even though normally a "const char *"
18299      cannot be used to initialize a "char *".  */
18300   if (TREE_CODE (expr) == STRING_CST)
18301     return expr;
18302   /* Preserve arithmetic constants, as an optimization -- there is no
18303      reason to create a new node.  */
18304   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18305     return expr;
18306   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18307      There is at least one place where we want to know that a
18308      particular expression is a throw-expression: when checking a ?:
18309      expression, there are special rules if the second or third
18310      argument is a throw-expression.  */
18311   if (TREE_CODE (expr) == THROW_EXPR)
18312     return expr;
18313
18314   if (TREE_CODE (expr) == COND_EXPR)
18315     return build3 (COND_EXPR,
18316                    TREE_TYPE (expr),
18317                    TREE_OPERAND (expr, 0),
18318                    (TREE_OPERAND (expr, 1)
18319                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18320                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18321                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18322   if (TREE_CODE (expr) == COMPOUND_EXPR
18323       && !COMPOUND_EXPR_OVERLOADED (expr))
18324     return build2 (COMPOUND_EXPR,
18325                    TREE_TYPE (expr),
18326                    TREE_OPERAND (expr, 0),
18327                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18328
18329   /* If the type is unknown, it can't really be non-dependent */
18330   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18331
18332   /* Otherwise, build a NON_DEPENDENT_EXPR.
18333
18334      REFERENCE_TYPEs are not stripped for expressions in templates
18335      because doing so would play havoc with mangling.  Consider, for
18336      example:
18337
18338        template <typename T> void f<T& g>() { g(); }
18339
18340      In the body of "f", the expression for "g" will have
18341      REFERENCE_TYPE, even though the standard says that it should
18342      not.  The reason is that we must preserve the syntactic form of
18343      the expression so that mangling (say) "f<g>" inside the body of
18344      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18345      stripped here.  */
18346   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18347 }
18348
18349 /* ARGS is a vector of expressions as arguments to a function call.
18350    Replace the arguments with equivalent non-dependent expressions.
18351    This modifies ARGS in place.  */
18352
18353 void
18354 make_args_non_dependent (VEC(tree,gc) *args)
18355 {
18356   unsigned int ix;
18357   tree arg;
18358
18359   FOR_EACH_VEC_ELT (tree, args, ix, arg)
18360     {
18361       tree newarg = build_non_dependent_expr (arg);
18362       if (newarg != arg)
18363         VEC_replace (tree, args, ix, newarg);
18364     }
18365 }
18366
18367 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18368    with a level one deeper than the actual template parms.  */
18369
18370 tree
18371 make_auto (void)
18372 {
18373   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18374   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18375                                TYPE_DECL, get_identifier ("auto"), au);
18376   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18377   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18378     (0, processing_template_decl + 1, processing_template_decl + 1,
18379      TYPE_NAME (au), NULL_TREE);
18380   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18381   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18382   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18383
18384   return au;
18385 }
18386
18387 /* Given type ARG, return std::initializer_list<ARG>.  */
18388
18389 static tree
18390 listify (tree arg)
18391 {
18392   tree std_init_list = namespace_binding
18393     (get_identifier ("initializer_list"), std_node);
18394   tree argvec;
18395   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18396     {    
18397       error ("deducing from brace-enclosed initializer list requires "
18398              "#include <initializer_list>");
18399       return error_mark_node;
18400     }
18401   argvec = make_tree_vec (1);
18402   TREE_VEC_ELT (argvec, 0) = arg;
18403   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18404                                 NULL_TREE, 0, tf_warning_or_error);
18405 }
18406
18407 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18408
18409 static tree
18410 listify_autos (tree type, tree auto_node)
18411 {
18412   tree init_auto = listify (auto_node);
18413   tree argvec = make_tree_vec (1);
18414   TREE_VEC_ELT (argvec, 0) = init_auto;
18415   if (processing_template_decl)
18416     argvec = add_to_template_args (current_template_args (), argvec);
18417   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18418 }
18419
18420 /* walk_tree helper for do_auto_deduction.  */
18421
18422 static tree
18423 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
18424                  void *type)
18425 {
18426   /* Is this a variable with the type we're looking for?  */
18427   if (DECL_P (*tp)
18428       && TREE_TYPE (*tp) == type)
18429     return *tp;
18430   else
18431     return NULL_TREE;
18432 }
18433
18434 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18435    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18436
18437 tree
18438 do_auto_deduction (tree type, tree init, tree auto_node)
18439 {
18440   tree parms, tparms, targs;
18441   tree args[1];
18442   tree decl;
18443   int val;
18444
18445   /* The name of the object being declared shall not appear in the
18446      initializer expression.  */
18447   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
18448   if (decl)
18449     {
18450       error ("variable %q#D with %<auto%> type used in its own "
18451              "initializer", decl);
18452       return error_mark_node;
18453     }
18454
18455   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18456      with either a new invented type template parameter U or, if the
18457      initializer is a braced-init-list (8.5.4), with
18458      std::initializer_list<U>.  */
18459   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18460     type = listify_autos (type, auto_node);
18461
18462   parms = build_tree_list (NULL_TREE, type);
18463   args[0] = init;
18464   tparms = make_tree_vec (1);
18465   targs = make_tree_vec (1);
18466   TREE_VEC_ELT (tparms, 0)
18467     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18468   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18469                                DEDUCE_CALL, LOOKUP_NORMAL);
18470   if (val > 0)
18471     {
18472       error ("unable to deduce %qT from %qE", type, init);
18473       return error_mark_node;
18474     }
18475
18476   /* If the list of declarators contains more than one declarator, the type
18477      of each declared variable is determined as described above. If the
18478      type deduced for the template parameter U is not the same in each
18479      deduction, the program is ill-formed.  */
18480   if (TREE_TYPE (auto_node)
18481       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18482     {
18483       error ("inconsistent deduction for %qT: %qT and then %qT",
18484              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18485       return error_mark_node;
18486     }
18487   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18488
18489   if (processing_template_decl)
18490     targs = add_to_template_args (current_template_args (), targs);
18491   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18492 }
18493
18494 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18495    result.  */
18496
18497 tree
18498 splice_late_return_type (tree type, tree late_return_type)
18499 {
18500   tree argvec;
18501
18502   if (late_return_type == NULL_TREE)
18503     return type;
18504   argvec = make_tree_vec (1);
18505   TREE_VEC_ELT (argvec, 0) = late_return_type;
18506   if (processing_template_decl)
18507     argvec = add_to_template_args (current_template_args (), argvec);
18508   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18509 }
18510
18511 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18512
18513 bool
18514 is_auto (const_tree type)
18515 {
18516   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18517       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18518     return true;
18519   else
18520     return false;
18521 }
18522
18523 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18524    appear as a type-specifier for the declaration in question, we don't
18525    have to look through the whole type.  */
18526
18527 tree
18528 type_uses_auto (tree type)
18529 {
18530   enum tree_code code;
18531   if (is_auto (type))
18532     return type;
18533
18534   code = TREE_CODE (type);
18535
18536   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18537       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18538       || code == METHOD_TYPE || code == ARRAY_TYPE)
18539     return type_uses_auto (TREE_TYPE (type));
18540
18541   if (TYPE_PTRMEMFUNC_P (type))
18542     return type_uses_auto (TREE_TYPE (TREE_TYPE
18543                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18544
18545   return NULL_TREE;
18546 }
18547
18548 /* For a given template T, return the vector of typedefs referenced
18549    in T for which access check is needed at T instantiation time.
18550    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18551    Those typedefs were added to T by the function
18552    append_type_to_template_for_access_check.  */
18553
18554 VEC(qualified_typedef_usage_t,gc)*
18555 get_types_needing_access_check (tree t)
18556 {
18557   tree ti;
18558   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18559
18560   if (!t || t == error_mark_node)
18561     return NULL;
18562
18563   if (!(ti = get_template_info (t)))
18564     return NULL;
18565
18566   if (CLASS_TYPE_P (t)
18567       || TREE_CODE (t) == FUNCTION_DECL)
18568     {
18569       if (!TI_TEMPLATE (ti))
18570         return NULL;
18571
18572       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18573     }
18574
18575   return result;
18576 }
18577
18578 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18579    tied to T. That list of typedefs will be access checked at
18580    T instantiation time.
18581    T is either a FUNCTION_DECL or a RECORD_TYPE.
18582    TYPE_DECL is a TYPE_DECL node representing a typedef.
18583    SCOPE is the scope through which TYPE_DECL is accessed.
18584    LOCATION is the location of the usage point of TYPE_DECL.
18585
18586    This function is a subroutine of
18587    append_type_to_template_for_access_check.  */
18588
18589 static void
18590 append_type_to_template_for_access_check_1 (tree t,
18591                                             tree type_decl,
18592                                             tree scope,
18593                                             location_t location)
18594 {
18595   qualified_typedef_usage_t typedef_usage;
18596   tree ti;
18597
18598   if (!t || t == error_mark_node)
18599     return;
18600
18601   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18602                || CLASS_TYPE_P (t))
18603               && type_decl
18604               && TREE_CODE (type_decl) == TYPE_DECL
18605               && scope);
18606
18607   if (!(ti = get_template_info (t)))
18608     return;
18609
18610   gcc_assert (TI_TEMPLATE (ti));
18611
18612   typedef_usage.typedef_decl = type_decl;
18613   typedef_usage.context = scope;
18614   typedef_usage.locus = location;
18615
18616   VEC_safe_push (qualified_typedef_usage_t, gc,
18617                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18618                  &typedef_usage);
18619 }
18620
18621 /* Append TYPE_DECL to the template TEMPL.
18622    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18623    At TEMPL instanciation time, TYPE_DECL will be checked to see
18624    if it can be accessed through SCOPE.
18625    LOCATION is the location of the usage point of TYPE_DECL.
18626
18627    e.g. consider the following code snippet:
18628
18629      class C
18630      {
18631        typedef int myint;
18632      };
18633
18634      template<class U> struct S
18635      {
18636        C::myint mi; // <-- usage point of the typedef C::myint
18637      };
18638
18639      S<char> s;
18640
18641    At S<char> instantiation time, we need to check the access of C::myint
18642    In other words, we need to check the access of the myint typedef through
18643    the C scope. For that purpose, this function will add the myint typedef
18644    and the scope C through which its being accessed to a list of typedefs
18645    tied to the template S. That list will be walked at template instantiation
18646    time and access check performed on each typedefs it contains.
18647    Note that this particular code snippet should yield an error because
18648    myint is private to C.  */
18649
18650 void
18651 append_type_to_template_for_access_check (tree templ,
18652                                           tree type_decl,
18653                                           tree scope,
18654                                           location_t location)
18655 {
18656   qualified_typedef_usage_t *iter;
18657   int i;
18658
18659   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18660
18661   /* Make sure we don't append the type to the template twice.  */
18662   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
18663                     get_types_needing_access_check (templ),
18664                     i, iter)
18665     if (iter->typedef_decl == type_decl && scope == iter->context)
18666       return;
18667
18668   append_type_to_template_for_access_check_1 (templ, type_decl,
18669                                               scope, location);
18670 }
18671
18672 /* Set up the hash tables for template instantiations.  */
18673
18674 void
18675 init_template_processing (void)
18676 {
18677   decl_specializations = htab_create_ggc (37,
18678                                           hash_specialization,
18679                                           eq_specializations,
18680                                           ggc_free);
18681   type_specializations = htab_create_ggc (37,
18682                                           hash_specialization,
18683                                           eq_specializations,
18684                                           ggc_free);
18685 }
18686
18687 /* Print stats about the template hash tables for -fstats.  */
18688
18689 void
18690 print_template_statistics (void)
18691 {
18692   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
18693            "%f collisions\n", (long) htab_size (decl_specializations),
18694            (long) htab_elements (decl_specializations),
18695            htab_collisions (decl_specializations));
18696   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
18697            "%f collisions\n", (long) htab_size (type_specializations),
18698            (long) htab_elements (type_specializations),
18699            htab_collisions (type_specializations));
18700 }
18701
18702 #include "gt-cp-pt.h"